text:
Q: Howto resolve a function name conflict when compiling a kernel module I'm trying to compile a 3rd party kernel module for RHEL 5.6 and it is failing due to function name conflicts with mutex_acquire and mutex_release.  This kernel module compiles cleanly on RHEL 4.7 so something changed between kernels 2.6.9 and 2.6.18.  Sadly, this kernel module is no longer supported by the vendor but I do have the source code for mutex.c and mutex.h which define these functions.  Unfortunately there is an object file nivxi.o upon which no source code is distributed and this object file is calling mutex_acquire and mutex_release so I cannot just simply alter their names.
As an aside, I originally attempted to just modify the names slightly and the compile errors went away but when it went to make the .ko kernel module it complained that it couldn't find mutex_acquire or mutex_release; presumably due to nivxi.o
How do I force the compiler/linker to use the function definitions in my local .c/.h files even though they trounce over like-named functions elsewhere?
mutex.h
NIVXICC void mutex_acquire(mutex_t *mutex);
NIVXICC void mutex_release(mutex_t *mutex);

nivxicc.h (just incase this is pertinent)
#ifndef NIVXICC_H
#define NIVXICC_H
#define NIVXICC __attribute__((regparm(0))) __attribute__((cdecl))
#endif

/usr/include/lockdep.h (conflicting definition)
#ifdef CONFIG_DEBUG_LOCK_ALLOC
# ifdef CONFIG_PROVE_LOCKING
#  define mutex_acquire(l, s, t, i)             lock_acquire(l, s, t, 0, 2, i)
# else
#  define mutex_acquire(l, s, t, i)             lock_acquire(l, s, t, 0, 1, i)
# endif
# define mutex_release(l, n, i)                 lock_release(l, n, i)
#else
# define mutex_acquire(l, s, t, i)              do { } while (0)
# define mutex_release(l, n, i)                 do { } while (0)
#endif

Error
# make
make -C /lib/modules/2.6.18-238.el5/build SUBDIRS=/usr/local/nivxi/src KBUILD_VERBOSE=1 modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-238.el5-i686'
test -e include/linux/autoconf.h -a -e include/config/auto.conf || (            \
        echo;                                                           \
        echo "  ERROR: Kernel configuration is invalid.";               \
        echo "         include/linux/autoconf.h or include/config/auto.conf are missing.";      \
        echo "         Run 'make oldconfig && make prepare' on kernel src to fix it.";  \
        echo;                                                           \
        /bin/false)
mkdir -p /usr/local/nivxi/src/.tmp_versions
rm -f /usr/local/nivxi/src/.tmp_versions/*
make -f scripts/Makefile.build obj=/usr/local/nivxi/src
gcc -m32 -Wp,-MD,/usr/local/nivxi/src/.vxi.o.d  -nostdinc -isystem \
/usr/lib/gcc/i386-redhat-linux/4.1.2/include -D__KERNEL__ -Iinclude \
-include include/linux/autoconf.h -Wall -Wundef -Wstrict-prototypes \
-Wno-trigraphs -fno-strict-aliasing -fno-common -Wstrict-prototypes \
-Wundef -Werror-implicit-function-declaration \
-fno-delete-null-pointer-checks -fwrapv -Os -pipe -msoft-float \
-fno-builtin-sprintf -fno-builtin-log2 -fno-builtin-puts \
-mpreferred-stack-boundary=2  -march=i686 -mtune=generic -mtune=generic \
-mregparm=3 -ffreestanding -Iinclude/asm-i386/mach-generic \
-Iinclude/asm-i386/mach-default -fomit-frame-pointer -g -fno-stack-protector \
-Wdeclaration-after-statement -Wno-pointer-sign -DVXI_MAJOR=0 \
-DREMAP_PAGE_RANGE_VMA -D__DEBUG__ -DMODULE -D"KBUILD_STR(s)=#s" \
-D"KBUILD_BASENAME=KBUILD_STR(vxi)" -D"KBUILD_MODNAME=KBUILD_STR(vximod)" \
-c -o /usr/local/nivxi/src/.tmp_vxi.o /usr/local/nivxi/src/vxi.c

    In file included from /usr/local/nivxi/src/vxi.c:13:
    /usr/local/nivxi/src/mutex.h:59:42: error: macro "mutex_acquire" requires 4 arguments, but only 1 given
    In file included from /usr/local/nivxi/src/vxi.c:13:
    /usr/local/nivxi/src/mutex.h:59: warning: 'regparm' attribute only applies to function types
    /usr/local/nivxi/src/mutex.h:59: warning: 'cdecl' attribute only applies to function types
    /usr/local/nivxi/src/mutex.h:61:42: error: macro "mutex_release" requires 3 arguments, but only 1 given
    /usr/local/nivxi/src/mutex.h:61: warning: 'regparm' attribute only applies to function types
    /usr/local/nivxi/src/mutex.h:61: warning: 'cdecl' attribute only applies to function types
    /usr/local/nivxi/src/vxi.c:128:31: error: macro "mutex_acquire" requires 4 arguments, but only 1 given
    /usr/local/nivxi/src/vxi.c:133:31: error: macro "mutex_release" requires 3 arguments, but only 1 given
    /usr/local/nivxi/src/vxi.c:146:31: error: macro "mutex_acquire" requires 4 arguments, but only 1 given
    /usr/local/nivxi/src/vxi.c:158:31: error: macro "mutex_release" requires 3 arguments, but only 1 given
    /usr/local/nivxi/src/vxi.c: In function 'vxi_mmap':
    /usr/local/nivxi/src/vxi.c:243: error: implicit declaration of function 'remap_page_range'
    make[2]: *** [/usr/local/nivxi/src/vxi.o] Error 1
    make[1]: *** [_module_/usr/local/nivxi/src] Error 2
    make[1]: Leaving directory `/usr/src/kernels/2.6.18-238.el5-i686'
    make: *** [default] Error 2

A: The problem will not be in your object file as macros have file-scope and are replaced by the preprocessor.  Thus after being compiled, the macro no longer exists as far as your nivxi.o file is concerned.
The issue is probably in your mutex.h file.  I would look at the top and you will likely see an #include <lockdep.h> line. Thus once the preprocessor gets down to your function definition, it treats mutex_acquire as a token to be replaced (with the wrong number of arguments).
The easiest way to solve your problem will be to #undef mutex_acquire and #undef mutex_release at the beginning of mutex.h.  This will prevent the preprocessor from replacing the tokens in your mutex.h.  Since defines have file-scope, you don't need to worry about this propagating beyond your application


text:
Q: Parameter Expansion instead of cut I have a variablefull_name=first_name:last_name, how can I use parameter expansion to extract first_name and last_name?
The result of this cut command
echo $full_name | cut -d ":" -f1

is first_name. And the result of
echo $full_name | cut -d ":" -f2

is
last_name.
Is there a better way to achieve this? How to split a string by : delimiter?

A: In bash, a common idiom is to do:
$ full_name=first_name:last_name
$ echo "${full_name#*:}"
last_name
$ echo "${full_name%:*}"
first_name

The ${var#word} pattern removes word from the beggining of var, and ${var%word} removes word from the end.  The man page describes is better than I can:
   ${parameter#word}
   ${parameter##word}
          Remove  matching  prefix  pattern.   The  word  is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules described under Pattern Matching
          below.  If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern  (the  ``#''  case)  or  the  longest
          matching  pattern  (the  ``##''  case) deleted.  If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an
          array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

   ${parameter%word}
   ${parameter%%word}
          Remove matching suffix pattern.  The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using  the  rules  described  under  Pattern  Matching
          below.  If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``%'' case) or the
          longest matching pattern (the ``%%'' case) deleted.  If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If  parameter
          is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

A: I would use read instead.
 IFS=: read -r first last <<< "$full_name"

For full POSIX compatibility,
 IFS=: read -r first last <<EOF
 $full_name
 EOF

For only two fields, there's not much difference between this and parameter expansion. But read scales to multiple fields much better than parameter expansion:
x="1:2:3:4:5"
IFS=: read -r a b c d e <<< "$x"

vs
a=${x%%:*}
t=${x#*:}
b=${t%%:*}
t=${t#*:}
c=${t%%:*}
t=${t#*:}
d=${t%%:*}
e=${t#*:}

A: You might customize the IFS (Internal Field Separator) special variable's value, for example:
$ IFS=":$IFS" bla="abc:def"; for i in $bla; do echo $i; done
abc
def

It would then be good to back up the original value and then bring it back after it's not needed anymore. Otherwise you might observe unexpected behavior :D

A: William Pursell has covered parameter expansion.
For this scenario you could also use parameter substitution:
$ full_name=first_name:last_name

$ echo "${full_name//:*/}"
first_name

$ fname="${full_name//:*/}"
$ echo "${fname}"
first_name

$ echo "${full_name//*:/}"
last_name

$ lname="${full_name//*:/}"
$ echo "${lname}"
last_name

redpajama_set_name: RedPajamaStackExchange


text:
Q: Correlation ID not found error on iOS build on AppCenter I get the following error when I try to deploy a react-native iOS app on AppCenter
##[error]"{\"message\":\"Not found. Correlation ID: ec546922-3dbd-488e-80fb-15dcc8a51a84\",\"statusCode\":404,\"code\":\"Not Found\"}"

It started happening last week, but I haven't changed any native dependency, so I'm not sure what is this. Also, the android deployment works fine.

A: In my case, ios was working fine but not Android. Also, an other Android release pipeline was working fine. The issue was company name missing in the app slug. E.g Company name is Tesla and the build you'd like to deploy is battery then app slug should be Tesla\battery. Initially, app slug was battery only. After I added Tesla\ in front of battery, it worked fine for me.

A: We had this issue, but it resolved on its own without us doing any change. It might not be the case for you, but maybe try to rebuild the app a few times if it was working in the history and you haven't done any change.

A: For people having still the problem, adding the email from our Jenkins (jenkins-appcenter@...) as a collaborator worked.


text:
Q: Javascript: erroneous data being set to a map I have this function. The input to the function is data obtained from a json file. I have a map called arrowMap which is then set to arrowsMap which is in turn set to arrowsDataMap. The problem is face is that the data is overwritten in the arrowsDataMap at the old keys. So when I do this arrowsDataMap.get("0").get(0).get(1)), i get the data that was at (arrowsDataMap.get("1").get(0).get(1)) and the same data at that location too. So data is essentially overwritten. Any help is appreciated.
function animateLines(data) {
pointLength = data.points.length;
arrowLength = data.points["0"].point.length;

var viewEntryKey=0;
for (var viewEntryKey in data.points) {
    for (var i = 0; i < data.points[viewEntryKey].point.length; i++) {
        var arrowMap = new Map();

        arrowMap.set(1,data.points[viewEntryKey].point[i].latLng);
        arrowMap.set(2,data.points[viewEntryKey].point[i].size);
        arrowMap.set(3,data.points[viewEntryKey].point[i].angle);

        arrowsMap.set(i,arrowMap);
            //alert(arrowsMap.get(0).get(1));

}

arrowsDataMap.set(viewEntryKey,arrowsMap);
}

json file:

{
  "points": [
  {
    "point": [
      {
        "latLng": [-88.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.79"
      },
      {
        "latLng": [-88.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.69"
      }
      ,
      {
        "latLng": [-88.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.49"
      }
      ,
      {
        "latLng": [-88.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.29"
      }
      ,
      {
        "latLng": [-88.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.09"
      }
      ,
      {
        "latLng": [-88.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "-0.09"
      }
      ,
      {
        "latLng": [-88.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "-0.29"
      }
      ,
      {
        "latLng": [-88.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "-0.49"
      }
      ,
      {
        "latLng": [-88.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "-0.69"
      }
    ]
  },
  {
    "point": [
      {
        "latLng": [-89.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.79"
      },
      {
        "latLng": [-89.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.69"
      }
      ,
      {
        "latLng": [-89.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.49"
      }
      ,
      {
        "latLng": [-89.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.29"
      }
      ,
      {
        "latLng": [-89.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "0.09"
      }
      ,
      {
        "latLng": [-89.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "-0.09"
      }
      ,
      {
        "latLng": [-89.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "-0.29"
      }
      ,
      {
        "latLng": [-89.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "-0.49"
      }
      ,
      {
        "latLng": [-89.9999988477954, 29.999999681521295],
        "size": "0.15",
        "angle": "-0.69"
      }
    ]
  }
  ]
}

A: I have a feeling you should recreat arrowsMap for each member of data.points. So, inside the first loop, before the second loop starts, put var arrowsMap = new Map();.
Since you weren't creating a new Map for each arrow, the data from the previous arrow that was saved was being overwritten by the next arrow.


text:
Q: Inserting Variables MySQL Using Python Not showing up in data base I'm have some problems and its more then likely something really dumb that i missed and i feel kind bad post something on here about this but if you guys could help it would be nice heres my code
    import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost", "testuser", "123", "test")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
number = 300
number1 = 5001

sql = "INSERT INTO PARTS (PART_NUMBER) VALUES (%d)"

try:
    number = 300
    # Execute the SQL command

    cursor.execute(sql,(number,))

    # Commit your changes in the database
    db.commit()
    print("Updated!")
except db.Error, e:
    print "Error %d: %s" % (e.args[0],e.args[1])
    # Rollback in case there is any error
    db.rollback()
    print("was rolled back")

# disconnect
db.close()

after i run it no problems but its not show up in my data base when recall the data back nothing   can someone tell me why ?
Thanks for your time.

A: You should always use %s, even for numbers.
sql = "INSERT INTO PARTS (PART_NUMBER) VALUES (%s)"

Check the first example here: http://mysql-python.sourceforge.net/MySQLdb.html#some-examples . It uses %s to the max_price variable, which is an int.
Quoted from the link:

In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5".


text:
Q: Element.scrollTop always return 0 I need to detect whether user scroll to the bottom of the HTML element. I know that best way to do that is use:
obj.scrollTop === (obj.scrollHeight - obj.offsetHeight)

But the problem is that in my case, obj.scrollTop always returns 0. It's probably something wrong with my CSS or with the fact that I use slick library, but I can't find what it could be.
Here's my parent component:

            <Slider ref={slider} {...settings}>
                <PlayerSlide1 />
                <PlayerSlide2 />
                <PlayerFAQ ref={faqContainer} />
            </Slider>

And child component HTML:

        ... some inner HTML

I want to detect whether user scroll to the bottom of my child component (with class faq).
Here's my CSS:
body {
    overflow: hidden;
    position: relative;
}

.container {
    overflow: hidden;
    height: 100vh
}

.player {
    position: relative;
    margin-top: 50px;
}

.scrollCarousel {
    width: 100%;
    height: auto;
    min-height: 75vh;
}

.scrollCarousel__slide {
    width: calc(var(--siteWidthNarrow) - 20px);
    margin: auto;
    background: transparent;
    height: auto;
    min-height: 70vh;
    max-height: calc(100vh - 177px);
    overflow-x: visible;
}

.faq {
    padding-bottom: 30px;
    overflow: scroll;
}

A: body {
    overflow: hidden; //maybe this causes the issue, once you set overflow hidden, then you should set min-height 100vh
    position: relative;
}

things like:
body {
    overflow: hidden;
    min-height:100vh;
    position: relative;
}


text:
Q: I want to program fn keys to bring up words that I use a lot I remember old computers where you could program fn keys to add long words to your text to save typing them again and again. I would like to do this on a Mac.
I have tried karabiner but that doesn't seem to allow adding text to keys.
I don't want to make autocorrects or shortcuts, I want to press a function key and get the word.
Is this possible either with software or with the Mac as it is?
Thanks.


text:
Q: DIV no carga en su contenido página PHP completa tengo una página php con contenido html y un div, dependiendo del valor que selecciono desde un combobox, llamo a una página php y la cargo completa en el div, si la cargo sin pasar parámetros en su url se carga, pero con una grilla vacía ya que no puede completarla porque necesita leer el parámetro pasado, si la paso con parámetros en la url, directamente no lo carga en el div, no hace nada, probé redireccionando la web sin parámetros y me muestra la página con su grilla vacía, si le paso parámetros, no redirecciona, parece ser que los parámetros son un problema
<!doctype html>

<meta charset="utf-8">
<title>Prueba</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

               <select name="cbx_datadases" size="1" id="cbx_datadases"  style="display:block;width:100%;height:28px;z-index:0;" title="Seleccionar base de datos">

               <?php
                  $enlace = mysql_connect('localhost', 'usuario', 'clave');
                  $resultado = mysql_query("SHOW DATABASES");
                  while ($fila = mysql_fetch_assoc($resultado))
                  {
                    echo'<OPTION VALUE="'.$fila['Database'].'">'.$fila['Database'].'</OPTION>';
                  }
               ?>
               </select>

Ya probé de copiar la URL generada desde mi código, la pego en una nueva pestaña y funciona perfecto, por lo cual, la web que quiero mostrar en el DIV funciona perfectamente.
No sé dónde está el problema, probé con Get() en vez de load() y me pasa lo mismo.
AGREGO :
Si hago :

    <?php include("showtables.php"); ?>

me muestra el contenido de la página showtables.php perfecto, pero con la grilla vacía porque no paso parámetros, en cambio si paso parámetros, hasta con harcode,

    <?php include("showtables.php?basedatos=baseprueba"); ?>

no muestra nada, de hecho, como si $("#wb_div_tablas").fadeIn(800); no funcionara
Gracias

A: Considerando que estás usando jQuery para manejar el evento, en vez de usar
this.value

intenta con:
$(this).val()


text:
Q: SQL Compact database with PHP I have been given 2 files .DB and .sdf to work with. I have googled it a little and found out that its SQL Compact database format. I really have no idea how to work with these database files.
I have found here on stackoverflow some 3rd party tools, bud they were all for windows (I am on Mac).
I have also tried to open it in SQLite but no success.
I need this data in my web app written in PHP. So conversion to MySQL or Postrge seems to be an ideal solution. Any ideas?

A: You can use MSSQL extension in PHP to work with these databases


text:
Q: A Boundary crossing result for discrete brownian bridge Let $S_n$ be a random walk with gaussian increments with $S_0=0$, i.e. $S_n-S_{n-1}\sim N(0,1), n\geq 1$. Fix $a>0,b\in \mathbb{R}$ and $c<a+bn$. Define the new process
$$
B_{n,c}(k):=S_k-\frac{k}{n}\left (S_n-c\right)
$$
to be a discrete bridge ending at $c$. I want to find an expression for the probability
$$
\mathbb{P}\left(\max_{0\leq k\leq n}B_{n,c}(k)-bk\geq a\right),
$$
which is only the probability that the bridge crosses the linear boundary by time $n$.
This expression is known in the continuous case (for the brownian bridge), see for example Scheike. The probability is given by
$$
\mbox{exp}(-2a(a+bt-c)/t).
$$
I have no reasons to believe that such an equivalent form would not hold in the discrete case.
The proof given in the article above doesn't "discretize" well because of the time inversion and time scaling properties used in the continuous case that dont translate into the discrete case.
I'm looking for some insight on how to compute this probability. I would like to get an exact expression, but I could settle for an upper bound that goes in $1/n$.
If it can be of any help, I have shown that the probability (found in Scheike as well)
$$
\mathbb{P}(\max_{0\leq s\leq t}W_s-bs\geq a)=1-\Phi(a/\sqrt{t}+b\sqrt{t})+exp(-2ab)\Phi(b\sqrt{t}-a/\sqrt{t})
$$
holds for the discrete brownian motion $S_n$.

A: I haven't managed a full answer for this, so this is just a sketch with a few ideas in it.
For notation I'm going to let $W(t)$ be a standard Brownian motion.
I can then consider $W(k)$ for integer k.  Similarly I'm going to consider a Brownian bridge $B_{n,c}(t)$ sampled at integer times.
Firstly I definitely think your estimate for the non bridge case is a strict upper bound and the error doesn't go away as $n\to\infty$.
To see this recall that with probability one for all positive $b$ there exists a time $T$ such that  $W(t) < a +bt$ for every $t>T$. It is east to see that there is a positive probability that there is a non integer $t$ with $W(t)> a+bt$ but $W(k) < a+bk$ for every integer $k$. the difficult part of the question is not the bridge, it's the discretisation error.
Notice that the , your constant $c$ is superfluous, $B_{n,c}(k) > a + bk$ if and only if $B_{n,0}(k) > a + \left(b-\frac cn\right)k$ so we can focus on the $0$ to $0$ bridge. For small $n$ you can work this out exactly by writing down the correlation matrix of the $B_{n,0}(k)$'s and integrating over the multivariate Gaussian. Not very nice and there's probably no closed form, but it's the only way to get an exact answer.
For large $n$ I can construct my bridge $\tilde B_n(t)$ By letting $T$ be the largest time such that $W(T) = \frac{W(n)}2$ then setting $\tilde B_n(t) = W(t)$ for $t<T$ and $\tilde B_n(t) = W(n) - W(t)$ for $t\geq T$.
If $W(n)$ is positive then $\tilde B_n(t) > a+bt$ only if $W(t) > a+bt$ if $W(t)$ is negative the opposite is true, but if there exists $t$ such that $\tilde B_n(t) > a+bt$ but $W(t) < a+bt$ I can define $\tilde T<n$ as the largest time such that $W(T)=0$ and set  $\tilde W(t)$ = $W(t)$ for $t<\tilde T$ and $\tilde W(t) = -W(t)$ for $t>\tilde T$.
You should be able to convince yourself that $\tilde W(t)\geq\tilde B_n(t)$
for every $t$ so if $\tilde B_n(t)$ crosses the boundary so does $\tilde W(t)$. Furthermore as $W(t)$ does not cross the boundary  $\tilde B_n(t)$ can only cross the boundary for $t>T$. So if I create a bridge by reflecting $\tilde W(t)$ it does not cross the boundary.
So there exists a measure preserving map ($W\mapsto\tilde W$) that takes the set of paths where the bridge crosses the boundary but the path itself does not onto to the set  of paths that do cross the boundary but the reflection bridge does not. So the probability that the path crosses the boundary is greater than or equal to the probability that the bridge crosses the boundary.
Notice that the argument does not break down if I only count boundary crossings that occur at integer times. I think that the error for the discrete process is bounded above by the error for the continuous process.
Another avenue you might want to consider is to get rid of $b$ by setting $\tilde c = c - nb$ Then $B_{n,c}(t) > a+bt$ if and only if $B_{n,\tilde c}(t) > a$.  Now I can create a bridge from $0$ to $\tilde c$ the same way, by conditioning my bridge to hit $\tilde c$ before time $n$ and then reflecting as before to create a bridge. So now I'm interested in the probability that
there exists a pair $k < t<n$ with $n\in\mathbb N$ and $t\in\mathbb R$ such that
$W(k) > a$ and $W(t) = $\tilde c$. (or an alternative case where the bridge crosses but the Brownian motion doesn't I think these probabilities will drop off pretty rapidly. )
This might be a way of getting a handle on your discretisation error. Although it's essentially the same problem (What's the probability that a Brownian motion goes above a certain boundary at real times, but not integer times) it should be easier in this case because you can use the reflection principle and other tricks in this situation.
Sorry it's not an answer, but hopefully there's an idea or two in there that you can use.


text:
Q: linaro compiler cannot find library when adding -static I am trying to statically cross-compile an Application for ARM using the Linaro-Toolchain 7.1.1 . The final elf file is dependent on two shared-objects. I need to statically compile the application because there are dependencies that are not available on my target-system (eg. libstdc++). The -L and -I flags are in the makefile and everything works normally without the -static Flag. However when i use the -static flag, my linaro-linker tells me that it cannot find the dependencies, even though i know they are there as liba.so and libb.so. Any help or point to literature is appreciated, i feel like i did not fully understand what -static does, eventhough i did my research online.
Thanks

A: Thanks to your comments i was able to solve my problem and understand why i had it.
As user RPGillespie mentioned, the -static flag needs archived (libx.a) versions of the objects, so i had to compile the .o files to .a files using the ar-tool from the linaro toolchain.
Furthermore, as user RPGillespie refered me to, i had to specify the archives x using -l:libx.a instead of -lx in the g++ command.
Also it took me some time to notice that if the x.a files are not present, the linker will link dynamically. In my makefile the executable was compiled before the x.a file was available (because i just modified the makefile used to build the x.so).


text:
Q: which command to use in SunOS which is equal to zgrep in linux Trying to find a string in *.gz file and try the following;
   zipgrep user >filename>.gz
     [<filename>.gz]
     End-of-central-directory signature not found.  Either this file is not
     a zipfile, or it constitutes one disk of a multi-part archive.  In the
     latter case the central directory and zipfile comment will be found on
     the last disk(s) of this archive.
     zipinfo:  cannot find zipfile directory in one of <filename>.gz or
      010414:22:59.serverlog.gz.zip, and cannot find <filename>.gz.ZIP, period.
      /usr/bin/zipgrep: test: argument expected

zgrep is not available;
 zgrep -h
      -bash: zgrep: command not found

Thanks for your help.

A:
I tried zcat also but it is giving me this error; .gz |grep -i user-user

That indicates you're doing something like this:
zcat '<filename>.gz |grep -i user-user <filename.serverlog.gz.Z'

You want this:
zcat filename.gz | grep -i user-user


text:
Q: Suggestion for a large hash table (2^25 elements) I want to write a birthday attack program in Haskell for a variant of SHA1 which only produces only a 50 bit hash. To do this I need a hash table capable of storing approx. 2^25 entries.
The keys in this map will be Int64 and the values will be short length strings (~ 16 bytes).
Any suggestions for which hash implementation to use?
(Disregard that last update - I would need a bit array of 2^50 elements.)

A: For 2^25 entries at 8 bytes a piece, you are looking at something like 768MB of storage for just the data, at most probably around 3 gigabytes with actual overhead for storing bytestrings -- guesstimating 80 bytes per bytestring, then you have the hashtable/map's internals to store, and the boxing for the key, etc.
This means you can store the entire thing resident in memory on a decent machine, which keeps the problem relatively sane, but your collection times will kind of suck.
I would recommend using a lot of smaller hash tables, by partitioning your keyspace, that way you can run lots of the updates in parallel regardless of the hash table you use.
As for implementation:
You can either wrap a bunch of immutable hash tables like the wide-fanout ones from unordered-containers in IORefs and use some kind of atomicModifyIORef or something like ryan newton's compare and swap primitive, or you can try to use the old Data.HashTable implementation in a straightforward imperative manner.
The latter will improve your asymptotics by a logarithmic factor over the hash-array mapped tries used by unordered-containers, but Data.HashTable has bad constants. At the scale of your problem these factors probably cancel out though.

A: I also posted same sort of question. And from some suggestion, I am using Kyoto Cabinet. It is pretty cool and gives nice performance also. You can check my posts also because I have similar issues. EX. one, two and three. Perhaps this may helpful.


text:
Q: Java Exceptions. Cast one type to another Could someone explain why the first cast does not give a CCE ?
public class Test {

  public static void main(String[] args) throws Throwable {
    Test.<RuntimeException>throwIt(new Exception());
  }

  @SuppressWarnings("unchecked")
  private static <T extends Throwable> void throwIt(Throwable throwable) throws T {
    throw (T) throwable; // no ClassCastException
    throw (RuntimeException) throwable; // ClassCastException(as it should be)
  }
}

P.S. Comment one cast (otherwise it won't compile).

A: This is the feature of Java generics realization, it was realized through type erasure, that's why (T) cast actually cast it to Throwable as leftmost bound. Because, new Exception() produces a Throwable object you can safely throw it.
You can check it in JSL
http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#108979


text:
Q: How to register an org.apache.aries.blueprint.Interceptor in OSGi Karaf? I'm trying to implement a simple Interceptor to invoke methods of registered services in an OSGi Karaf environment. The services are published via blueprint configuration and, although there are working examples how to intercept CXF web-services, I can't find any documentation of how to register an implementation of org.apache.aries.blueprint.Interceptor.
This feature must have been introduced a few years ago according to Jira.
In broadest sense this question is related to Can I inject proxies in front of Blueprint services published by other bundles? that is solved with proxies whereas an interceptor approach is only discussed on the surface.
If the functionality I'm looking for is labeled differently within apache terminology, I'd still find a working end-2-end example very useful as the thread above only states the theoretical approach.

A: You can only add blueprint interceptors in namespace handlers not completely outside the bundle.
For an example of implementing a namespace see blueprint-authz. As you can see in the example you will have to introduce a simple element that the user has to add to his xml. This seems to be the only way to get a hook into the blueprint initialization.


text:
Q: How to find specified data in excel by using python (positive number first appeared and negative number nearby) I want to search data in every row in excel and find out the the first appeared positive number(A) and one negative number(B) just before A in sequence.
Like:
-5 -6 -3 4 1
I need number -3 and 4
I try to use this kind of code:
import xlrd

testFile=xlrd.open_workbook('test.xls')
mySheet=testFile.sheet_by_name("Sheet1")

nrows=mySheet.nrows
ncols=mySheet.ncols

def f(j):
    value=mySheet.cell(0,j).value
    return value

for j in range(ncols):
    if f(j)*f(j*1)>0:
        print f(j),f(j+1)

but when I run it, error comes out:

Traceback (most recent call last):
    File "test1.py", line 15, in (module)
      print f(j),f(j+1)
    File "test1.py", line 10, in f
      value=mySheet.cell(0,j).value
    File "C:\Python27\lib\site-packages\xlrd\sheet.py", line 399, in cell
      self._cell_types [rowx][colx],
IndexError: array index out of range

I have no idea why I cannot use the function f(j)*f(j+1)>0to find out the first positive number and nearby negative number.
Would someone help to find the problems?

A: Your range is from 0 to j. you are trying to access j+1 value. Hence, IndexError: array index out of range.
Also, you are doing if f(j)*f(j*1)>0: you probably wanted to do if f(j)*f(j+1)<0: Here I changed 2 things. made j*1 to j+1 and >0 to <0. You are checking if negativepositive against negativenegative. f(j)*f(j*1) should remain >0 until u find the first positive number.
And to solve index out of range run your loop until (ncols-1)
You can also do it in a much more efficient way. Just check if the number is positive. If yes then return that and the value at the previous index. You would not have to multiply which is an extra time consuming command


text:
Q: Calculating value of $\delta$ for a function $y=\frac1{(1-x)^2}$ unbounded at $x\rightarrow 1$ The function $y=\frac 1{(1-x)^2}$ is unbounded at $x\rightarrow 1$.
How can I calculate the value of $\delta$ such that $y> 10^6$ if $\left | x-1 \right |< \delta$ ?
Taking $y=f(x)=10^6$, putting in ${y=\frac1{(1-x)^2}}$, we get
$10^6 = \frac1{(1-x)^2}\\
\frac1{(1-x)^2} = \frac1{10^6}\\
x=1-\sqrt{(10^{-6})}$ meaning $x= 0.999$.
As, $\left |x-1\right |< \delta,$ hence $ \left|0.999 -1\right| < \delta,$ or
$10^{-3} < \delta$.
It can imply that,
$ \delta$ must be at least $10^{-3}$ or greater $ \delta \geq 10^{-3}$
(After correction by user:505767)

A: Pick $\delta$ such that
$$y=\frac{1}{\delta^2}=10^6$$
then at $\delta=±0.001$, $y=10^6$.
So$$|x-1|<\delta=0.001$$
in order to have $$y=\frac{1}{(1-x)^2}>\frac{1}{\delta^2}=10^6$$

A: We have that for $A,B>0$ (i.e. dividing both sides by $AB$)
$$A>B \iff \frac 1 A < \frac 1 B$$
therefore
$$\frac{1}{(1-x)^2}>10^6 \iff (1-x)^2<\frac1{10^6}=10^{-6}$$
form which, using that $\sqrt{A^2}=|A|$ and (taking the square roots both sides)
$$A^2<B \iff |A|<\sqrt B$$
we find
$$(1-x)^2<10^{-6} \iff |1-x|<10^{-3}$$
and $|1-x|=|x-1|$.
In your evaluation it should be
$$x=1-\sqrt{10^{-6}}=1-10^{-3}=0.999$$
which is correct but not much effective and clear to obtain the result.


text:
Q: Setting client area size (after creation)? I want to adjust the height of the client area after creation of the main window. I use CW_USEDEFAULT when creating it and I simply want to resize that to the nearest height which is divisible by a fixed number. I've tried processing WM_SIZE, but it doesn't seem to work like I want it to, and I'm not really sure SetWindowPos is the appropriate way to resize the client area.. ?
LRESULT CALLBACK mainWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message) {
      case WM_SIZE:
        if (HIWORD(lParam) % 15) {
          SetWindowPos(hWnd, NULL, 0, 0, LOWORD(lParam), HIWORD(lParam) / 15 * 15, SWP_NOMOVE);
        }
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;

      case WM_DESTROY:
        PostQuitMessage(0);
        break;

      default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }

    return 0;
}

The result is a zero-height client area for some reason:

Another couple of approaches I've tried:

*

*Updating the RECT top / bottom members when
WM_NCCALCSIZE is sent.

*Changing the cy member of the CREATESTRUCT when the WM_CREATE
message is sent.

Any ideas?

A: I use the following, but not from the WM_SIZE message, just from a function:
r= <a rect with the size you want>;
/* Compute the size of the window rectangle based on the given
 * client rectangle size and the window style, then size the
 * client window.
 */
AdjustWindowRect (&r, GetWindowLong(hWnd, GWL_STYLE), FALSE);
SetWindowPos (hWnd, 0,
          r.left, r.top,
          r.right  - r.left,
          r.bottom - r.top,
          SWP_NOZORDER | SWP_NOACTIVATE);

UpdateWindow(hWnd);

A: I realized my if-statement wasn't working as intended, since, when SetWindowPos is used to update the main window, it actually sets the full window height, whereas HIWORD(lParam) is only the client area height. In my case (Windows 7), the client area and full window height simply aren't both divisible by 15 at any point, so it will essentially keep looping. So here's my solution:
int initSize = 0; /* global */

/* ... */

case WM_SIZE:
    if (!initSize && HIWORD(lParam) % 15) {
        RECT r;
        GetClientRect(hWnd, &r);
        r.bottom = r.top + (HIWORD(lParam) / 15 * 15);
        AdjustWindowRect(&r, GetWindowLong(hWnd, GWL_STYLE), TRUE);
        SetWindowPos(hWnd, NULL, 0, 0, r.right - r.left, r.bottom - r.top, SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOMOVE);
        initSize = 1;
    }
    return DefWindowProc(hWnd, message, wParam, lParam);
    break;


text:
Q: C# DateTime.Ticks equivalent in Java What is the Java equivalent of DateTime.Ticks in C#?
DateTime dt = new DateTime(2010, 9, 14, 0, 0, 0);
Console.WriteLine("Ticks: {0}", dt.Ticks);

What will be the equivalent of above mentioned code in Java?

A: Well, java.util.Date/Calendar only have precision down to the millisecond:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, 0); // Clear the millis part. Silly API.
calendar.set(2010, 8, 14, 0, 0, 0); // Note that months are 0-based
Date date = calendar.getTime();
long millis = date.getTime(); // Millis since Unix epoch

That's the nearest effective equivalent. If you need to convert between a .NET ticks value and a Date/Calendar you basically need to perform scaling (ticks to millis) and offsetting (1st Jan 1AD to 1st Jan 1970).
Java's built-in date and time APIs are fairly unpleasant. I'd personally recommend that you use Joda Time instead. If you could say what you're really trying to do, we can help more.
EDIT: Okay, here's some sample code:
import java.util.*;

public class Test {

    private static final long TICKS_AT_EPOCH = 621355968000000000L;
    private static final long TICKS_PER_MILLISECOND = 10000;

    public static void main(String[] args) {
        long ticks = 634200192000000000L;

        Date date = new Date((ticks - TICKS_AT_EPOCH) / TICKS_PER_MILLISECOND);
        System.out.println(date);

        TimeZone utc = TimeZone.getTimeZone("UTC");
        Calendar calendar = Calendar.getInstance(utc);
        calendar.setTime(date);
        System.out.println(calendar);
    }
}

Note that this constructs a Date/Calendar representing the UTC instant of 2019/9/14. The .NET representation is somewhat fuzzy - you can create two DateTime values which are the same except for their "kind" (but therefore represent different instants) and they'll claim to be equal. It's a bit of a mess :(

A: Base on Jon Skeet I developed this class
import java.util.Calendar;
import java.util.Date;

public class DateHelper {

    private static final long TICKS_AT_EPOCH = 621355968000000000L;
    private static final long TICKS_PER_MILLISECOND = 10000;

    public static long getUTCTicks(Date date){

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return (calendar.getTimeInMillis() * TICKS_PER_MILLISECOND) + TICKS_AT_EPOCH;

    }

    public static Date getDate(long UTCTicks){

        return new Date((UTCTicks - TICKS_AT_EPOCH) / TICKS_PER_MILLISECOND);

    }

}

It works for me

A: In Java is:
long TICKS_AT_EPOCH = 621355968000000000L;
long tick = System.currentTimeMillis()*10000 + TICKS_AT_EPOCH;

A: System.nanoTime() gives you nanoseconds in Java (since 1.6). You'll still need to shift/rescale, but no precision will be lost.

A: And for those of us showing up trying to get the current number of ticks as defined by the UUID specification:
/**
    Returns the current tick count.
    Ticks are the number of 100 ns intervals since October 15, 1582
    @return
*/
private static long getUtcNowTicks() {

    final long UNIX_EPOCH_TICKS = 122192928000000000L; //Number of ticks from 10/16/1582 to 1/1/1970
    Instant i = Clock.systemUTC().instant(); //get the current time
    long ticks = UNIX_EPOCH_TICKS; // number of ticks as of 1/1/1970
    ticks += i.getEpochSecond()*10000000; //number of whole seconds (converted to ticks) since 1/1/1970
    ticks += i.getNano() / 100; //number of ticks since the start of the second

    return ticks;

    /*
    Some interesting tick values

    Date            Ticks
    ==========  ==================
    10/15/1582                   0  Start of UUID epoch; the date we switched to the Gregorian calendar)
     1/01/1601    5748192000000000  Start of Windows epoch (start of 1st Gregorian 400-year cycle)
    12/30/1899  100101312000000000  Start of Lotus 123, Excel, VB, COM, Delphi epoch
     1/01/1900  100103040000000000  Start of SQL Server epoch
     1/01/1970  122192928000000000  Start of UNIX epoch
     1/01/2000  131659776000000000
     1/01/2010  134815968000000000
     1/01/2020  137971296000000000
     1/19/2038  143714420469999999  UNIX Y2k38 problem (January 19, 2038  3:14:07 am)
    */
}

A: To convert .Net Ticks to millis in java use this :
static final long TICKS_PER_MILLISECOND = 10000;
long ticks = 450000000000L; // sample tick value
long millis = (ticks  / TICKS_PER_MILLISECOND);

A: There are 10,000 ticks in a millisecond, and C# considers the beginning of time January 1, 0001 at midnight. Here's a one-liner which converts an Instant to ticks.
public static long toTicks(Instant i)
{
   return Duration.between(Instant.parse("0001-01-01T00:00:00.00Z"), i).toMillis() * 10000;
}


text:
Q: Adding angular.morris-chart to angular app I'm trying to draw some donut charts with angular.morris-chart.js in my angular app.But when i can't figure out how to add it.
I added the js file in my libs directory, added it in my index.html after angular call. And i also injected it in my app.
But it still doesn't work. I get this error in my browser console: 'ReferenceError: Morris is not defined'.
Any clue to solve my issue ?

A: You can try to use ng-morris :
https://github.com/cleechtech/ng-morris

A: Include in your project-'raphael/raphael.js','morris.js/morris.js', 'angular-morris-chart/src/angular-morris-chart.js','morris.js/morris.css'

These files will be in your bower_components after the bower install angular-morris-chart.

A: You should move to Angular-Morris. I have used it in Angular 1.3 and 1.5 perfectly.
It is really easy to use.
Add these:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-morris/1.3.0/angular-morris.min.js"></script>

Inject the dependency to your module:
'angular.morris'

Then just use it in your template:
<div
bar-chart
bar-data='[
    { y: "2006", a: 100, b: 90 },
    { y: "2007", a: 75,  b: 65 },
    { y: "2008", a: 50,  b: 40 },
    { y: "2009", a: 75,  b: 65 },
    { y: "2010", a: 50,  b: 40 },
    { y: "2011", a: 75,  b: 65 },
    { y: "2012", a: 100, b: 90 }
]'
bar-x='y'
bar-y='["a", "b"]'
bar-labels='["Series A", "Series B"]'
bar-colors='["#31C0BE", "#c7254e"]'>
</div>

Once it shows up, start passing values from controller.
bar-data =<controller>.arrayname (stringify if required)


text:
Q: My App from Page Tab wont load it goes to http://www.facebook.com/common/invalid_request.php# My Facebook App , on my Canvas loads properly. Both http and https AKA SSL. I then added the app to my Page as a tab. But when I click on the tab, All I get is a Facebook Logo Picture, when I follow the link i.e. Click on the Facebook logo link it brings me to https://www.facebook.com/common/invalid_request.php
I though it might be that the Canvas width size is like 720px, and I lowered my sites width to 520px, the size of pages.
A person in Augest had the same question:
Facebook Application Error In Page
I programmed a Facebook app, and i need to put in a Facebook page.
The application works great outside the Facebook page (standalone).
But when I try to access the application through the page's tab, Facebook's Logo (which linked to http://www.facebook.com/common/invalid_request.php#) appears instead of the app.
What could be the reason to this problem?

A: A Facebook app can have a different page tab URL configured which should be loaded when the App is loaded on a Page tab - is this set for your app? If so, it may not be set to the URL you were expecting (i.e it's not the same URL as your normal canvas app)
Also, when a page is loaded on a tab, a POST request is sent to your server with a signed_request callback, so your server or code may be expecting only a GET request.
Check these docs for more info:
https://developers.facebook.com/docs/appsonfacebook/pagetabs/ - note that the screenshots on this are currently out of date, i'll see if we can get them updated this week
https://developers.facebook.com/docs/authentication/signed_request/ shows the method to decode the info which is passed to your app on a page-tab load


text:
Q: How to stop sending read receipt for message read using OpenPop.NET I am reading all unread emails for an email id using OpenPop.Net in C#. The application is sending read receipt to the sender for all the message read by OpenPop.
Please suggest a way to stop sending read receipt.

A: This is not an openPOP issue, but rather a server issue. Since I'm not sure what mail server you're using, here's an article on how to disable this behavior in Exchange 2007 (it's the same for 2010). Hope this helps.


text:
Q: Windows crashes when I try to reload site running on XAMPP I am developing a statamic (flat file CMS) site and when I am reloading the site running on a XAMPP machine, my windows crashes. It showes up the same error every time:
Stop code: SYSTEM_SERVICE_EXCEPTION
What failed: cldflt.sys

The crashes are since I edited this file: site/content/pages/index.md. I've already tried to run this site with WAMP and MAMP but windows crashes the same way every time I try to reload the page. I also can't find anything useful in the Windows Event Viewer and I couldn't find any fixes to this either. Even when I reset the index.md to its default, the crash comes up anyways!
Did anyone got the same issue or knows a fix for this?
Thanks!

A: Okay guys, I've got an solution for this one.
This error is caused by the cldflt.sys which is responsible for some processes in OneDrive. So I moved my project directory to an non-synced folder and everything is fine. Otherwise, you could end the OneDrive task but I think this isn't the shiny solution. Yes, I tried these workarounds with those deactivate-this-file methods but then the site isn't loading evermore... whyever.
Hope I could help you.


text:
Q: gRPC polling for incoming packets from multiple sockets at once I am looking into possibility of listening on different sockets at once. To handle multiple socket connection at the same fd_set can be used in Linux. I have seen that gRPC also support this functionality with having epoll based pollset.
https://github.com/grpc/grpc/blob/18df25228cfa1f97fc5cca9176fbaef64c0e4221/doc/epoll-polling-engine.md
I intend to call different services in async mode and providing a service at the same time. Therefore, I was thinking about having a poll-set consist of client sockets waiting for async responses and server sockets. It seems to be possible in gRPC. I haven't been able to find anything in gRPC API that exposes construction of a poll-set.
Therefore, my question is how to use this capability of gRPC?
Does gRPC manages this automatically? In that case how can I wait for incoming messages?

A: The same CompletionQueue should be used for both client and server. To wait for the incoming messages next needs to be invokek.


text:
Q: Un-catchable ErrorException in PHP Sometimes, my php say:

"ErrorException : Error while sending QUERY packet. PID=X"

I tried to put a try/catch block in order to process a retry (with \Exception as exception class), but my try/catch block has no effect and the error is still thrown.
Have you any idea? Thanks a lot

A: This error happens sometimes due to the packets exceed the max_allowed_packet
it is not PHP Exception to catch it, it is MySQL error.
can you update your my.cnf and add the following:
max_allowed_packet=50M
then restart MySQL, you should be OK.


text:
Q: R increment vector in for-loop I have a table calles "pvalue" of 61 columns :

*

*the first one is the name of the sample "IdEch"

*all other columns are different pvalues named Pvalue1 to Pvalue60
I would like to select all "IdEch" that display AT LEAST one value < 0.01

I tried by doing a for-loop on each column (that select Pvalue < 0.01)
But I don't manage to record the IdEch in a vector. I just have the number of the column...which is useless... I do not manage to find the solution....
Here is my script:
res = data.frame()

list_pvalue = c()

for (i in 2:ncol(pvalue)) {

  res = subset( pvalue , pvalue[,i] < 0.01 )

  list_pvalue = c(res$IdEch,list_pvalue)

}

list_pvalue = unique(list_pvalue)

A: You're almost there. You want to find rows for which any pvalues are < 0.01, for each row.
To do something for each row, use apply. To see if any values are true, use any (?apply, ?any)
# pvalue[, -1] selects all but the first column
# pvalue[, -1] < 0.01 is a logical dataframe of TRUE/FALSE
# apply(X, 1, FUN) applys FUN to each row of X
# apply(pvalue[, -1] < 0.01, 1, any) is TRUE for each row that has a pvalue < 0.01
pvalue[apply(pvalue[, -1] < 0.01, 1, any), ] # is what you are after

A: Try below example
#dummy data
set.seed(123)
pvalue <- data.frame(IdEch=paste0("ID",1:10),
                     Pvalue1=runif(10,0,0.05),
                     Pvalue2=runif(10,0,0.05),
                     Pvalue3=runif(10,0,0.05),
                     Pvalue4=runif(10,0,0.05),stringsAsFactors = FALSE)

pvalue
#    IdEch     Pvalue1     Pvalue2     Pvalue3     Pvalue4
# 1    ID1 0.014378876 0.047841667 0.044476966 0.048151212
# 2    ID2 0.039415257 0.022666708 0.034640170 0.045114952
# 3    ID3 0.020448846 0.033878532 0.032025341 0.034535264
# 4    ID4 0.044150870 0.028631670 0.049713489 0.039773371
# 5    ID5 0.047023364 0.005146234 0.032785290 0.001230684
# 6    ID6 0.002277825 0.044991249 0.035426523 0.023889799
# 7    ID7 0.026405274 0.012304387 0.027203301 0.037922977
# 8    ID8 0.044620952 0.002102977 0.029707101 0.010820397
# 9    ID9 0.027571751 0.016396036 0.014457987 0.015909050
# 10  ID10 0.022830737 0.047725182 0.007355682 0.011581289

pvalue[ rowSums(pvalue[,-1] < 0.01) > 1, "IdEch" ]
# [1] "ID5"

A: pvalue[-1]

gives the data frame without the IdEch column.  Applying pmin to this gives you the minimum values in each row.  If some value is less than 0.01, then the min value is.
do.call("pmin", pvalue[-1]) < 0.01

then gives you the rowindices that have small values.  So that
pvalue[do.call("pmin", pvalue[-1]) < 0.01]

should be what you want.


text:
Q: What does this phrase from shapelys nearest_points() documentation mean? In the shapely user manual for nearest_points() there is the following remark

Note that the nearest points may not be existing vertices in the
geometries.

What is existing vertices in this context?

A: It means exactly what it says: the resulting shortest-distance points might not lie on the exact vertices of your input geometries.
Look at the following example:
import shapely

line  = shapely.geometry.LineString([(-1,0),(1,0)])
poly = shapely.geometry.Polygon([(0,0.5),(1,1.5),(-1,1.5)])

near_line, near_poly = shapely.ops.nearest_points(line, poly)

print(near_line.wkt)
# 'POINT (0 0)'

print(near_poly.wkt)
# 'POINT (0 0.5)'

Notice how the near_line object is a point at (0,0), which is not a vertex in the original line object. While the point (0,0) is contained in the original line object, it was NOT an actual vertex.
That is what the documentation is referring to.


text:
Q: Vector subscript out of range after closing ifstream Trying to read a file using ifstream. I came to the following error:
Vector subscript out of range
This happens until I reach the closing statement for the opened file, removing it does not cause an exception.
Here is some sample code:
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
#include <sstream>
#include <iostream>

using namespace std;

int main()
{
    ifstream ifile("myswearwords.txt");

    if (!ifile.is_open())
    {
        cerr << "File not found!\n";
        return false;
    }

    std::vector<std::string> myswearswords;
    std::copy(std::istream_iterator<std::string>(ifile),
        std::istream_iterator<std::string>(),
        std::back_inserter(myswearswords));

//  ifile.close(); -> exception rased, when I reach th ebrakpoint at this point

/// do further work
return 0;
}

Could anyone explain me the error here?

A: The code that you have posted has some compile time issues:

*

*You don't #include <iostream>

*You don't have an open curly brace immediately after int main()

*You don't declare ifstream ifile
With all this corrected the code runs fine: http://ideone.com/mzOyE2
Once the data is copied into myswearswords there is no preserved connection between ifile and myswearswords. So you should not be seeing this error.
Now obviously if you're even able to compile you haven't showed us all of your actual code. The actual bug then is likely in the un-shown section of code.
Incidentally, you could improve your code by using the vector constructor rater than subsequently copying into myswearswords:
const vector<string> myswearswords{ istream_iterator<string>(ifile), istream_iterator<string>() };


text:
Q: PHP - Subtract value from 2 objects where key = is the same Im not sure if ive wrote the question properly but ill elaborate more on what i need.
I have two objects which i need to change to array and they have keys 1,2,3 but they have different values i need to subtract the values from the array where the keys are the same, I hope this makes sense.
Things ive tried to far

*

*Push them both to 1 array and do the math from there (can't figure out how to do this)

*use array_diff to find the difference in the arrays but didn't work.

All help appreciated any more information needed will be provided
Example Arrays:
Array 1
1 => 300.00,
2 => 300.00,
3 => 300.00

Array 2
1 => 200.00,
2 => 200.00,
3 => 200.00

Desired output
1 => 100.00,
2 => 100.00,
3 => 100.00

A: The best option for this seems to be a for loop
$arr1 = [300, 300, 300];
$arr2 = [200, 200, 200];

$arr_length = sizeof($arr1) -1;

$minus_arr = [];

for($i = 0; $i <= $arr_length; $i++){
    $minus = $arr1[$i] - $arr2[$i];
    array_push($minus_arr, $minus);
}

print_r($minus_arr);

I took for granted your given arrays above, it sounds like the arrays you're using are either not the same size or have strings or nulls in them so check for an int first.
    <?php

$arr1 = [300, 300, 300];
$arr2 = [200, 200, 200];

$arr_length = sizeof($arr1) -1;

$minus_arr = [];

for($i = 0; $i <= $arr_length; $i++){
    if(is_int($arr1[$i]) && is_int($arr2[$i])){
        $minus = $arr1[$i] - $arr2[$i];
        array_push($minus_arr, $minus);
    }
}

print_r($minus_arr);

A: I hope I do not misunderstand your question.
My method is iterate through 2 arrays, and whenever their keys are the same, do the operation. Here is a example:
function diff($arr1, $arr2) {
    $result = [];
    foreach($arr1 as $key1 => $value1) {
        foreach($arr2 as $key2 => $value2) {
            if ($key1 == $key2) {
                $result[$key1] = $value1 - $value2;
            }
        }
    }
    return $result;
}

I see there is Laravel in your tag, if you're using laravel, I'm sure that you can achieve this better with Collection. The document is here. It provides you a more 'OO' way (similar to javascript) you can operate arrays in php.

A: For an indexed array,
function diff($arr1, $arr2){
    $arr3=array();
    for($i=0;$i<count($arr1);$i++){
        $arr3[$i]=$arr1[$i]-$arr2[$i];
    }
    print_r($arr3);
}
$arr1=array(300,300,300);
$arr2=array(100,100,100);
diff($arr1, $arr2);
//Displays 200, 200, 200, as expected


text:
Q: What's wrong in this merge sort code that it runs for horribly long time? So, the algorithm below works perfectly fine, for input sizes - 10,20,30
Input size - 35 time lag is visible in output
Input size - 40 You will be waiting a while
Anything above 40 - doesn't complete sorting.
public class TestSorting {

    public static void main(String[] args) {

        long start, end;

        Comparable[] numbers = generateRandom(45);
        Comparable[] temp;

        temp = Arrays.copyOf(numbers,numbers.length);
        System.out.println("-----------------------------------------------------------");
        System.out.println("                  M E R G E   S O R T");
        System.out.println("-----------------------------------------------------------");
        System.out.println("Initial: " + Arrays.asList(temp));
        start = System.nanoTime();
        Merge.sort(temp);
        end = System.nanoTime();
        System.out.println("Final  : " + Arrays.asList(temp));
        System.out.println("Total Runtime: " + (end-start));

    }

    private static Comparable[] generateRandom(int size) {
        Comparable[] data = new Comparable[size];

        Random random = new Random();

        for(int i = 0 ;i<size;i++)
            data[i] = random.nextInt(100);

        return data;
    }
}

Merge.java
public class Merge {

    public static boolean lessThan(Comparable x, Comparable y) {
       return x.compareTo(y)<0;
    }

    public static void sort(Comparable[] data) {
        sort(data,0,data.length-1);
    }

    private static void sort(Comparable[] data,int low,int high) {
        if(high<=low) return;

        int mid = low + (high-low)/2;
        sort(data,0,mid);
        sort(data,mid+1,high);
        merge(data,low,mid,high);
    }

    private static void merge(Comparable[] data, int low, int mid, int high) {

        Comparable[] X = new Comparable[mid-low+1]
        Comparable[] Y = new Comparable[high-mid];

        for(int i=0;i<X.length;i++) X[i] = data[low+i];
        for(int i=0;i<Y.length;i++) Y[i] = data[mid+1+i];

        int start1 = 0, start2 = 0;
        while(start1<X.length && start2<Y.length) {
            if(lessThan(X[start1],Y[start2])) data[low++] = X[start1++];
            else data[low++] = Y[start2++];
        }

        while (start1 < X.length) data[low++] = X[start1++];
        while (start2 < Y.length) data[low++] = Y[start2++];
    }

}

Can anyone help me figure out what's wrong?
Is it the extra local array creations that's making it go slow?

A: The recursive call
sort(data,0,mid);

should actually be
sort(data,low,mid);


text:
Q: Using EXISTS within a GROUP BY clause Is it possible to do the following:
I have a table that looks like this:
declare @tran_TABLE TABLE(
EOMONTH DATE,
AccountNumber INT,
CLASSIFICATION_NAME VARCHAR(50),
Value Float

)

INSERT INTO @tran_TABLE VALUES('2018-11-30','123','cat1',10)
INSERT INTO @tran_TABLE VALUES('2018-11-30','123','cat1',15)
INSERT INTO @tran_TABLE VALUES('2018-11-30','123','cat1',5 )
INSERT INTO @tran_TABLE VALUES('2018-11-30','123','cat2',10)
INSERT INTO @tran_TABLE VALUES('2018-11-30','123','cat3',12)
INSERT INTO @tran_TABLE VALUES('2019-01-31','123','cat1',5 )
INSERT INTO @tran_TABLE VALUES('2019-01-31','123','cat2',10)
INSERT INTO @tran_TABLE VALUES('2019-01-31','123','cat2',15)
INSERT INTO @tran_TABLE VALUES('2019-01-31','123','cat3',5 )
INSERT INTO @tran_TABLE VALUES('2019-01-31','123','cat3',2 )
INSERT INTO @tran_TABLE VALUES('2019-03-31','123','cat1',15)

EOMONTH     AccountNumber   CLASSIFICATION_NAME     Value
2018-11-30  123                     cat1                10
2018-11-30  123                     cat1                15
2018-11-30  123                     cat1                5
2018-11-30  123                     cat2                10
2018-11-30  123                     cat3                12
2019-01-31  123                     cat1                5
2019-01-31  123                     cat2                10
2019-01-31  123                     cat2                15
2019-01-31  123                     cat3                5
2019-01-31  123                     cat3                2
2019-03-31  123                     cat1                15

I want to produce a result where it will check whether in each month, for each AccountNumber (just one in this case) there exists a CLASSIFICATION_NAME cat1, cat2, cat3.
If all 3 exist for the month, then return 1 but if any are missing return 0.
The result should look like:
EOMONTH     AccountNumber   CLASSIFICATION_NAME
2018-11-30    123                   1
2019-01-31    123                   1
2019-03-31    123                   0

But I want to do it as compactly as possible, without first creating a table that groups everything by CLASSIFICATION_NAME, EOMONTH and AccountNumber and then selects from that table.
For example, in the pseudo code below, is it possible to use maybe an EXISTS statement to do the group by?
SELECT
    EOMONTH
    ,AccountNumber
    ,CASE WHEN EXISTS (CLASSIFICATION_NAME = 'cat1' AND 'cat2' AND 'cat3') THEN 1 ELSE 0 end
    ,SUM(Value) AS totalSpend
FROM @tran_TABLE
GROUP BY
    EOMONTH
    ,AccountNumber

A: You could emulate this behavior by counting the distinct classifications that answer this condition (per group):
SELECT
    EOMONTH
    ,AccountNumber
    ,CASE COUNT(DISTINCT CASE WHEN classification_name IN ('cat1', 'cat2', 'cat3') THEN classification_name END)
          WHEN 3 THEN 1
          ELSE 0
     END
    ,SUM(Value) AS totalSpend
FROM @tran_TABLE
GROUP BY
    EOMONTH
    ,AccountNumber

A: Try this-
SELECT EOMONTH,
AccountNumber,
CASE
    WHEN COUNT(DISTINCT CLASSIFICATION_NAME) = 3 THEN 1
    ELSE 0
END CLASSIFICATION_NAME
FROM @tran_TABLE
GROUP BY EOMONTH,AccountNumber

Output is-
2018-11-30  123 1
2019-01-31  123 1
2019-03-31  123 0

A: Query like this. You can count distinct values.
When you count unique values then column 'Three_Unique_Cat'. When you count exactly 'cat1','cat2','cat3' then column 'Three_Cat1_Cat2_Cat3'
SELECT
    EOMONTH, AccountNumber
    ,CASE WHEN
       COUNT(DISTINCT CLASSIFICATION_NAME)=3 THEN 1
       ELSE 0
    END AS 'Three_Unique_Cat'
    ,CASE WHEN
       COUNT(DISTINCT CASE WHEN CLASSIFICATION_NAME IN ('cat1','cat2','cat3')
        THEN CLASSIFICATION_NAME ELSE NULL END)=3 THEN 1
       ELSE 0
     END AS 'Three_Cat1_Cat2_Cat3'
    ,SUM(Value) AS totalSpend
FROM @tran_TABLE
GROUP BY EOMONTH, AccountNumber

Output:
EOMONTH   AccountNumber Three_Unique_Cat    Three_Cat1_Cat2_Cat3    totalSpend
2018-11-30  123 1   1   52
2019-01-31  123 1   1   37
2019-03-31  123 0   0   15

A: It's easy, just as below:
select
    EOMONTH,
    AccountNumber,
    case when count(distinct CLASSIFICATION_NAME) = 3 then 1 else 0 end as CLASSIFICATION_NAME
from
    tran_TABLE
group by
    EOMONTH,
    AccountNumber


text:
Q: docker-compose build hangs in script with yarn install I have this script where i put docker-compose build and it hangs at the end of the RUN yarn install:
[3/4] Linking dependencies...
warning " > @craco/craco@6.4.3" has incorrect peer dependency "react-scripts@^4.0.0".
warning "@craco/craco > cosmiconfig-typescript-loader@1.0.9" has unmet peer dependency "@types/node@*".
warning "@craco/craco > cosmiconfig-typescript-loader@1.0.9" has incorrect peer dependency "typescript@>=3".
warning "@craco/craco > cosmiconfig-typescript-loader > ts-node@10.8.1" has unmet peer dependency "@types/node@*".
warning " > @testing-library/user-event@12.8.3" has unmet peer dependency "@testing-library/dom@>=7.21.4".
[4/4] Building fresh packages...
success Saved lockfile.
Done in 175.73s.
^CBuild complete.

You can see I interrupted the hang with ctrl+c and after that the it says "build complete".
This prevents my script to continue with docker-compose up...
I have this docker-compose.yml file:
version: '3.7'

services:

  frontend:
    build:
      context: .
      dockerfile: ./compose/production/build/Dockerfile
    restart: always
    stdin_open: true
    ports:
      - 80:80
    volumes:
      - staticfiles:/app/static
      - mediafiles:/app/media
    depends_on:
      - backend
    networks:
      spa_network:
        ipv4_address: 172.20.128.3

  backend:
    build:
      context: .
      dockerfile: ./compose/production/django/Dockerfile
    restart: always
    command: /start
    volumes:
      - staticfiles:/app/static
      - mediafiles:/app/media
      - sqlite_db:/app/db
    ports:
      - 8000:8000
    env_file:
      - ./env/prod-sample
    networks:
      spa_network:
        ipv4_address: 172.20.128.2

networks:
  spa_network:
    ipam:
      config:
        - subnet: 172.20.0.0/16

volumes:
  sqlite_db:
  staticfiles:
  mediafiles:

and the build which is hanging has this dockerfile:
FROM node:14-stretch-slim as frontend-builder

WORKDIR /app/frontend
COPY ./frontend .
ENV PATH ./node_modules/.bin/:$PATH
RUN yarn install
RUN yarn build

###############################################

FROM nginx:1.19.2-alpine

RUN rm /etc/nginx/conf.d/default.conf
COPY ./compose/production/build/nginx.conf /etc/nginx/conf.d
COPY --from=frontend-builder /app/frontend/build /usr/share/nginx/html/build

Notice the build is hanging only on first build. When i rerun the build process (docker-compose build) and it is in cache it is processing the next RUN command...
I've tried to use sudo docker-compose up --build -d but it's the same...maybe it has something to do with yarn?
The issue is described here : https://github.com/yarnpkg/yarn/issues/6605
but they say it's not yarn
And they point to there https://github.com/yarnpkg/yarn/issues/749#issuecomment-253317395 to use --no cache
I've tried to use --no cache and it is the same. It hangs after "Done in x s."

A: Apparently, running the following commands :
   RUN set -ex; \
      yarn install --frozen-lockfile --production; \
      yarn cache clean; \
      yarn run build

instead of
RUN yarn install
RUN yarn build

in the Dockerfile seems to work properly


text:
Q: jquery parallax.js not work I've been trying more than 10 times to use parallax.js jquery plugin. But it doesn't work. I don't understand what's going on with me.
plugin Site: http://matthew.wagerfield.com/parallax/
my demo work site: http://contact.themeshef.com/
Can anybody help me about how to use parallax js ?
Thanks in advance!
Page source:
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title></title>

A: You are using non-compiled version of library. either you should compile and use or you can download compiled version of parallax.min.js file from here or you can use cdn.
In this example i'm using CDN

<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <title></title>

A: For Laravel only
Add the below line before Creating a new instance of the Parallax class.

*

*import Parallax from "parallax-js";

*window.Parallax = Parallax;

Explanation:
This code imports the default export from the "parallax-js" module and assigns it to a variable named Parallax. It then assigns the value of Parallax to a property of the global window object also named Parallax. This allows the Parallax variable and any functions or properties associated with it to be accessed globally, which can be useful in cases where multiple scripts need to interact with the same Parallax instance or configuration.
The "parallax-js" module is a JavaScript library that provides a simple way to create parallax effects on web pages, where background images move at a different rate than the foreground content as the user scrolls. The library provides an object-oriented interface for creating parallax instances and defining their behavior, and it can be used with any HTML element or image.
Overall, this code is likely used in a web development project that requires the use of the Parallax library, and it makes the library's functionality available to other scripts on the same page.


text:
Q: E2E testing with serverside template preprocessing -- possible? I've been playing around with Angular the past week or so learning its ins and outs. I am now at a point where I'm trying to figure out the best way to restructure my app to do E2E testing, given that it will be embedded into a preexisting site, rather than stand on its own.
The problem comes in how to handle index.html from the angular-seed project, since my understanding is that Karma needs to point itself via scenarios.js at something in order to load and bootstrap the app before testing.
The markup currently in index.html will need to be inserted into the larger HTML structure of my page when it is being put together by our servers. There is no further preprocessing that must be done to the top-level Angular template, but this seems to be enough to complicate the testing process considerably.
This leaves me with three options as far as I can tell for enabling E2E testing:
1) duplicate the index.html code in its entirety to keep around as a complete mockup for testing
2) use a single angular route and ngView to access my top level view template (reducing the test purposes index.html to little more than <ng-view></ng-view> and <script> tags)
3) fold and just use Selenium for high-level testing
The first option introduces a maintainability problem, and the second is undesirable because it limits the testability of any aspect of the app outside the <ng-view>. Not an issue now, but could be as the app grows. And three, well, I've heard Selenium creates a lot of headaches with Angular apps that are best avoided by using the purpose-built Angular E2E testing tools.
So how is this situation typically handled?


text:
Q: VS2015 C++ cross-platform for iOS, vcremote issues I have installed all the prerequisites for using VS2015 to build, deploy and debug an iOS app ( currently just trying with the samples that comes with VS2015 )
Everything works fine, it builds and deploys the test-app to my iPad, but once it's supposed to start it, it fails with:
Unable to start debugging. Unexpected LLDB output from command "-target-select remote localhost:3031". Command 'target-select'. Fn 'target-select' failed
Tried to google this but the information / support for this seems to be minimal to nonexistant.
If I launch the app manually on the iPad it runs just fine.


text:
Q: Undefined Slot variable in Laravel I am getting an error which is "Undefined variable: nav"
In my home.blade.php,I have this code
@extends('master')
@section('content')
    {!! $nav !!}
@endsection

And in my header component(header.blade.php)
@component('component.header')
    @slot('nav')
       new html
    @endslot
@endcomponent

Can you help?
FYI my component is in a component directory in views and home is in views directory


text:
Q: How to make git to clone svn settings also? I'd like to create a read-only Git mirror of a SVN repository. I don't need to setup the Git->SVN direction and I've already done the SVN-Git synchronization.
Now I would like to somehow "clone" the git-svn setup from the Git server to a local Git repository as I would like to have a possibility to commit to the SVN repository directly, not via the Git mirror. For instance, after cloning my Git repository with git pull and committing some changes, I'd like to do git svn dcommit and the commit should be correctly written to the SVN repository. I don't need to fetch the changes directly from SVN, though it'd be nice to have such possibility. Obviously, I don't want to clone the SVN repository (which has about 45.000 revisions) from scratch to my local disc.
Is this somehow possible or is there any easy script that would solve my problem? Or is there any better way to solve the whole Git mirroring? Unfortunately, I don't have admin access to the SVN repository.


text:
Q: UISwipeGestureRecognizer fails to execute some times In my application I have added a UISwipeGestureRecognizer to navigate between viewControllers, but sometimes it fails to perform action on swipe gesture. I have simply added the swipe left and swipe right gesture in my viewDidLoad of parent viewController as i wanted to add the same in all my child viewControllers.
//Adding swipe gesture recognizers
UISwipeGestureRecognizer *swipeLeftGesture=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightNavigationButtonTapped)];
swipeLeftGesture.delegate = self;
[self.view addGestureRecognizer:swipeLeftGesture];
swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;

UISwipeGestureRecognizer *swipeRightGesture=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftNavigationButtonTapped)];
swipeRightGesture.delegate = self;
[self.view addGestureRecognizer:swipeRightGesture];
swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight;

I also added logs to check that when the swipe is being missed like below.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"touched for event %@", event.class);
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gesture
 shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGesture {
NSLog(@"gesture failed %@", otherGesture.class);
return YES;
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:      (UITouch *)touch{
 NSLog(@"touch %@", gestureRecognizer.class);
 return YES;
 }

In my case when the swipe is working correct, this is the log:
<Warning>: touch UISwipeGestureRecognizer
<Warning>: touch UISwipeGestureRecognizer
<Warning>: gesture failed _UISystemGestureGateGestureRecognizer
<Warning>: gesture failed _UISystemGestureGateGestureRecognizer
<Warning>: gesture failed UISwipeGestureRecognizer
<Warning>: gesture failed _UISystemGestureGateGestureRecognizer
<Warning>: gesture failed _UISystemGestureGateGestureRecognizer
<Warning>: touched for event UITouchesEvent

and when the swipe is not working correct this is the log:
<Warning>: touch UISwipeGestureRecognizer
<Warning>: touch UISwipeGestureRecognizer
<Warning>: gesture failed UISwipeGestureRecognizer
<Warning>: gesture failed _UISystemGestureGateGestureRecognizer
<Warning>: gesture failed _UISystemGestureGateGestureRecognizer
<Warning>: gesture failed _UISystemGestureGateGestureRecognizer
<Warning>: gesture failed _UISystemGestureGateGestureRecognizer
<Warning>: touched for event UITouchesEvent

Right now I am not able to understand the actual issue occurring in my case and what could be the issue. Please let me know if you have idea regarding why this issue could be occurring.

A: Have you tried returning NOin
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gesture
 shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGesture? Because that's the default behavior and this simple UISwipGestureRecognizer setup is working for me.


text:
Q: How to Create NodeJS Application without view ? Only NodeJS REST API I need to create a NodeJS application which serves only for exposing REST APIs. When I created a ExpressJS project using Express generator express myNodeApp, it creates a project defaulting the view to .jade files.
Can I create and run a NodeJS project without views ? My NodeJS project will expose REST services which another client application will consume. Hence my NodeJS project do not need any UI elements. Also what package.json or .bin/www file will have. I will be hosting my NodeJS project in Azure cloud and my client application will consume the exposed service from cloud.

A: For an example see the code in this answer:

*

*Node.js send data to backend with AJAX
Stripping all unnecessary code it would be basically:
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

app.post('/email', (req, res) => {
  console.log(req.body.address);
  res.json({ ok: true });
});

app.listen(4443, () => console.log('Listening on http://localhost:4443/'));

This code is a very simple REST API that exposes one endpoint but you can easily add more.
But if you're building a RESTful API from scratch then you can consider using some other frameworks like: Hapi, Restify, LoopBack, and other frameworks listed on http://nodeframework.com/ - Express is a very solid but fairly minimal framework and it's not the only option out there.

A: You can do this with express - see below
Install express and body-parser, feel free to use the module below
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

module.exports = {
    init: function(module_Enabled){
        var portnum = 1234;    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

        var allowCrossDomain = function(req,÷ res, next) {
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
            res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

            // intercept OPTIONS method
            if ('OPTIONS' == req.method) {
                res.send(200);
            } else {
                next();
            }
        };
        app.use(bodyParser.urlencoded({
            extended: false
        }));
        app.use(bodyParser.json());
        app.use(allowCrossDomain);
        var server = app.listen(portnum, function() {
            var host = server.address().address;
            var port = server.address().port;
            console.log("Content Provider Service listening at http://%s:%s", host, port);
        });
        app.get('/', function(req, res) {
            res.send('data');
        });
    }
}

A: Yes you can. express is capable to return response other that html element.
However, I would recommend you to use swagger project in developing REST API via express. The project will surely come in handy when developing and MAINTAINING API, especially if your API is huge and complex (lots of url and operation).
This site has a good explanation on how to install, use and run the swagger in NodeJs.


text:
Q: How to connect two databases? I have a site that's has got 2 open source programs installed. Elgg and Osclass. Both are great, but the problem is they each have their own database and therefore users must register a seperate account on each site. Is their any way to link the two databases (on cpanel) so that an account created on one will automatically be created on the other as well.

A: Since they are open source, you can modify their source-code. So you will need to do the following things:

*

*Write your own function which takes an Elgg user as an argument and creates an OsClass user for it. func1

*Write your own function which takes an OsClass user and creates an Elgg user for it. func2

*Write your own function which takes an existing Elgg user and finds the corresponding OsClass user. func3

*Write your own function which takes and existing OsClass user and finds the corresponding Elgg user for it. func4

*Modify Elgg to make sure that func1 is called just after an Elgg user was successfully created.

*Modify OsClass to make sure that func2 is called just after an OsClass user was successfully created.

*Make sure that whenever a user is removed, you call either func3 or func4, to get the corresponding user from the other database and remove that user.

A: You can use SAML (simplesamlphp) to get a Single Sign On service to start a session on both platforms with the same users.
There are plugins for elgg to do this (https://elgg.org/plugins/1939508) and it shouldn be difficult to get it to work in osClass.


text:
Q: Which version of the extension builder is working for TYPO3 9.5 LTS? It is recommend to use a recent version from Github https://github.com/FriendsOfTYPO3/extension_builder.
The latest version of the master branch does not work for the current LTS version of TYPO3 and I don't find any tags 9.x at all on Github.
In the extension manager the master branch identifies already as 9.10.0 so I have hope there is a working version for TYPO3 9.5 LTS. Which version is it?
If there is no working version for 9.t LTS, what is your workaround?

A: As of today a working approach for TYPO3 9.5 LST is this:
Latest commit of master:
ad22d356546794cecfe436ad2d3e3290933f3693
Manual fix of the save bug as given here by the user qbadev:
https://github.com/FriendsOfTYPO3/extension_builder/issues/178


text:
Q: Which layer should contain ICommand? In WPF, I have a ViewModel class called Malfunctions, and it has an ObservableCollection of PartMalfunctions. Typically, there are anywhere between 10 to 15 PartMalfunction objects in the ObservableCollection; how many there are depends upon other parameters that are outside the scope of this question.
I have some xaml that has a DataGrid which binds to this ObservableCollection. In the DataGrid I display various properties of the PartMalfuction (ie - description, name, etc.) and I have a Start timer button that the user can click. The Start timer button is bound to the ICommand StopwatchCmd in the PartMalfunction Model class (you can see all of this below in the code).
Here is my question: Do I have the StopwatchCmd in the wrong layer (ie - Does it belong in the Malfunctions ViewModel)? I have really struggled with this and tried to figure it out on my own, but I keep hitting a wall, so to speak, because the StopwatchCmd in the Model class works great! I mean it's able to execute there and perform whatever business rules it needs to and interact with just that instance of the object for which it fired. If I stick it in the ViewModel then it seems like I have to go through more work to get it to do what it's already doing.
Please note that I have left out some code from the Malfunctions ViewModel as it's not related to this question. Here is the code to the Malfunctions ViewModel.
public class Malfunctions : ViewModelBase {
       public ObservableCollection<Model.PartMalfunction> AllPartMalfunctions {
            get;
            private set;
        }
}

The Model class for PartMalfunction looks something like this:
public class PartMalfunction : INotifyPropertyChanged {
    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName) {
        if (PropertyChanged != null) {
            PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }

    private int _seconds;
    private string _stopwatchText = string.Empty;
    private bool _isStopwatchInProgress = false;
    System.Windows.Threading.DispatcherTimer _timer = new System.Windows.Threading.DispatcherTimer();
    RelayCommand _stopwatchCmd;

    public ICommand StopwatchCmd {
        get {
            if (_stopwatchCmd == null)
                _stopwatchCmd = new RelayCommand(param => this.StopwatchClick());
            return _stopwatchCmd;
        }
    }
    public bool IsStopwatchInProgress {
        get {
            return _isStopwatchInProgress;
        }
        set {
            _isStopwatchInProgress = value;
            OnPropertyChanged("IsStopwatchInProgress");
        }
    }
    public string StopwatchText {
        get {
            return _stopwatchText;
        }
        set {
            _stopwatchText = value;
            OnPropertyChanged("StopwatchText");
        }
    }
    private void StopwatchClick() {

        if (!this.IsStopwatchInProgress) {
            // Start the timer
            _seconds = 0;

            // Will immediately update the timer text to "00:00:00"
            this.StopwatchText = GetElapsed();

            _timer.Tick += DispatcherTimer_Tick;
            _timer.Interval = new TimeSpan(0, 0, 1); // Ticks every second
            _timer.Start();

            this.IsStopwatchInProgress = true;
        }
        else {
            // Stop the timer
            _timer.Stop();
            _timer.Tick -= DispatcherTimer_Tick;
            _seconds = 0;

            this.IsStopwatchInProgress = false;
        }
    }
    private void DispatcherTimer_Tick(object sender, System.EventArgs e) {
        _seconds += 1;

        this.StopwatchText = GetElapsed();
    }
    private string GetElapsed() {
        int hour = 0, min = 0, sec = 0;

        if (_seconds > 59) {
            min = (int)_seconds / 60;
            sec = _seconds % 60;

            if (min > 59) {
                hour = (int)min / 60;
                min = min % 60;
            }
        }
        else
            sec = _seconds;

        string elapsed = hour < 10 ? "0" + hour.ToString() : hour.ToString();
        elapsed += ":" + (min < 10 ? "0" + min.ToString() : min.ToString());
        elapsed += ":" + (sec < 10 ? "0" + sec.ToString() : sec.ToString());

        return elapsed;
    }
}

A: This question could be perceived as being primarily as opinion based, but I do believe it helps less experience developers understand the boundaries of the Model-View-ViewModel.
For me what you think is a Model is in fact a ViewModel, to be more specific the parent ViewModel (Malfunctions) has a collection of child ViewModels (PartMalfunction) exposed as a collection (ObservableCollection), meaning there isn't problem with the ICommand properties on the PartMalfunction class.
If I find a Model class doing a lot of format of data for display (text, dates etc) then it is more likely to be a ViewModel, this kind of thing is the responiblity of the ViewModel. Also for me a Model class does not implment the INotifyPropertyChanged interface, notifications are done using events (or Rx streams) and the subscriber (ViewModel) can then choose how and when to update the UI.

A: Here is how I organize it in MVVM:

*

*Models : only entities, partials of classes which are consumed.

*View :  Xaml and code behind which may show/manipulate Models as provided by the View Model.

*ViewModel : This layer is where the business logic resides and data (the models) retrieved from the DB are stored. It is the conduit between the View and the Models. It can access databases, create timers, hold ICommands,.... as long as the what it relates to business logic. No direct view processing; per-se (See implementation).

Remember when three tier systems were all the rage? If you think of MVVM as three tiers that may help. IMHO

Which layer should contain ICommand?

The viewmodel should hold the reference, because it handles the business logic of what the command does. But...
Implementation
The implementation of the command can be held in the View or on the ViewModel based on the needs of the command. I have frequently defined the references in the VM to then provide actual processing in the View which has stateful View values to be processed during runtime.

A: ICommand has two interesting members. Execute, which defines an action that another object can request that the owner of the command do, and CanExecute, which defines whether or not another should request the action. This is very apparent in the names of ICommand's properties, but if you look carefully, they land ICommand a perfect home in the ViewModel layer. Your view models can expose some actions, with control over when they are allowed to execute, to an unknown view. Since commands are generally public properties on the view model, you can easily bind to them from WPF controls without any tight coupling. Button for example, can bind to a command to define what it does without needing to know what type its DataContext(view model) is.
If you tried to place your ICommand in your view, you might find that they would be cumbersome compared to a method, since views have access to their own methods. Because of this, ICommand is not well suited in the View layer.
Since your view model abstracts the model away from your model (ideally), you wouldn't be able to (and wouldn't want to) put commands on your model classes. Any logic that deals with being presented or interacted with does not belong in the model layer.


text:
Q: ios - How to decode XML document? I'm new to iPhone development,I'm trying to get access token from Google,When I logged in,I'm getting HTML content,in that HTML content I want to get token that is contained in BinarySecurityToken node.
How to get that in the below HTML content?

    <title>Working...</title>

    <form method="POST"
            name="hiddenform"
            action="http://localhost:26298/LoginSuccess.aspx">
        <input type="hidden" name="wa" value="wsignin1.0" />
        <input type="hidden" name="wresult"
            value="<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
        <t:Lifetime><wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2013-04-29T11:50:29.895Z</wsu:Created><wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2013-04-29T12:00:29.895Z</wsu:Expires></t:Lifetime><wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"><EndpointReference xmlns="http://www.w3.org/2005/08/addressing"><Address>urn:orin.converse</Address></EndpointReference></wsp:AppliesTo>
       <t:RequestedSecurityToken>
           <wsse:BinarySecurityToken wsu:Id="uuid:5a48faca-2977-4c10-8cee-d213726f1971" ValueType="http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                 aHR0cCUzYSUyZiUyZnNjaGVtYXMubWljcm9zb2Z0LmNvbSUyZndzJTJmMjAwOCUyZjA2JTJmaWRlbnRpdHklMmZjbGFpbXMlMmZyb2xlPVVzZXImaHR0cCUzYSUyZiUyZnNjaGVtYXMueG1sc29hcC5vcmclMmZ3cyUyZjIwMDUlMmYwNSUyZmlkZW50aXR5JTJmY2xhaW1zJTJmZW1haWxhZGRyZXNzPWtyYWoubmFnJTQwZ21haWwuY29tJmh0dHAlM2ElMmYlMmZzY2hlbWFzLnhtbHNvYXAub3JnJTJmd3MlMmYyMDA1JTJmMDUlMmZpZGVudGl0eSUyZmNsYWltcyUyZm5hbWU9TmFnYXJhamFuK0thcnRoaWtleWFuJmh0dHAlM2ElMmYlMmZzY2hlbWFzLnhtbHNvYXAub3JnJTJmd3MlMmYyMDA1JTJmMDUlMmZpZGVudGl0eSUyZmNsYWltcyUyZm5hbWVpZGVudGlmaWVyPWh0dHBzJTNhJTJmJTJmd3d3Lmdvb2dsZS5jb20lMmZhY2NvdW50cyUyZm84JTJmaWQlM2ZpZCUzZEFJdE9hd2szaEtsblhkRzJsVmozX2F4bFJ1TlRVRzBMT09qdDJBayZodHRwJTNhJTJmJTJmc2NoZW1hcy5taWNyb3NvZnQuY29tJTJmYWNjZXNzY29udHJvbHNlcnZpY2UlMmYyMDEwJTJmMDclMmZjbGFpbXMlMmZpZGVudGl0eXByb3ZpZGVyPUdvb2dsZSZBdWRpZW5jZT11cm4lM2FvcmluLmNvbnZlcnNlJkV4cGlyZXNPbj0xMzY3MjM2ODI5Jklzc3Vlcj1odHRwcyUzYSUyZiUyZmNvbnZlcnNlLmFjY2Vzc2NvbnRyb2wud2luZG93cy5uZXQlMmYmSE1BQ1NIQTI1Nj04TjhQVmRFa1U0Q3NXODhnNVF1QVJkV0Q1c0t0dWxkS3RhY2NOaWd0Sjk0JTNk
           </wsse:BinarySecurityToken>
       </t:RequestedSecurityToken><t:TokenType>http://schemas.xmlsoap.org/ws/2009/11/swt-token-profile-1.0</t:TokenType><t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType><t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType></t:RequestSecurityTokenResponse>" />

Script is disabled. Click Submit to continue.

            <input type="submit" value="Submit" />

    </form>

Any ideas? Thanks in advance.

A: Already done ... Look forward. But it seems that you use XML/HTML namespaces, hum . Cheers.
https://stackoverflow.com/questions/6116827/looking-for-a-good-tutorial-on-nsxmlparser


text:
Q: std::thread arguments must be invocable after conversion to rvalues I am trying to create 2 threads, that work with float arrays. Howere compiler gives me these errors:
/usr/include/c++/9/thread: In instantiation of 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(bool*, float*, float*, float*); _Args = {bool*, float (*)[10], float (*)[10], float (*)[10]}; <template-parameter-1-3> = void]':
main.cpp:16:66:   required from here
/usr/include/c++/9/thread:120:44: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
  120 |           typename decay<_Args>::type...>::value,
      |                                            ^~~~~
/usr/include/c++/9/thread: In instantiation of 'struct std::thread::_Invoker<std::tuple<void (*)(bool*, float*, float*, float*), bool*, float (*)[10], float (*)[10], float (*)[10]> >':
/usr/include/c++/9/thread:131:22:   required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(bool*, float*, float*, float*); _Args = {bool*, float (*)[10], float (*)[10], float (*)[10]}; <template-parameter-1-3> = void]'
main.cpp:16:66:   required from here
/usr/include/c++/9/thread:243:4: error: no type named 'type' in 'struct std::thread::_Invoker<std::tuple<void (*)(bool*, float*, float*, float*), bool*, float (*)[10], float (*)[10], float (*)[10]> >::__result<std::tuple<void (*)(bool*, float*, float*, float*), bool*, float (*)[10], float (*)[10], float (*)[10]> >'
  243 |    _M_invoke(_Index_tuple<_Ind...>)
      |    ^~~~~~~~~
/usr/include/c++/9/thread:247:2: error: no type named 'type' in 'struct std::thread::_Invoker<std::tuple<void (*)(bool*, float*, float*, float*), bool*, float (*)[10], float (*)[10], float (*)[10]> >::__result<std::tuple<void (*)(bool*, float*, float*, float*), bool*, float (*)[10], float (*)[10], float (*)[10]> >'
  247 |  operator()()
      |  ^~~~~~~~
/usr/include/c++/9/thread: In instantiation of 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(float*); _Args = {float (*)[10]}; <template-parameter-1-3> = void]':
main.cpp:17:43:   required from here
/usr/include/c++/9/thread:120:44: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
  120 |           typename decay<_Args>::type...>::value,
      |                                            ^~~~~
/usr/include/c++/9/thread: In instantiation of 'struct std::thread::_Invoker<std::tuple<void (*)(float*), float (*)[10]> >':
/usr/include/c++/9/thread:131:22:   required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(float*); _Args = {float (*)[10]}; <template-parameter-1-3> = void]'
main.cpp:17:43:   required from here
/usr/include/c++/9/thread:243:4: error: no type named 'type' in 'struct std::thread::_Invoker<std::tuple<void (*)(float*), float (*)[10]> >::__result<std::tuple<void (*)(float*), float (*)[10]> >'
  243 |    _M_invoke(_Index_tuple<_Ind...>)
      |    ^~~~~~~~~
/usr/include/c++/9/thread:247:2: error: no type named 'type' in 'struct std::thread::_Invoker<std::tuple<void (*)(float*), float (*)[10]> >::__result<std::tuple<void (*)(float*), float (*)[10]> >'
  247 |  operator()()
      |  ^~~~~~~~

I thought that I forgot some ctor arguments for the dma thread but that is not the case.
Here is my code:
#include <iostream>
#include <cstdint>
#include <thread>

void dma_service(bool*, float*, float*, float*);
void live_audio(float*);
void live_draw(float*);

    constexpr int d_size = 10;
    float data[d_size];
    float pwm_cp[d_size];
    float fft_cp[d_size];
    bool drdy = 0;
    std::thread dma_thrd(dma_service, &drdy, &data, &pwm_cp, &fft_cp);
    std::thread audio_thrd(live_draw, &pwm_cp);

int main(){
    for (auto i = 0; i < d_size; i++)
    {
        data[i] = 0;
        pwm_cp[i] = 0;
    }
    printf("Hello, World!\n");
    drdy = 1;

    int k = 3;
    while(k-->0)
    {
        audio_thrd.join();
        printf("\n\n\n");

        for (auto i = 0; i < d_size; i++)
        {
            data[i]++;
        }
        drdy = 1;
    }

}

void dma_service(bool* flag, float* d_array, float* pwm_array, float* fft_array) {
    while (!flag) ;

    for (auto i = 0; i < d_size; i++)
    {
        pwm_array[i] = d_array[i];
        fft_array[i] = d_array[i];
    }

    flag = 0;

}

void live_audio(float* pwm_array) {
    dma_thrd.join();
    printf("Audio Array:\n");
    for (auto i = 0; i < d_size; i++)
    {
        printf("PWM_CP[%d] %f\n", i, pwm_array[i]);
    }
}

I don't have much experience with lambda functions so I have no idea if they're needed here (and would be happy to avoid them).
Thanks for any suggestions!

A: Given float data[d_size];, &data is deduced as a "pointer to array" type. That won't match a float* argument.
You can simply omit &, then array-to-pointer decay will kick in and the types will match.
std::thread dma_thrd(dma_service, &drdy, data, pwm_cp, fft_cp);
std::thread audio_thrd(live_draw, pwm_cp);

Or pass the address of the first element:
std::thread dma_thrd(dma_service, &drdy, &data[0], &pwm_cp[0], &fft_cp[0]);
std::thread audio_thrd(live_draw, &pwm_cp[0]);

Note that this is not sufficient to make the program work. I see it's lacking thread synchronization, and starting threads at global scope like that is problematic because they will start before main(). Also join() in a loop won't work correctly, as join() can be performed only once.

A: To have matching arguments, you need:
constexpr int d_size = 10;
float data[d_size];
float pwm_cp[d_size];
float fft_cp[d_size];
bool drdy = 0;

void dma_service(bool*, float*, float*, float*);
std::thread dma_thrd(dma_service, &drdy, &data[0], &pwm_cp[0], &fft_cp[0]);

Demo
or
constexpr int d_size = 10;
float data[d_size];
float pwm_cp[d_size];
float fft_cp[d_size];
bool drdy = 0;

void dma_service(bool*, float(*)[10], float(*)[10], float(*)[10]);
std::thread dma_thrd(dma_service, &drdy, &data, &pwm_cp, &fft_cp);