Q:

CMake is not finding Boost

I am trying to install CGAL. They describe their installation process as ever-so-simple here, section 6.1. When I run cmake-gui and then click configure, I get the following output:
CMake Error at D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:1192 (message):
  Unable to find the requested Boost libraries.

  Boost version: 1.51.0

  Boost include path: D:/program files/boost_1_51

  The following Boost libraries could not be found:

          boost_thread
          boost_system

  No Boost libraries were found.  You may need to set BOOST_LIBRARYDIR to the
  directory containing Boost libraries or BOOST_ROOT to the location of
  Boost.
Call Stack (most recent call first):
  cmake/modules/CGAL_SetupBoost.cmake:6 (find_package)
  cmake/modules/CGAL_SetupDependencies.cmake:85 (include)
  CMakeLists.txt:590 (include)

But I did set up BOOST_ROOT, in CMake's GUI, to D:/program files/boost_1_51, which exists. And the two libraries it mentions are definitely installed.  What is happening here? What do I need to do?
Attached is the output when running cmake -DBoost_DEBUG=ON:
D:\program files\CGAL-4.1>cmake -DBoost_DEBUG=ON
== Setting paths ==
-- Build CGAL from release in directory CGAL-4.1
-- Packagenames: CGAL-4.1
== Setting paths (DONE) ==

== Generate version files ==
-- CGAL_MAJOR_VERSION=4
-- CGAL_MINOR_VERSION=1
-- CGAL_BUGFIX_VERSION=0
-- CGAL_SONAME_VERSION=10
-- CGAL_SOVERSION     =10.0.0
-- CGAL_REFERENCE_CACHE_DIR=
-- Building shared libraries
-- Targetting Visual Studio 10 Win64
-- Target build enviroment supports auto-linking
-- Using VC10 compiler.
-- Generator uses intermediate configuration directory: $(Configuration)
-- USING CMake version: 2.8.10
-- System: Windows
== Generate version files (DONE) ==

== Set up flags ==
-- Build type: Release
-- USING CXXFLAGS = ' /DWIN32 /D_WINDOWS /W3 /Zm1000 /GR /EHsc -D_CRT_SECURE_NO_
DEPRECATE -D_SCL_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS -D_SCL_SECURE_NO_
WARNINGS /fp:strict /fp:except- /MD /O2 /Ob2 /D NDEBUG'
-- USING LDFLAGS = ' /STACK:10000000 /machine:x64  /INCREMENTAL:NO'
== Set up flags (DONE) ==

== Detect external libraries ==
-- External libraries supported: GMP;MPFR;ZLIB;OpenGL;LEDA;MPFI;RS;RS3;OpenNL;TA
UCS;Eigen3;BLAS;LAPACK;QGLViewer;ESBTL;Coin3D;NTL;IPE
-- Preconfiguring library: GMP ...
-- GMP has been preconfigured:
--   CGAL_UseGMP-file:
--   GMP include:      D:/program files/CGAL-4.1/auxiliary/gmp/include
--   GMP libraries:    D:/program files/CGAL-4.1/auxiliary/gmp/lib/libgmp-10.lib

--   GMP definitions:
-- USING GMP_VERSION = '5.0.1'
-- Preconfiguring library: MPFR ...
-- MPFR has been preconfigured:
--   CGAL_UseMPFR-file:
--   MPFR include:      D:/program files/CGAL-4.1/auxiliary/gmp/include
--   MPFR libraries:    D:/program files/CGAL-4.1/auxiliary/gmp/lib/libmpfr-4.li
b
--   MPFR definitions:
-- USING MPFR_VERSION = '3.0.0'
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:566 ] _b
oost_TEST_VERSIONS = 1.56.1;1.56.0;1.56;1.55.1;1.55.0;1.55;1.54.1;1.54.0;1.54;1.
53.1;1.53.0;1.53;1.52.1;1.52.0;1.52;1.51.1;1.51.0;1.51;1.50.1;1.50.0;1.50;1.49.1
;1.49.0;1.49;1.48.1;1.48.0;1.48;1.47.1;1.47.0;1.47;1.46.1;1.46.0;1.46;1.45.1;1.4
5.0;1.45;1.44.1;1.44.0;1.44;1.43.1;1.43.0;1.43;1.42.1;1.42.0;1.42;1.41.1;1.41.0;
1.41;1.40.1;1.40.0;1.40;1.39.1;1.39.0;1.39;1.38.1;1.38.0;1.38;1.37.1;1.37.0;1.37
;1.56.0;1.56;1.55.0;1.55;1.54.0;1.54;1.53.0;1.53;1.52.0;1.52;1.51.0;1.51;1.50.0;
1.50;1.49.0;1.49;1.48.0;1.48;1.47.0;1.47;1.46.1;1.46.0;1.46;1.45.0;1.45;1.44.0;1
.44;1.43.0;1.43;1.42.0;1.42;1.41.0;1.41;1.40.0;1.40;1.39.0;1.39;1.38.0;1.38;1.37
.0;1.37;1.36.1;1.36.0;1.36;1.35.1;1.35.0;1.35;1.34.1;1.34.0;1.34;1.33.1;1.33
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:568 ] Bo
ost_USE_MULTITHREADED = TRUE
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:570 ] Bo
ost_USE_STATIC_LIBS = OFF
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:572 ] Bo
ost_USE_STATIC_RUNTIME =
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:574 ] Bo
ost_ADDITIONAL_VERSIONS = 1.56.1;1.56.0;1.56;1.55.1;1.55.0;1.55;1.54.1;1.54.0;1.
54;1.53.1;1.53.0;1.53;1.52.1;1.52.0;1.52;1.51.1;1.51.0;1.51;1.50.1;1.50.0;1.50;1
.49.1;1.49.0;1.49;1.48.1;1.48.0;1.48;1.47.1;1.47.0;1.47;1.46.1;1.46.0;1.46;1.45.
1;1.45.0;1.45;1.44.1;1.44.0;1.44;1.43.1;1.43.0;1.43;1.42.1;1.42.0;1.42;1.41.1;1.
41.0;1.41;1.40.1;1.40.0;1.40;1.39.1;1.39.0;1.39;1.38.1;1.38.0;1.38;1.37.1;1.37.0
;1.37
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:576 ] Bo
ost_NO_SYSTEM_PATHS =
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:644 ] De
clared as CMake or Environmental Variables:
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:646 ]
BOOST_ROOT = D:/program files/boost_1_51/bin
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:648 ]
BOOST_INCLUDEDIR =
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:650 ]
BOOST_LIBRARYDIR =
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:652 ] _b
oost_TEST_VERSIONS = 1.56.1;1.56.0;1.56;1.55.1;1.55.0;1.55;1.54.1;1.54.0;1.54;1.
53.1;1.53.0;1.53;1.52.1;1.52.0;1.52;1.51.1;1.51.0;1.51;1.50.1;1.50.0;1.50;1.49.1
;1.49.0;1.49;1.48.1;1.48.0;1.48;1.47.1;1.47.0;1.47;1.46.1;1.46.0;1.46;1.45.1;1.4
5.0;1.45;1.44.1;1.44.0;1.44;1.43.1;1.43.0;1.43;1.42.1;1.42.0;1.42;1.41.1;1.41.0;
1.41;1.40.1;1.40.0;1.40;1.39.1;1.39.0;1.39;1.38.1;1.38.0;1.38;1.37.1;1.37.0;1.37
;1.56.0;1.56;1.55.0;1.55;1.54.0;1.54;1.53.0;1.53;1.52.0;1.52;1.51.0;1.51;1.50.0;
1.50;1.49.0;1.49;1.48.0;1.48;1.47.0;1.47;1.46.1;1.46.0;1.46;1.45.0;1.45;1.44.0;1
.44;1.43.0;1.43;1.42.0;1.42;1.41.0;1.41;1.40.0;1.40;1.39.0;1.39;1.38.0;1.38;1.37
.0;1.37;1.36.1;1.36.0;1.36;1.35.1;1.35.0;1.35;1.34.1;1.34.0;1.34;1.33.1;1.33
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:734 ] lo
cation of version.hpp: D:/program files/boost_1_51/boost/version.hpp
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:754 ] ve
rsion.hpp reveals boost 1.51.0
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:786 ] gu
essed _boost_COMPILER = -vc100
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:796 ] _b
oost_MULTITHREADED = -mt
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:839 ] _b
oost_RELEASE_ABI_TAG = -
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:841 ] _b
oost_DEBUG_ABI_TAG = -gd
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:884 ] _b
oost_LIBRARY_SEARCH_DIRS = D:/program files/boost_1_51/bin/lib;D:/program files/
boost_1_51/bin/stage/lib;D:/program files/boost_1_51/lib;D:/program files/boost_
1_51/../lib;D:/program files/boost_1_51/stage/lib;C:/boost/lib;C:/boost;C:\Progr
am Files (x86)/boost/boost_1_51_0/lib;C:\Program Files (x86)/boost/boost_1_51/li
b;C:\Program Files (x86)/boost/lib;C:\Program Files (x86)/boost;/sw/local/lib
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:962 ] Se
arching for THREAD_LIBRARY_RELEASE: boost_thread-vc100-mt-1_51;boost_thread-vc10
0-mt;boost_thread-mt-1_51;boost_thread-mt;boost_thread
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:994 ] Se
arching for THREAD_LIBRARY_DEBUG: boost_thread-vc100-mt-gd-1_51;boost_thread-vc1
00-mt-gd;boost_thread-mt-gd-1_51;boost_thread-mt-gd;boost_thread-mt;boost_thread

-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:962 ] Se
arching for SYSTEM_LIBRARY_RELEASE: boost_system-vc100-mt-1_51;boost_system-vc10
0-mt;boost_system-mt-1_51;boost_system-mt;boost_system
-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:994 ] Se
arching for SYSTEM_LIBRARY_DEBUG: boost_system-vc100-mt-gd-1_51;boost_system-vc1
00-mt-gd;boost_system-mt-gd-1_51;boost_system-mt-gd;boost_system-mt;boost_system

-- [ D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmake:1108 ] B
oost_FOUND = FALSE
CMake Error at D:/program files/CMake 2.8/share/cmake-2.8/Modules/FindBoost.cmak
e:1192 (message):
  Unable to find the requested Boost libraries.

  Boost version: 1.51.0

  Boost include path: D:/program files/boost_1_51

  The following Boost libraries could not be found:

          boost_thread
          boost_system

  No Boost libraries were found.  You may need to set BOOST_LIBRARYDIR to the
  directory containing Boost libraries or BOOST_ROOT to the location of
  Boost.
Call Stack (most recent call first):
  cmake/modules/CGAL_SetupBoost.cmake:6 (find_package)
  cmake/modules/CGAL_SetupDependencies.cmake:85 (include)
  CMakeLists.txt:590 (include)

-- Boost include:     D:/program files/boost_1_51
-- Boost libraries:
-- Boost definitions:
-- USING BOOST_VERSION = '1.51.0'
== Detect external libraries (DONE) ==

== Write compiler_config.h ==
== Write compiler_config.h (DONE) ==

== Generating build files ==
Configuring libCGAL
-- Requested component: MPFR
-- Requested component: GMP
libCGAL is configured
-- Sources for CGAL component library 'Core' detected
Configuring libCGAL_Core
-- Requested component: MPFR
-- Requested component: GMP
libCGAL_Core is configured
-- Sources for CGAL component library 'ImageIO' detected
Configuring libCGAL_ImageIO
-- Could NOT find ZLIB (missing:  ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
-- OpenGL include:
-- OpenGL libraries:   glu32;opengl32
-- Requested component: MPFR
-- Requested component: GMP
libCGAL_ImageIO is configured
-- NOTICE: CGAL_ImageIO needs ZLib to read compressed files. That feature will n
ot be activated.
-- Sources for CGAL component library 'Qt3' detected
Configuring libCGAL_Qt3
-- CGAL_Qt3 needs Qt3, cannot be configured.
-- Sources for CGAL component library 'Qt4' detected
Configuring libCGAL_Qt4
-- USING OPENGL_VERSION = '1.1'
-- USING QT4_VERSION = '4.8.3'
-- OpenGL include:
-- OpenGL libraries:   glu32;opengl32
-- OpenGL definitions:
-- Qt4 include:        D:/QT/include
-- Qt4 libraries:      optimized;D:/QT/lib/qtmain.lib;debug;D:/QT/lib/qtmaind.li
b;optimized;D:/QT/lib/QtOpenGL4.lib;debug;D:/QT/lib/QtOpenGLd4.lib;optimized;D:/
QT/lib/QtGui4.lib;debug;D:/QT/lib/QtGuid4.lib;optimized;D:/QT/lib/QtCore4.lib;de
bug;D:/QT/lib/QtCored4.lib
-- Qt4 definitions:    -DQT_DLL
-- moc executable:     D:/QT/bin/moc.exe
-- uic executable:     D:/QT/bin/uic.exe
-- Requested component: MPFR
-- Requested component: GMP
libCGAL_Qt4 is configured
-- Sources for CGAL component libraries 'CGAL;Core;ImageIO;Qt3;Qt4' detected
== Generating build files (DONE) ==

-- Configuring incomplete, errors occurred!

(I saw at least three questions with the same title as this question. Each of them had a different answer that worked for the OP, but not for me, so I am sorry to repeat the question...)

A:

Your output shows that CMake is searching for the libraries in the following places:
D:/program files/boost_1_51/bin/lib
D:/program files/boost_1_51/bin/stage/lib
D:/program files/boost_1_51/lib
D:/program files/boost_1_51/../lib
D:/program files/boost_1_51/stage/lib
C:/boost/lib
C:/boost
C:\Program Files (x86)/boost/boost_1_51_0/lib
C:\Program Files (x86)/boost/boost_1_51/lib
C:\Program Files (x86)/boost/lib
C:\Program Files (x86)/boost
/sw/local/lib

It also shows that it's expecting the libraries to be named in a certain way. For example, the release version of Boost.Thread:
boost_thread-vc100-mt-1_51
boost_thread-vc100-mt
boost_thread-mt-1_51
boost_thread-mt
boost_thread

If your Boost libraries do exist in one of the searched locations, then it's probably the name of the library that's the problem. You can adjust the expected name of the Boost libraries by setting the appropriate CMake variables relevant to the FindBoost module.
For example, if you built Boost using bjam with link=static threading=multi then in your CMakeLists.txt before find_package(Boost ...) you'll want to do
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)

Or invoke CMake with -DBoost_USE_STATIC_LIBS=ON -DBoost_USE_MULTITHREADED=ON.
As @noam has pointed out in the comments below, in this particular case, it appears that CGAL requires the shared (DLL) versions of the Boost libraries; passing -DBoost_USE_STATIC_LIBS=ON on the command line doesn't have any effect.

A:

I had this error, but I have progressed.
I was using the CMake GUI, ticked the checkbox "Advanced" (between checkbox "Grouped" and button "Add Entry"), and ticked the newly seen checkbox "CGAL_Boost_USE_STATIC_LIBS".
You may need to press "Configure" an extra time or two before the extra options are revealed.


Q:

Coalesce columns with capitalised and non capitalised versions of variables names without specifying the variable names

I have a (large) data frame as follows:
library(data.table)
DT <- fread(
"ID country year A b B a
4   NLD   2002  NA   1   NA   0
5   NLD   2002  NA   0   NA   1
6   NLD   2006  NA   1   NA   1
7   NLD   2006  NA   0   NA   0
8   NLD   2006  0   NA   0   NA
9   GBR   2002  0   NA   0   NA
10  GBR   2002  0   NA   0   NA
11  GBR   2002  0   NA   0   NA
12  GBR   2006  1   NA   1   NA
13  GBR   2006  1   NA   0   NA",
header = TRUE)

I would simply like to merge variables A and a, and, B and b.
EDIT: The problem is that I have to do this for more than 1000 variables, so I would like to avoid specifying either the column names which need not to be checked or the ones that do.
I was hoping for a solution that first splits the columns into a group for which there is no non-capitalised alternative, and a group for which there is.
As far as I understand the solution here:
Coalesce columns based on pattern in R
It still requires to provide the variables names for which the case needs to be checked. If I misunderstand this solution, which is very much possible, please let me know. In any case, as explained, I need a solution without specifically specifying the variables.
I found a good start here.
That solution has however a slightly different approach than the one I need.
How do I make such a variable merge conditional on something like tolower(varname) == varname ?
Desired output:
DT <- fread(
"ID country year A B
4   NLD   2002  0  1
5   NLD   2002  1  0
6   NLD   2006  1  1
7   NLD   2006  0  0
8   NLD   2006  0  0
9   GBR   2002  0  0
10  GBR   2002  0  0
11  GBR   2002  0  0
12  GBR   2006  1  1
13  GBR   2006  1  0 ",
header = TRUE)

A:

The OP is using data.table, so the question deserves a data.table answer.
The approach below is similar to sindri_baldur's answer in general but differs in important details. In particular,

it will also coalesce multiple columns like "CC", "cc", "cC" covering the different ways of writing variable names, e.g., upper case, lower case, as well as lower and upper camel case.
it will return a description of the columns which have been coalesced.

library(data.table)
library(magrittr) # piping is used to improve readability
names(DT) %>%
  data.table(orig = ., lc = tolower(.)) %>%
  .[, {
    if (.N > 1L) {
      new <- toupper(.BY)
      old <- setdiff(orig, new)
      DT[, (new) := fcoalesce(.SD), .SDcols = orig]
      DT[, (old) := NULL]
      sprintf("Coalesced %s onto %s", toString(old), new)
    }
  }, by = lc]
DT[]

   lc                 V1
1:  a Coalesced a onto A
2:  b Coalesced b onto B

DT[]

    ID country year A B
 1:  4     NLD 2002 0 1
 2:  5     NLD 2002 1 0
 3:  6     NLD 2006 1 1
 4:  7     NLD 2006 0 0
 5:  8     NLD 2006 0 0
 6:  9     GBR 2002 0 0
 7: 10     GBR 2002 0 0
 8: 11     GBR 2002 0 0
 9: 12     GBR 2006 1 1
10: 13     GBR 2006 1 0

For another use case
DT2 <- fread(
  "ID country year A b B a CC cc cC
4   NLD   2002  NA   1   NA   0   1  NA  NA
5   NLD   2002  NA   0   NA   1  NA   2  NA
6   NLD   2006  NA   1   NA   1  NA  NA   3
7   NLD   2006  NA   0   NA   0  NA  NA  NA
8   NLD   2006  0   NA   0   NA   1  NA  NA
9   GBR   2002  0   NA   0   NA  NA   2  NA
10  GBR   2002  0   NA   0   NA  NA  NA   3
11  GBR   2002  0   NA   0   NA   1  NA  NA
12  GBR   2006  1   NA   1   NA  NA   2  NA
13  GBR   2006  1   NA   0   NA  NA  NA   3",
  header = TRUE)
DT <- copy(DT2)

above code returns

   lc                       V1
1:  a       Coalesced a onto A
2:  b       Coalesced b onto B
3: cc Coalesced cc, cC onto CC

DT[]

    ID country year A B CC
 1:  4     NLD 2002 0 1  1
 2:  5     NLD 2002 1 0  2
 3:  6     NLD 2006 1 1  3
 4:  7     NLD 2006 0 0 NA
 5:  8     NLD 2006 0 0  1
 6:  9     GBR 2002 0 0  2
 7: 10     GBR 2002 0 0  3
 8: 11     GBR 2002 0 0  1
 9: 12     GBR 2006 1 1  2
10: 13     GBR 2006 1 0  3

Explanation

The column names are turned into a data.table with a additional column lc of the lower case versions of the column names.
Instead of a for loop we use grouping by = and data.table's feature to evaluate any expression, even with side effects. So, DT is updated by reference for each distinct value of lc within the scope of the data.table which was created on-the-fly in step 1 but only if there is more than one column in the group.

Future extensions
This approach can be extended to coalesce columns which use underscore, dots, or blanks "_", ".", " "in its column names, e.g., "var_1", "VAR.1", "Var 1".


Q:

Cambiar color del texto al dar scroll

Tengo un menú que al bajar la página, éste continúa ahí y el color cambia de transparente a blanco, pero la letra deseo que cambie a negro.
Tengo en mi código JS que tome el identificador del div padre y cambie a todos sus hijos el color. Pues no me funciona, ya he intentado de varias formas y aun no he dado con el clavo.
Pongo mi código (también en JSFiddle):

window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    document.getElementById("navbar").style.height = "75px";
    document.getElementById("navbar").style.backgroundColor = "#fff";
    document.getElementById("navbar").style.color = "#000";
    document.getElementById("navbar").style.line - height;
    "37.5px";
  } else {
    document.getElementById("navbar").style.height = "100px";
    document.getElementById("navbar").style.backgroundColor = "blue";
    document.getElementById("navbar").style.color = "#000";
    document.getElementById("navbar").style.line - height;
    "50px";
  }
}
a {
  text-decoration: none;
  list-style: none;
  color: white;
}

#cabecera {
  width: 100%;
  height: 755px;
}

#navbar {
  overflow: hidden;
  background-color: blue;
  transition: 0.4s;
  position: fixed;
  width: 100%;
  height: 100px;
  z-index: 99;
}

#navbar .container {
  width: 90%;
  height: 100%;
  align-items: center;
  display: flex;
  left: 0;
  right: 0;
}

#navbar #title {
  display: inline-block;
  line-height: inherit;
  white-space: nowrap;
  width: 30%;
}

#navbar .container .menu {
  width: 70%;
  margin-left: 50px;
  display: inline-block;
  line-height: inherit;
  white-space: nowrap;
}

#navbar .container .menu>a {
  width: 100%;
  height: 100%;
  padding-right: 50px;
}

      JORGE ACEVEDO

        Jorge Acevedo
        Mis Propuestas
        Contacto

A:

Esto es un problema con la precedencia de los selectores y la herencia de valores en CSS.
Le estás cambiando el color al texto del elemento con id navbar, pero en el CSS tienes declarado que el color de los a será blanco. Entonces no importa que le cambies el color al navbar con JavaScript, porque los a dentro del navbar tienen su propio color en el CSS.
Una solución rápida sería:

Ponerle a los a un valor de color igual a inherit, de este modo heredará el color del padre/ancestro que lo tenga definido.
a {
  color: inherit;
  ...
}

Ponerle al navbar el blanco como color inicial.
#navbar {
  color: white;
  ...
}

Aquí puedes ver tu código con esos dos cambios:

Nota: he corregido un pequeño bug (el color nunca se ponía como blanco al hacer scroll hacia arriba) porque estaba relacionado con la pregunta, pero he dejado sin tocar otra parte del código que contiene errores (height no está definido) porque no están relacionados con el problema de la pregunta.

window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    document.getElementById("navbar").style.height = "75px";
    document.getElementById("navbar").style.backgroundColor = "#fff";
    document.getElementById("navbar").style.color = "#000";
    document.getElementById("navbar").style.line - height;
    "37.5px";
  } else {
    document.getElementById("navbar").style.height = "100px";
    document.getElementById("navbar").style.backgroundColor = "blue";
    document.getElementById("navbar").style.color = "#fff";
    document.getElementById("navbar").style.line - height;
    "50px";
  }
}
a {
  text-decoration: none;
  list-style: none;
  color: inherit;
}

#cabecera {
  width: 100%;
  height: 755px;
}

#navbar {
  overflow: hidden;
  background-color: blue;
  transition: 0.4s;
  position: fixed;
  width: 100%;
  height: 100px;
  z-index: 99;
  color: white;
}

#navbar .container {
  width: 90%;
  height: 100%;
  align-items: center;
  display: flex;
  left: 0;
  right: 0;
}

#navbar #title {
  display: inline-block;
  line-height: inherit;
  white-space: nowrap;
  width: 30%;
}

#navbar .container .menu {
  width: 70%;
  margin-left: 50px;
  display: inline-block;
  line-height: inherit;
  white-space: nowrap;
}

#navbar .container .menu>a {
  width: 100%;
  height: 100%;
  padding-right: 50px;
}

      JORGE ACEVEDO

        Jorge Acevedo
        Mis Propuestas
        Contacto


Q:

asp mvc - generic repository and unit of work - override repository method

I am new to repository patterns in ASP MVC 2 and I am trying to figure out how to extend an operation in my generic repository class, and am having trouble figuring out how do it or find examples of it online.  I want a generic repository and unit of work that will work for most cases, but want something easy to alter slightly for special cases.
I have the following generic repository interface and repository:
public interface IRepository<TEntity> where TEntity : class
{
    List<TEntity> Get();
    TEntity GetByKey(object key);
    void Insert(TEntity entity);
    void Delete(TEntity entity);
    void Save();
}

public class RepositoryBase<TEntity> : IRepository<TEntity> where TEntity : class
{
    private readonly string entity_set_name;
    public readonly string entity_key_name;

    private ObjectContext object_context;
    private ObjectSet<TEntity> object_set;

    public RepositoryBase(ObjectContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        object_context = context;
        object_set = object_context.CreateObjectSet<TEntity>();

        entity_set_name = object_set.EntitySet.Name;
        entity_key_name = object_set.EntitySet.ElementType.KeyMembers.Single().Name;
    }

    public virtual List<TEntity> Get()
    {
        return object_set.ToList();
    }

    public virtual TEntity GetByKey(object key)
    {
        var entityKey = new EntityKey(entity_set_name, entity_key_name, key);
        return (TEntity)object_context.GetObjectByKey(entityKey);
    }

    public virtual void Insert(TEntity entity)
    {
        object_set.AddObject(entity);
    }

    public virtual void Delete(TEntity entity)
    {
        object_set.DeleteObject(entity);
    }

    public virtual void Save()
    {
        object_context.SaveChanges();
    }
}

...and the following Unit of Work class:
public class UnitOfWork : IDisposable
{
    private MyEntities context = null;
    public Dictionary<Type, object> repositories = new Dictionary<Type, object>();

    public UnitOfWork()
    {
        context = new EmployeeAccessFormEntities();
    }

    public IRepository<TEntity> Repository<TEntity>() where TEntity : class
    {
        if (repositories.Keys.Contains(typeof(TEntity)) == true)
        {
            return repositories[typeof(TEntity)] as IRepository<TEntity>;
        }
        IRepository<TEntity> r = new RepositoryBase<TEntity>(context);
        repositories.Add(typeof(TEntity), r);
        return r;
    }

    public virtual void Save()
    {
        context.SaveChanges();
    }

    #region IDisposable Members

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    #endregion
}

I have a specific type of entity that needs additional work added to the insert method.  I want to do someting like:
public partial class MyEntity : RepositoryBase<MyEntity>
{
    public override void Insert(MyEntity entity)
    {
        // do additional work

        base.Insert(entity);
    }
}

...but I receive an error that "Partial declarations must not specify different base classes."
So my question is, where would I be able to put that overridden Insert method?  Do I have to make a seperate repository that inherits the generic repository?  If I did that, how would I need to change my unit of work class?
Thank you for any advice.

A:

I think I understand this better after some time, so figured I would close it.  I didn't need to "override" anything, I just needed to add the additional work in my unit of work class (duh), and then call the insert.  Thanks for the thought provoking responses.


Q:

Updating an Entity in EF with a 1:1 relationship

I have an application with 4 layers:
-Core           (Models)
-Repository     (EF DbContext actions)
-Service        (Business logic)
-Web            (MVC)

I'm trying to update an object with a 1:1 relationship with EF using the following method:
    public async Task<bool> UpdateProductTicketing(ProductTicketing ticketing)
    {
        var product = await GetProductByIdAsync(ticketing.ProductId);

        // Validation removed for simplicity

        // 'ticketing' passed validation so let's
        // just replace it with the existing record.
        product.Ticketing = ticketing;

        _repo.ProductRepository.Update(product);
        return await _repo.SaveAsync();
    }

This works for an initial insert, but it doesn't work as I'd expect when I'm updating the record:
A first chance exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred...

The actual error message is:
Violation of PRIMARY KEY constraint 'PK_dbo.ProductTicketing'. Cannot insert duplicate key in object 'dbo.ProductTicketing'. The statement has been terminated.

Obviously the PK and FK "ProductId" doesn't change - so why does EF try to drop and insert my record instead of just updating it, and why does it fail?
But more importantly - how can I prevent this. I know I can manually map the object values and then update it - that works but it's tedious mapping two identical objects together and doesn't feel correct.
My repository for retrieving the Product object is in my Repository layer, while the method above is in my Service layer.
This is how I'm currently resolving this - and it looks as dirty as it feels:
    public async Task<bool> UpdateProductTicketing(ProductTicketing ticketing)
    {
        var product = await GetProductByIdAsync(ticketing.ProductId);

        // Validation removed for simplicity

        if (product.Ticketing == null)
        {
            product.Ticketing = ticketing;
        }
        else
        {
            product.Ticketing.AllowEventBooking = ticketing.AllowEventBooking;
            // Doing the same for all other properties etc
            // etc
            // etc
        }

        _repo.ProductRepository.Update(product);
        return await _repo.SaveAsync();
    }

How can I achieve this without doing all this horrible mapping an object to an identical object?
Edit
Here are the two models referred to above:
[Table(@"Products")]
public class Product
{
    [Key]
    public int Id { get; set; }
    public virtual ProductTicketing Ticketing { get; set; }
    // Removed others for clarity

    [Timestamp]
    public byte[] RowVersion { get; set; }
}

[Table(@"ProductTicketing")]
public class ProductTicketing
{
    [Key, ForeignKey("Product")]
    public int ProductId { get; set; }

    public bool AllowEventBooking { get; set; }
    // Removed others for clarity

    public virtual Product Product { get; set; }
}

It's also probably worth noting that the "ProductTicketing" object I'm passing into the UpdateProductTicketing method is a new object created from values in my controller - but the ID is the same so I assume it should work.

A:

I think I see the problem now - when you do product.Ticketing = ticketing;, EF treats this as a new insert.
To avoid this, you can do one of these things:

Continue using the workaround (which is not a wokaround actually but just the way EF expects you to tell when to insert vs. when to update).
Now this depends on rest of your code and design, but instead of fetching the product, you can fetch the ticket and update its properties. Of course, this means that if the ticketing is not found, you need to insert it which then kinda looks like what you're already doing with UpdateProductTicketing.
Use the InsertOrUpdate pattern (I made some assumptions about your code but hopefully it gives you the idea - the main thing here is the InsertOrUpdate method):
public class ProductRepository : IRepository
{
    private SomeContext context;

    public void InsertOrUpdate(ProductTicketing ticketing)
    {
        context.Entry(ticketing).State = ticketing.ProductId == 0 ?
                                       EntityState.Added :
                                       EntityState.Modified;
        context.SaveChanges();
    }
}

// And a generic version
public void InsertOrUpdate<T>(T entity) where T : class
{
    if (context.Entry(entity).State == EntityState.Detached)
        context.Set<T>().Add(entity);

    context.SaveChanges();
}


Q:

Scale 1080p screen to 720p - everything is too small

I used to work on a 720p laptop screen, and now I have a new 1080p laptop screen with the same 15.6" size. With this higher resolution, everything is too small, and my eyes get tired faster. Is it possible to scale everything to 720p but keep the resolution 1080p?
I tried using Accessibility, but that doesn't scale everything.

A:

Yes you can, go in : Parameters > Display and set  “Scale for menu and title bars” to the value that is best suited for you.

It will scale all your desktop while keeping your original 1080p resolution.


Q:

i want to delete multible inputs by notepad++

i have this regular expression
replace this
^(\d+.\d+.\d+.\d+ )(.+)\r\n(\1.+\r\n)*
to
\1\2\r\n
it's make this results
replacing this
109.172.14.61 : 1 : 1
109.172.14.61 : 1 : 8888
109.172.14.61 : 2 : 1234
109.172.14.61 : 2 : 8888
109.172.60.153 : 73 : 73
109.188.66.153 : 11 : 0000
109.188.66.153 : 11 : 123456
109.188.83.137 : 2010 : 22222

to this
109.172.14.61 : 1 : 1
109.172.60.153 : 73 : 73
109.188.83.137 : 2010 : 22222

but i need another result
i want this
109.172.14.61 : 1 : 1
109.172.14.61 : 1 : 8888
109.172.14.61 : 2 : 1234
109.172.14.61 : 2 : 8888
109.172.60.153 : 73 : 73
109.188.66.153 : 11 : 0000
109.188.66.153 : 11 : 123456
109.188.83.137 : 2010 : 22222

to this
109.172.14.61 : 1 : 1
109.172.14.61 : 2 : 1234
109.172.60.153 : 73 : 73
109.188.66.153 : 11 : 0000
109.188.83.137 : 2010 : 22222

any help please !!

A:

Have a try with:
Find what: ^(\d+(?:\.\d+){3}\s+:\s+\d+)(.+?)\R(?:\1.+?\R)*
Replace with: $1$2\r\n
Explanation:
^           : start line
(           : begin capture group 1
  \d+       : 1 or more digits
  (?:       : begin NON capture group
    \.      : a dot
    \d+     : 1 or more digits
  ){3}      : non capture group repeated 3 times
  \s+       : 1 or more space
  :         : semi-colon
  \s+       : 1 or more space
  \d+       : 1 or more digits
)           : end of group 1
(           : begin group 2
  .+?       : 1 or more any character but newline non greedy
)           : end group 2
\R          : any kind of line break (\n or \r\n or \r)
(?:         : begin non capture group
  \1        : same content as group 1
  .+?       : 1 or more any character but newline non greedy
  \R        : any kind of line break (\n or \r\n or \r)
)*          : non capture group repeated 0 or more times.


Q:

Random number generator code fix (alternative for srand48/drand48)

Let me start by saying that I know near nothing about C and C++. In fact, as a Mathematics major, I'm totally new to programming. That being said, I need to wrap some older code so am trying to struggle through it. Now, when trying to run a test, I get the error

Severity  Code    Description Project File    Line    Suppression State
  Error LNK2019 unresolved external symbol srand48 referenced in
  function main PokerEval   C:\Users\M.Faas\Documents\Visual Studio
  2017\Projects\Pokerproject\PokerEvalC\PokerEval\allfive.obj   1
  Error LNK2019 unresolved external symbol drand48 referenced in
  function shuffle_deck PokerEval   C:\Users\M.Faas\Documents\Visual
  Studio 2017\Projects\Pokerproject\PokerEvalC\PokerEval\pokerlib.obj   1
  Error LNK1120 2 unresolved
  externals PokerEval   C:\Users\M.Faas\Documents\Visual Studio
  2017\Projects\Pokerproject\PokerEvalC\PokerEval\x64\Debug\PokerEval.exe   1

And the same for drand48.
The code I'm using starts as follows:
#include <stdio.h>
#include "arrays.h"
#include "poker.h"

void srand48();
double drand48();

And continues to use srand48 and drand48 in these snippets of code:
// Seed the random number generator.
srand48(getpid());

And for drand48:
//
//  This routine takes a deck and randomly mixes up
//  the order of the cards.
//
void
shuffle_deck(int *deck)
{
    int i, n, temp[52];

    for (i = 0; i < 52; i++)
        temp[i] = deck[i];

    for (i = 0; i < 52; i++)
    {
        do {
            n = (int)(51.9999999 * drand48());
        } while (temp[n] == 0);
        deck[i] = temp[n];
        temp[n] = 0;
    }
}

The full code can be found here: http://suffe.cool/poker/code/
But I can't think of a way to fix this issue, even though it seems very minor. That said, speed is absolutely essential, as the code will be run several millions of times. I'm using visualstudio on a x64 machine.

A:

These declarations
void srand48();
double drand48();

are deprecated, you should use full prototypes instead:
void srand48(long);
double drand48(void);

or better include the header where they are declared.
But your problem is that these functions don't even exist on windows. So just remove these declarations. You can emulate these functions (with maybe a bit lower quality of the random numbers) using the standard srand() and rand() functions (declared in stdlib.h) like this:
#define srand48(x) srand((int)(x))
#define drand48() ((double)rand()/RAND_MAX)

Here's a little PoC example:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define srand48(x) srand((int)(x))
#define drand48() ((double)rand()/RAND_MAX)

int main(void)
{
    srand48(time(0));

    for (;;)
    {
        printf("%f\n", drand48());
    }
}


Q:

Retrica displays blue pixels instead of the captured image on Android 2.x

I installed Retrica on my Samsung Galaxy SL I9003, but when I opened it I could only see blue pixels instead of the image captured by my camera. I tried to change the parameters of the app, reboot my phone and reinstall it, but it's not working anyway.
How can I fix this?

A:

I read on Retrica's website that they're aware of this problem for android 2.x devices and they're working to fix it.


Q:

Serving local json files: how to cache

I have some local files, they are filled with pure json text.
I have a php script that serves them. I use php because it allows me to serve them in a zipped format, depending on the capabilities specified in the request. This is much leaner.
The php does this by getting an url parameter, fetching the file, and dumping its (zipped) output on the stream.
Still, now I'm wondering how to cache these files. How can I specify in the php code that the file will not have changed, so that the client can use a cached version of that response?
Or is there an option to serve these files statically in a zipped manner so caching is performed by the static web server? (I'm using httpd).

A:

Apache 1.3 uses mod_gzip while Apache 2.x uses mod_deflate. You can compress you content without using php script dpending upon type of request. Use following lines in your apache config to deflate/gzip static content:
AddOutputFilterByType DEFLATE application/javascript

You can also add far future expire header for static content using apache. You do not need to use php script for that. Add this line to your apache config for static content:
ExpiresActive On
ExpiresDefault "access plus 4 hours"
ExpiresByType application/javascript "access plus 1 year"

You can also add it to a .htaccess file in your static content directory


Q:

Build warnings vs IntelliSense warnings

I just joined a company with legacy code.
The build has over 10000 warnings.
90% of the warnings are "obsolete" warnings.
My coworkers don't want me to disable those warnings, because it is useful for them in IntelliSense.
My question is: is there a practical way, where I can still see the warning in the editor in Visual Studio, but it does not show up in the build.log?

A:

Is there a practical way, where i can still see the warning in the editor in visual studio, but it does not show up in the build.log?

Since you can not disable those warnings and using #pragma warning disable is not your option, I would like provide your a workaround to resolve this question.
You can managed to supress the warning level with /p:WarningLevel=X with MSBuild command line.
For example, when I build the sample project from Visual Studio, there is a warining in the error list window:

Then I build it with MSBuild command line with property /p:WarningLevel=0 in the command line:
msbuild "YourProjectName" /fl /flp:logfile=D:\MyProjectOutput.log;verbosity=diagnostic /p:WarningLevel=0

The meaning of the level:
Warning
Level    Meaning
-------- -------------------------------------------
      0  Turns off emission of all warning messages.

      1  Displays severe warning messages

      2  Displays level 1 warnings plus certain, less-severe warnings, such
         as warnings about hiding class members

      3  Displays level 2 warnings plus certain, less-severe warnings, such
         as warnings about expressions that always evaluate to true or false

      4  (the default) Displays all level 3 warnings plus informational warnings

There is no warining in the build log, then open the log file, there is also no warning here:

Hope this helps.


Q:

Java compiler can't find the CMSProcessableInputStream for bouncycastle

I pulled this example from the following link.  I am having problems because I can't get the compiler to find the CMSProcessableInputStream class.
Does anyone have any suggestions?
https://apache.googlesource.com/pdfbox/+/5f032354760374773f7339bbad2678d3281e90ee/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateVisibleSignature.java
This is a snippet of my pom.xml:
        <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>1.8.9</version>
    </dependency>
   <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.6</version>
   </dependency>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcpg-jdk16</artifactId>
        <version>1.46</version>
    </dependency>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk16</artifactId>
        <version>1.46</version>
    </dependency>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcmail-jdk16</artifactId>
        <version>1.46</version>
    </dependency>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-ext-jdk16</artifactId>
        <version>1.46</version>
    </dependency>

This is the code:
    @Override
public byte[] sign(InputStream content) throws SignatureException,
        IOException {
    CMSProcessableInputStream input = new CMSProcessableInputStream(content);
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    // CertificateChain
    List<Certificate> certList = Arrays.asList(cert);
    CertStore certStore = null;
    try {
        certStore = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(certList), provider);
        gen.addSigner(privKey, (X509Certificate) certList.get(0),
                CMSSignedGenerator.DIGEST_SHA256);
        gen.addCertificatesAndCRLs(certStore);
        CMSSignedData signedData = gen.generate(input, false, provider);
        return signedData.getEncoded();
    } catch (Exception e) {
        // should be handled
        System.err.println("Error while creating pkcs7 signature.");
        e.printStackTrace();
    }
    throw new RuntimeException("Problem while preparing signature");
}

A:

1.
The CMSProcessableInputStream class is part of the CreateSignature class (without the word "visible") which is in the same package, which you can find in the source download of PDFBox. Get it here:
https://pdfbox.apache.org/downloads.html#recent
and click on "pdfbox-1.8.9-src.zip", and then look for pdfbox-1.8.9\examples\src\main\java\org\apache\pdfbox\examples\signature\CreateSignature.java in the zip file.
2.
The 1.8.9 version of PDFBox uses bc version 1.44, as shown on the official website:
<dependency>
  <groupId>org.bouncycastle</groupId>
  <artifactId>bcprov-jdk15</artifactId>
  <version>1.44</version>
</dependency>
<dependency>
  <groupId>org.bouncycastle</groupId>
  <artifactId>bcmail-jdk15</artifactId>
  <version>1.44</version>
</dependency>

Another solution is to use pdfbox-app, which has bc within.
A general hint: use source code that you find with google at your own risk. You don't know what version it is, or if it is correct. Try looking at the official website first.


Q:

Bash Terminal: Write only specific lines to logfile

I'm running simulation with lots of terminal output, which would exceed my disc space, if I'd save it to a logfile (e.g by "cmd > logfile"). Now I would like to follow the entire terminal output, but at the same time I would like to save specific data/lines/values from this output to a file.
1) Is there a way to that in bash?
2) Or as alternative: Is it possible to save the logfile, extract the needed data and then delete the processed lines to avoid generating a huge logfile?

A:

If you want to save into logfile only the output containing mypattern but you want the see all the output at the terminal, you could issue:
cmd 2>&1 | tee /dev/tty | grep 'mypattern' > logfile

I also assumed that the output of cmd may be directed to the standard output stream as well as to the standard error stream, by adding 2>&1 after cmd.


Q:

How to disable Ctrl-Space selecting chinese keyboard on windows 7?

I would like to use both chinese keyboard and eclipse ctrl-space for suggestions popup. Since I use chinese very rare, I would like just to disable ctrl-space selecting this language.
I have removed this combination from windows' chinese keyboard setup, but it either returns (if I remove) or just works without setting (if chaged).
Hot to disable ctrl-space totally for keyboard?

A:

I've been aware of this Windows bug for years. After tons of unsatisfying workarounds and fruitless searching the one or two times a year I attempt to find a solution, I finally have it!
Procedure

Go to Start > Type in regedit and start it
Navigate to HKEY_CURRENT_USER/Control Panel/Input Method/Hot Keys
Select the key named:

00000070 for the Chinese (Traditional) IME - Ime/NonIme Toggle hotkey
00000010 for the Chinese (Simplified) IME - Ime/NonIme Toggle hotkey

In the right sub-window, there are three subkeys.

Key Modifiers designate Alt/Ctrl/Shift/etc and is set to Ctrl (02c00000).
Virtual Key designates the finishing key and is set to Space (20000000).

Change the first byte in Key Modifiers from 02 to 00
Change the first byte in Virtual Key from 20 to FF
Log off and log back on. I don't think it's necessary to restart.
Do not change the Hot keys for input languages in Control Panel, unless you want to do this all over again.

Notes: Symptoms
Each registry key (thing that looks like a folder) is for each specific hotkey setting that you would normally find in Control Panel > Region and Language > Keyboards and Languages > Change keyboards... > Advanced Key Settings > Hot keys for input languages. The recurring bug is the hotkey being automatically reset to Ctrl+space even if changed via the GUI.
This is for Windows 7 64-bit, though from my research, it looks like it may work for XP and Vista as well.
Sources:
Traditional Chinese Pocket IME Hot Key Registry Settings
Simplified Chinese MSPY 3.0 IME Hot Key Registry Settings


Q:

How to make the program give an error message when an incorrect ticker symbol is entered in a program that scrapes websites for stock data

I am coding a project in which the user inputs the ticker of a stock, and then the program scrapes information about that stock from a specific website and returns the data. I have a fully working program, but an issue I have is that if the user enters a nonexistent stock ticker, the program gives an error and stops working. How can I fix this? Here is the relevant code segment for reference:
def make_url(ticker_symbol): #making a function that returns a URL when a ticker is passed through it
return "https://www.bloomberg.com/quote/%s:US" % ticker_symbol

def Calculation():
lower_stock = Ticker_entry.get()
stock = lower_stock.upper()
url = make_url(stock)
page = requests.get(url) #requesting the HTML code of the website
soup = BeautifulSoup(page.content, "lxml") #Converting the HTML code of the website into a beautifulsoup object

How do I make it such that if the user enters a nonexistent stock, the program gives a message saying "Please enter a valid stock ticker."?
Here is the full code for reference:
import matplotlib
import sys
from requests.exceptions import ConnectionError
import matplotlib.dates as dates
from tkinter import *
from bs4 import BeautifulSoup
import requests
import lxml
import datetime
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt

#Graphical User Interface
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
root = Tk()
root.title("Stock Price")
root.configure(background="white")

Calculator = Frame(root, height=300, width=700, bg="white").grid(column=0, row=2)
title = Label(root, bg="white", text="Stock Price Calculator", font="Sans 25 bold", fg="black").grid(row=0)

Stock_ticker = Label(root, text="Input stock ticker here:", font="Sans 18 bold")
Stock_ticker.place(x=7, y=60)
Ticker_entry = Entry(root, width=10)
Ticker_entry.place(x=235, y=64)

Stock_price = Label(root, text="Current stock price:", font="Sans 15")
Stock_price.place(x=7, y=100)

Stock_price_output = Entry(root, width=10)
Stock_price_output.place(x=160, y=100)

Stock_price_day = Label(root, text="Opening price for the day:", font="Sans 15")
Stock_price_day.place(x=7, y=140)

Stock_price_day_output = Entry(root, width=10)
Stock_price_day_output.place(x=195, y=141)

Last_closing_price = Label(root, text="Last closing price:", font="Sans 15")
Last_closing_price.place(x=7, y=180)

Last_closing_price_output = Entry(root, width=10)
Last_closing_price_output.place(x=180, y=181)

Stock_news = Label(root, text="News about stock:", font="Sans 15")
Stock_news.place(x=7, y=220)

Stock_news_output1 = Entry(root, width=50)
Stock_news_output1.place(x=150, y=221)

Stock_news_output2 = Entry(root, width=50)
Stock_news_output2.place(x=150, y=242)

Stock_news_output3 = Entry(root, width=50)
Stock_news_output3.place(x=150, y=263)

Submit = Button(root, text="Submit", font="Sans 14", command = lambda: Calculation())
Submit.place(x=165, y=300)

Reset = Button(root, text="Reset", font="Sans 14", command = lambda: Cleaning(Ticker_entry, Stock_price_output, Stock_price_day_output, Last_closing_price_output, Stock_news_output1, Stock_news_output2, Stock_news_output3))
Reset.place(x=250, y=300)
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

def make_url(ticker_symbol): #making a function that returns a URL when a ticker is passed through it
    return "https://www.bloomberg.com/quote/%s:US" % ticker_symbol

def make_historical_url(ticker_symbol):
    return "https://www.nasdaq.com/symbol/%s/historical" % ticker_symbol

def Calculation():
    lower_stock = Ticker_entry.get()
    stock = lower_stock.upper()
    url = make_url(stock)
    page = requests.get(url) #requesting the HTML code of the website
    soup = BeautifulSoup(page.content, "lxml") #Converting the HTML code of the website into a beautifulsoup object

    #Finding and inserting the current price
    current_number = soup.find('span', attrs={'class':'priceText__1853e8a5'})
    current_price = current_number.text
    Stock_price_output.insert(0, "$")
    Stock_price_output.insert(1, current_price)

    #Finding and inserting opening price
    opening_number = soup.find('div', attrs={'class':'value__b93f12ea'})
    opening_price = opening_number.text
    Stock_price_day_output.insert(0, "$")
    Stock_price_day_output.insert(1, opening_price)

    #Finding and inserting last closing price
    closing_numbers = soup.find_all('div', attrs={'class':'value__b93f12ea'})
    closing_number = closing_numbers[1]
    closing_price = closing_number.text
    Last_closing_price_output.insert(0, "$")
    Last_closing_price_output.insert(1, closing_price)

    #Finding and inserting news
    news = soup.find_all('div', attrs={'class':'headline__07dbac92'})
    news_1 = news[1].text
    news_2 = news[2].text
    news_3 = news[3].text

    Stock_news_output1.insert(0, news_1)
    Stock_news_output2.insert(0, news_2)
    Stock_news_output3.insert(0, news_3)

    #Drawing the graph of the stock
    historical_url = make_historical_url(stock)
    historical_page = requests.get(historical_url)
    soup_2 = BeautifulSoup(historical_page.content, "lxml")
    all_numbers = soup_2.find('tbody')
    all_nums = all_numbers.text
    all_nums_1 = all_nums.split()
    length = len(all_nums_1)

    prices = []
    dates = []

    current_time = datetime.datetime.now()
    current_time_format = current_time.strftime("%m/%d/%Y")
    all_nums_1[0] = current_time_format

    for t in range(int(length/6)):
        index = t * 6 + 4
        prices.append(all_nums_1[index])

    for t in range(int(length/6)):
        index = t * 6
        date_str = all_nums_1[index]
        format_str = '%m/%d/%Y'
        datetime_object = datetime.datetime.strptime(date_str, format_str)
        dates.append(datetime_object)

    final_dates = matplotlib.dates.date2num(dates)

    #plotting the graph of the last 3 months of stock price
    plt.plot_date(final_dates, prices, '-o')
    plt.xticks(rotation=90)
    plt.xlabel('Date')
    plt.ylabel('Price ($)')
    plt.suptitle("Price of the %s stock in the last 3 months" % stock)
    plt.show()

def Cleaning(writing_area1, writing_area2, writing_area3, writing_area4, writing_area5, writing_area6, writing_area7):
        writing_area1.delete(0, END)
        writing_area2.delete(0, END)
        writing_area3.delete(0, END)
        writing_area4.delete(0, END)
        writing_area5.delete(0, END)
        writing_area6.delete(0, END)
        writing_area7.delete(0, END)

root.mainloop()

Thanks!

A:

I initially suggested monitoring HTTP status code, however this is a non-starter as Bloomberg will automatically redirect you to a simple page to state that a ticker is invalid. However, this page has a standardised message:
The search for XYZ:US produced no matches. Try the symbol search.
Thus, searching for a portion of that string will do the trick, don't even need to specifiy the exact ticker value:
import requests, lxml
from bs4 import BeautifulSoup

r = requests.get('https://www.bloomberg.com/quote/XYZ:US')
soup = BeautifulSoup(r.content, "lxml")

f = soup.find_all("div", "premium__message")

if 'produced no matches' in str(f):
    # do something


Q:

Suspense component gets called before the data actually loads

I'm trying to add react lazy in my application, and for some reason, it doesn't seem to work.
The component in which I want the lazy load to work on, fetches its data from a server, then it renders the data. The problem is, the component in which the data is getting fetched, which is in the suspense tag, gets loaded before the data actually loads. Here's my code:
AnotherTest.jsx
const AnotherTest = () => {
    const [toDoListData, setToDoListData] = useState([]);

    useEffect(() => {
        async function fetchData() {
            setTimeout(async () => {
                const result = await axios.get(`/api/ToDos/filter/completed`);
                setToDoListData(result.data);
            }, 5000);
        }

        fetchData();
    }, []);

    if (!toDoListData.length) return null;

    return (

            {toDoListData.map(item => {
                return
{item.name}
;
            })}

    );
};

Test.jsx
import React, { lazy, Suspense } from 'react';
const AnotherTest = React.lazy(() => import('./AnotherTest'));

const Testing = () => {
    return (

            <Suspense fallback={
Loading...
}>
                <AnotherTest />
            </Suspense>

    );
};

A:

The only way I know of that's currently possible is by using fetch-suspense.
Read this for a complete article on how he did it.
This would turn your component into
const AnotherTest = () => {
    const toDoListData = useFetch('/api/ToDos/filter/completed', { method: 'GET' });
    return (

            {toDoListData.map(item => {
                return
{item.name}
;
            })}

    );
};

If for some reason the fetch-suspense package does not suit your needs the only way is to show a loader in the AnotherTest component itself while fetching the data.
Note that the lazy function is meant for code-splitting and thus lazy loading the JS file, not waiting for anything async in the component itself.
(There is also react-cache but they advice not to use it in real world applications.)


Q:

PHP code for inserting non-duplicate values into MySQL

I have basic PHP/MySQL experience, having taken an introductory class.  My knowledge is literally limited to the following PHP codes:
if(!($stmt = $mysqli->prepare...)
if(!($stmt->bind_param...)
if(!$stmt->execute...)

I'm currently trying to write a program that allows a user to enter a new password, and checks the password against existing passwords in the database.
Here is what I have:
<?php
foreach($Password){
    $dupesql = "SELECT PasswordID Passwords WHERE (Password = '$Password')";
    $duperaw = mysql_query($dupesql);
    if(mysql_num_rows($duperaw){
        echo nl2br("$Password has already been used \n");
    }
    else{
        echo "Password added \n";
    }
}
?>

I got the code from this post: Check for duplicates before inserting
I'm not sure if the code itself has problems or if I need to add anything else to my PHP code to get this working, as it's currently producing an "Error 500".

A:

I decided to go an entirely different route, which is to set the Password column as unique.
Then I did a simple INSERT that would prompt an error if the user attempts to add a duplicate:
<?php
        if(!($stmt = $mysqli->prepare("INSERT INTO Heroes(HeroName, FirstName, LastName, Age, HomeCountry, RoleID) VALUES (?,?,?,?,?,?)"))){
            echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
        }
        if(!($stmt->bind_param("sssisi",$_POST['HeroName'],$_POST['FirstName'],$_POST['LastName'],$_POST['Age'],$_POST['HomeCountry'],$_POST['RoleID']))){
            echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
        }
        if(!$stmt->execute()){
            echo "Execute failed: "  . $stmt->errno . " " . $stmt->error;
        } else {
            echo "Added " . $stmt->affected_rows . " row to Heroes.";
        }
?>


Q:

How to get all possible combinations of multiple sets where order matters recursively

Given multiple sets of values. I want to find every combination (sorry I am using this term loosely but am not sure what the correct word is) of those values while preserving the order.
ie for
var set1 = ["a","1"];
var set2 = ["b","2"];
var set3 = ["c","3"];

the output should be
[a][b][c]
[a][b][3]
[a][2][c]
[a][2][3]
[1][b][c]
[1][b][3]
[1][2][c]
[1][2][3]

This provides the correct results, but I don't think this is a very good solution but just can't wrap my head around doing this recursively. The example is in Javascript but any language or insight is fine.
var set1 = ["a","1"];
var set2 = ["b","2"];
var set3 = ["c","3"];

var input = [set1, set2, set3];
var result = [];

for(var a=0;a<input[0].length;a++){
    for(var i=0;i<input[1].length;i++){
        for(var j=0;j<input[2].length;j++){
            var output = [];
            output.push(input[0][a]);
            output.push(input[1][i]);
            output.push(input[2][j]);
            result.push(output);
            console.log("["+input[0][a]+"]["+input[1][i]+"]["+input[2][j]+"]");
        }
    }
}

A:

Sure, you can recursively explore the space like this:
function extend_set (base, sets) {
    if(sets.length === 0) {
        return console.log('found: '+base);
    }
    sets = sets.slice();

    var choices = sets.shift();
    for (var i = 0; i < choices.length; i += 1) {
        var b2 = base.slice();
        b2.push(choices[i]);
        extend_set(b2, sets);
    }
}

var set1 = ["a","1"];
var set2 = ["b","2"];
var set3 = ["c","3"];
var sets = [set1, set2, set3];
extend_set([], sets);


Q:

Pending developer release and availability date

I made the mistake of thinking that if I selected to manually release the app, that it would be released on the availability date I selected. My app is now in the 'Pending developer release' state and I was wondering if there was any way to still ensure that the app is released on the correct day without having to manually release it myself. If I click 'release this version', will the app be available immediately or will it be released on the availability date I selected?
Thanks

A:

It should be released on the availability date.  Though there is some confusion that seems to be the consensus.  Here are some other discussions on it:
Submitting third version of an iOS app via iTunesConnect before app goes live
http://iphonedevsdk.com/forum/business-legal-app-store/120651-my-app-is-pending-developer-release-now-if-i-press-release-this-version.html


Q:

create array by conditions

I want to insert numbers to an array by the next following:

the number should be between 1-5
the first number can't be 1, the second can't be 2, etc..
chosen number can't be inserted to another index

for example:
[1,2,3,4,5]
I randomize the first number: 1 [condition 2 doesn't exists: 1 can't be in the first index, so I randomize again and got 4).
so new array:
0 - 4
1 -
2 -
3 -
4 -

I randomize a number to the second cell and got 4, but 4 was inserted to the first element [condition 3], so I randomize again and got 2, but 2 can't be the second element [condition 2], so I randomize again and got 5.
0 - 4
1 - 5
2 -
3 -
4 -

etc
I tried to init a vec by the numbers (1-5):
var array = new Array();

array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;

var newarr = new Array();

function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

$(document).ready(function() {
    for (var i = 0; i < 5; i++) {
        var rand;
        // check condition 2
        while((rand = getRandomInt(1, 5)) == (i+1));
        newarr[i] = rand;
        //array.splice(i, 1);
    }

    // print the new array
    for (var i = 0; i < 5; i++) {
        alert((i+1) + '->' + newarr[i]);
    }
});

but I need to add condition 3 to my code,
any help appreciated!

A:

Try this:
$(document).ready(function() {
    for (var i = 0; i < 5; i++) {
        var rand;
        // check condition 2
        while((rand = getRandomInt(1, 5)) == (i+1) || $.inArray(rand, newarr)) // Also check, if generated number is already in the array
        newarr[i] = rand;
        //array.splice(i, 1);
    }

    // print the new array
    for (var i = 0; i < 5; i++) {
        alert((i+1) + '->' + newarr[i]);
    }
});

But beware. If you generate for example this array:
[2, 1, 4, 3]

You will end up having an endless while loop, since the only available number is 5, but it can't be inserted in that position.


Q:

How do I deploy app visibility settings from profiles in a sandbox to a production org?

I have changed the visibility of an app for user Profiles in my sandbox org and I'd like to deploy those changes to the production org. I can't find a way to do that but know that I must be missing something. Does anyone know how?

A:

You can use change sets for this.  For any component you deploy you can choose to also deploy the profile permissions for some or all profiles.  Note that only the permissions related to components in the change set are deployed.  Also note that you'll get errors if you include the profile settings for a profile that exists in your sandbox, but not in your production org.

setup->deploy->outbound change set
name the change set, click save
under change set components add the app to the change set
under profile settings add any profiles you'd like to have the permissions updated for

Currently change sets don't support standard applications. However, this can be done with the Metadata API, which added the ability to retrieve Standard applications with v29. You can use the list metadata api call to retrieve the names of Standard application which are generally in the form standard__<AppName>, e.g. standard__Sales. If you retrieve the app along with the profile you're changing the permissions on, you can then deploy those settings. Do note, that this would also deploy any changes to that app in the source org and any general profile permissions (i.e. loginIpRanges, API Enabled, etc).
Sample package.xml
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>standard__Sales</members>
        <name>CustomApplication</name>
    </types>
    <types>
        <members>MyProfile</members>
        <name>Profile</name>
    </types>
    <version>33.0</version>
</Package>

Sample retrieved profile xml
<?xml version="1.0" encoding="UTF-8"?>
<Profile xmlns="http://soap.sforce.com/2006/04/metadata">
    <applicationVisibilities>
        <application>standard__Sales</application>
        <default>false</default>
        <visible>false</visible>
    </applicationVisibilities>
    <custom>true</custom>
    <loginIpRanges>
        <endAddress>255.255.255.255</endAddress>
        <startAddress>0.0.0.0</startAddress>
    </loginIpRanges>
    <userLicense>Salesforce</userLicense>
    <userPermissions>
        <enabled>true</enabled>
        <name>ActivateContract</name>
    </userPermissions>
    <userPermissions>
        <enabled>true</enabled>
        <name>ApiEnabled</name>
    </userPermissions>
    <!-- truncated for brevity -->
</Profile>


Q:

Customize file extension colors for ls output in Cshell

I know that there is an option for ls:
ls --color

...that will display different colors for files, directories, links, etc. in c-shell, but i'm wondering if there's a way to customize the output of ls so that files that match *.foo come up as red, files that match *.bar come up as green, etc. I would expect there is some way to set this up in my startup file .cshrc. Any clean solutions?

A:

Yes its possible using LS_COLORS variable. You could define it as below:
setenv LS_COLORS "${LS_COLORS}:*.foo=00;31:*.bar=00;32:"

This variable is used to customize the way ls command shows color of the particular file. It has a pattern like:
*.foo=<Attribute>;<foreground text color>;<background color>

Attribute values:
00=none
01=bold
04=underscore
05=blink
07=reverse
08=concealed

Text color codes:

30=black
31=red
32=green
33=yellow
34=blue
35=magenta
36=cyan
37=white

Background color codes:

40=black
41=red
42=green
43=yellow
44=blue
45=magenta
46=cyan
47=white


Q:

Calculating the $n^\text{th}$ derivative

How do we calculate the $n^{\text{th}}$ derivative for
$$
\frac{x^3}{(x-a)(x-b)(x-c)}?
$$
How can I obtain the partial fraction for the given term?

A:

So since the coefficients of $x^3$ in the numerator and denominator are equal, there is a constant term of $1$, and the form you want is
$$\frac {x^3}{(x-a)(x-b)(x-c)}=1+\frac A{x-a}+\frac B{x-b}+\frac C{x-c}$$
If you clear fractions you obtain $$x^3=(x-a)(x-b)(x-c)+A(x-b)(x-c)+(x-a)B(x-c)+(x-a)(x-b)C$$
Now successively setting $x=a,b,c$ will give you the values for $A,B,C$
And then differentiating as many times as you like is easy.


Q:

c++ overloading function including bool and integer arguments

a simple and I guess easy to answer question (if I did not already got it myself). The following overloaded functions:
void BR(const bool set) { backwardReaction_[nReac_] = set; }
bool BR(const int reactionNumber) const { return backwardReaction_[reactionNumber]; }

The first function is a setter and the second a getter function. backwardReaction_ is of type  std::vector<bool>. The problem occurs whenever I want to call the second function. Here I get a compiler error overload function BR(xy) ambigious.
int main()
.
.
const int i = 3;
bool a = chem.BR(i);

The compiler error is equal to:
chemistryTestProg.cpp: In function ‘int main()’:
chemistryTestProg.cpp:74:34: error: call of overloaded ‘BR(const int&)’ is ambiguous
     const bool a = chem.BR(i);
                             ^
In file included from ../../src/gcc/lnInclude/chemistryCalc.hpp:38:0,
                 from ../../src/gcc/lnInclude/chemistry.hpp:38,
                 from chemistryTestProg.cpp:35:
../../src/gcc/lnInclude/chemistryData.hpp:266:18: note: candidate: void AFC::ChemistryData::BR(bool)
             void BR(const bool);
                  ^~
../../src/gcc/lnInclude/chemistryData.hpp:322:22: note: candidate: bool AFC::ChemistryData::BR(int) const
                 bool BR(const int) const;
                      ^~

I guess that I get the problem because of the types bool and int which are identically (true => int(1), false => int(0). As I am changing the getter name to, e.g., bool getBR(const int reactionNumber) {...} everything works fine. So I guess the problem is about the similarities of the bool and int treatment within c++. I also tried a variety of different calls such as:
const bool a = chem.BR(4)
const bool a = chem.BR(int(5))
const bool a = chem.BR(static_cast<const int>(2))
bool a = chem.BR(...)

Thus, I think it is really related to the bool andint overloading arguments. Nevertheless, I made a quick search and did not find too much about these two overload types and resulting problems. Tobi

A:

This is because you declared BR(int), but not BR(bool), to be const. Then when you call BR(int) on a non-const object, the compiler has two conflicting matching rules: parameter matching favours BR(int), but const-ness matching favours BR(bool).


Q:

Ignoring a client when broadcasting a message with SignalR

I want to ignore the client that made the request to broadcast the message my web app. The only way I can seem to do this is by caching the connectionId of the current user:
public class BroadcastHub : Hub
{

    public override Task OnConnected()
    {
        System.Runtime.Caching.MemoryCache.Default.Set(HttpContext.Current.User.Identity.Name + "-connectionId", Context.ConnectionId, new CacheItemPolicy() { Priority = CacheItemPriority.Default, SlidingExpiration = TimeSpan.FromHours(1), AbsoluteExpiration = MemoryCache.InfiniteAbsoluteExpiration });

        return base.OnConnected();
    }

    public override Task OnReconnected()
    {
        System.Runtime.Caching.MemoryCache.Default.Set(HttpContext.Current.User.Identity.Name + "-connectionId", Context.ConnectionId, new CacheItemPolicy() { Priority = CacheItemPriority.Default, SlidingExpiration = TimeSpan.FromHours(1), AbsoluteExpiration = MemoryCache.InfiniteAbsoluteExpiration });

        return base.OnReconnected();
    }

}

This allows me to do the following in the controller action method:
        IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<BroadcastHub>();
        hubContext.Clients.AllExcept((string)MemoryCache.Default.Get(HttpContext.Current.User.Identity.Name + "-connectionId")).sendAddedPasswordDetail(addedPassword);

This method seems to work... but I'm thinking it might be the wrong way of doing things. Is there a better way to ignore the requesting client?

A:

There is a specific property that allows this particular exception,
hubContext.Clients.Others.YourMethodHere

You can see it used here.
Edit:
As per the discussion in the comments, Others is not available when using GlobalHost.ConnectionManager.GetHubContext<T>
You will either need to continue using your current method or find a way to delegate this activity to the BroadcastHub to have access to Others.


Q:

Datepart logic for custom sql agent job schedule

Wanted help in code for below logic.

Job A needs to be run on 8th of month.
Job B needs to be run on Tuesday only.
Job c needs to be run on Daily(Minus Tuesday & Sunday).
And If Its Tuesday and 8Th Job A takes the precedence of Job.

i have coded logic for half of it.
Else If Begin logic,
--Tuesday Logic(0=Monday,1=Tuesday,2=Wed,3=Thu,4=Friday,5=Saturday,6=Sunday)
IF (SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE())/7*7,0) + 1)=1 -- If it is tuesday execute the Weekly+Daily Job
       Print 'executing weekly and daily tables'

ELSE
BEGIN
       Print 'executing daily job'
END
END

A:

Here is my logic:
BEGIN
--FULL REFRESH Cycle
declare @EightDayofMonth datetime =(DATEADD(DAY, 8-DAY(GETDATE()), CONVERT(date, GETDATE())));
declare @actuladayofmonth datetime = CONVERT(date, getdate());

----checking for 8th day --condition 1 ( 8th of month and NOT Tuesday and not sunday) if any other day job executes
IF (@actuladayofmonth=@EightDayofMonth) AND (DATEPART(WEEKDAY,GETDATE())<>3 OR DATEPART(WEEKDAY,GETDATE())<>1)

BEGIN
Print 'disabe daily job'
print 'executing full job'
    END

--checking for monthly 8th is tuesday logic
ELSE IF (@actuladayofmonth=@EightDayofMonth) AND DATEPART(WEEKDAY,GETDATE())=3
BEGIN

Print 'Disable Tuesday Weekly'
print 'Disable Daily on tuesday'
Print 'Executing full job'
    END

ELSE IF (@actuladayofmonth=@EightDayofMonth) AND DATEPART(WEEKDAY,GETDATE())=1
BEGIN
Print 'Execute disable sunday'
 END
  END


Q:

How to add array to JSON object in javascript?

I am trying to create a json string that has an array element:

var arrays = [0,1,2];
var obj = new Object();
obj.data = arrays;
console.log(JSON.stringify(obj));

I get this result:
{"data":{"0":0,"1":1,"2":2}}

I want this JSON string:
{"data": [0,1,2,3,4,5,6,7], "name":"number"}

How can I add an array element to a JSON Object?

A:

You can just use JSON.stringify like so:

var myObj = {"data": [0,1,2,3,4,5,6,7], "name":"number"};
var myJSON = JSON.stringify(myObj);

console.log(myJSON);

And you can convert it back using JSON.parse:

var myObj = {"data": [0,1,2,3,4,5,6,7], "name":"number"};
var myJSON = JSON.stringify(myObj);

console.log(JSON.parse(myJSON));


Q:

Adding duplicate values to ArrayList

Stackoverflow.
I'm trying to add 4 of each words in my ArrayList into the ArrayList itself. I have in my ArrayList two Strings. One is "java" and the other one is "Program". I'm trying to write a program that adds a total of 4 words of each word. Ex: I'm trying to add 4 x java and 4 x program.
Here's what I've got so far. I have no idea, what I'm doing wrong.
Any help or hints would be much appreciated.
 /*
  * Write a method called quadList that takes an ArrayList of strings as a parameter
   *  and replaces every string with four of that same string.
   *  For example, if the list stores the values ["java", "program"]
   *  before the method is called,it should store the values
   *  ["java ", " java ", " java ", " java ", "program", "program", "program", "program"]
   *   after the method finishes executing.
   */
  import java.util.ArrayList;

  public class Ex10_4_quadList {

public static void main(String[] args) {

    ArrayList<String> arrList = new ArrayList<String>();

    arrList.add("Java");
    arrList.add("Program");

    System.out.println("Before: " + arrList);
    quadList(arrList);
    System.out.println("after " + arrList);

}

private static void quadList(ArrayList<String> list) {

    for (int i = 0; i < list.size(); i++) {

        for (int j = 0; j < 4; j++) {
            String temp = list.get(i);
            list.add(temp);

        }

    }

}

  }

Here's the fixed code:
 public class Ex10_4_quadList {

public static void main(String[] args) {

    ArrayList<String> arrList = new ArrayList<String>();

    arrList.add("Java");
    arrList.add("Program");

    System.out.println("Before: " + arrList);
    quadList(arrList);
    Collections.sort(arrList);
    System.out.println("after " + arrList);

}

private static void quadList(ArrayList<String> list) {

    int initial = list.size();

    for (int i = 0; i < initial; i++) {

        for (int j = 0; j < 3; j++) {
            String temp = list.get(i);
            list.add(temp);

        }

    }

}

 }

A:

Try:
private static void quadList(ArrayList<String> list) {

    int listSize = list.size();

    for (int i = 0; i < listSize; i++) {

        for (int j = 0; j < 4; j++) {
            String temp = list.get(i);
            list.add(temp);

        }

    }

}
The problem with the code is that the list.size() is evaluated on every iteration. Since the inner loop is increasing the list size faster than the outer loop can iterate over it, the code effectively loops infinitely until JVM runs out of memory.


Q:

Why are suggested edit votes limited?

Is there a reason why I can only vote on 30 suggested edits per day? I don't think there is a real problem that more votes are abused or something like that. But every time, I reach this limit and then I stop voting, although it would be good for the community if suggested edits were accepted or rejected as fast as possible.

A:

OK, for now I increased it to 40 -- on Stack Overflow specifically, since there are more edits on the largest site.
We really want vote diversity here, so that's the point of the limits -- if the same 2 folks are vetting all the edits, that's not a sufficient set of eyeballs on those edits.

A:

Suggested edit votes are limited to spread the load. That's good for the site, because it allows more people to influence the vetting and spot good or bad trends. It's also good for you: after 30 edits, go and do something else, like check on the flags, or go pile on the close/reopen votes, or look for unanswered questions, or ponder a programming puzzle, or think about science… or get a life¹!
I have to say that if you are going through 30 votes in 10 minutes, you're not doing this seriously. If you mean this literally, that's 20 seconds on average. A lot of edits can be decided in less than that, but there are quite a few that require more (that hyperlink fix: is it truly a fix and not a spam injection? That typo in example code: does the fixed code actually work? That reformatting job: did it do nothing more than reformatting? That retagging: is the new tag really appropriate?). A lot of suggested edits don't go all the way. Take time to improve them! Did the editor remember to improve the title as well as the body? Now that the code has been reformatted, can the English be improved? Are these really the right tags for this question? And sometimes there are other things you might do, especially for question edits: is it worth polishing this turd, or should you vote to close? Or leave a comment telling the asker to post more information? And, maybe, answer a question now and then.
[This paragraph was written back when it took 10k rep to browse the queue and the approve/reject quota was 30/day.]

I do often burn through 30 edits in a day, but I see the limit as telling me to move on to other things. Especially since 30 recorded approvals/rejections means a lot more than 30 evaluated suggestions, if you take the time to improve a lot of them. I'd rather have more eyeballs. There are are currently about 1500 users with 10k rep, but of course many don't do any reviewing. I would prefer to lower the reputation threshold: open the queue to all ~2000 users with 8k rep, or maybe all ~2800 users with 6k rep. With the double vetting on SO, I don't think there would be any problem. (I'd be fine with lowering the threshold on other sites, but the volume doesn't require it — even SU's average is well below 30/day.)

Now that the review quota has been raised to 50/day (not counting Improve), I find that it's a lot to fit in a day. After that many, it's hard to still do the job seriously. I really don't want the quota to be raised again, I would prefer it brought back to 30/day, and instead to see more incentive for 5kers to review suggested edits. We need more eyes! There are about 5000 users with 5k rep, who can browse the queue. There are about 1000 suggestions on a weekday, i.e. we need 2000 reviews. If 1 in 5 eligible user reviews TWO (2) suggestions per day on average, we'll stay on top of the queue.
¹ Do what I say, not what I do.


Q:

My Macbook's headphone jack stopped working, how do I fix it?

my headphone jack output stopped working a couple days ago. As in - when I jack a cable (or headphones) the sound comes via the built-in speakers.
On the installed Windows (Bootcamp) it works OK (sound coming out via headphones when jacked in).
Any ideas how I can troubleshoot this?
The OS is Lion, freshly updated (update after the problem first appeared).

A:

(posted as an answer so you can accept it and mark this issue resolved)
Have you checked the Sound pref pane in System Preferences? There's a tab labeled "Output" where (I'd expect, as I don't have a portable in front of me just now) you can switch output between built-in speakers and the headphone jack. If the first toggle doesn't work, toggle it again.


Q:

where is X-axis mirror in 2.8 blender

i found amature-global x mirror in edit-mode. but it is not X-axis mirror.
where is it?

A:

Now you've got all sorts of mirrors in the top panel
upd: I was a little bit too hurry and didn't check if mirror options for mesh edit mode are the same for armature edit mode, but x-axis mirror is still there for armature. And it works as a mirror i.e. I move left wrist and right wrist is moved symmetrically. I've added another pic. You should have the same panel in armature edit mode unless you have manually edited your default UI.


Q:

Candidate definitions for "1-braided 2-category"?

Recall that a braided monoidal category is a category $\mathcal C$, a functor $\otimes: \mathcal C \times \mathcal C \to \mathcal C$ satisfying some properties, and a natural isomorphism $b_{V,W}: V\otimes W \to W\otimes V$ satisfying some properties.  Recall also that a monoidal category (just $\mathcal C,\otimes$ and their properties) is the same as a one-element 2-category: the objects of $\mathcal C$ become the morphisms, and the monoidal structure becomes composition.
Thus, is there a natural definition of "1-braided 2-category"?  I'm calling it "1-braided" because the braiding acts on 1-morphisms (as opposed to "braided monoidal 2-category", where the braiding acts on the 0-morphisms).
I realize, of course, that if $V,W$ are morphisms of a 2-category so that $V\circ W$ is defined, then generally $W\circ V$ is not defined, so a priori asking for any relationship $V\circ W \cong W\circ V$ doesn't make sense.  On the other hand, consider Aaron Lauda's categorification of $U\_q(\mathfrak{sl}\_2)$.  It is a 2-category, but different hom-sets can be more-or-less identified.

A:

In the Baez-Dolan periodic table a braided monoidal category is just a 2-monoidal category (that is a 3-category with one object and one 1-morphism).  If you just think that a braiding means that the structure is inherently 3-dimensional, then you might just want to think about a 1-monoidal 2-category (that is a 3-category with one object).


Q:

How to make return char function in c programming?

I'm Trying to do some simple c programming that will return the char value. The program is running with no error but, the output of the expected string does not appear. What I expected it will return the Halloworld when i run it.
#include <stdio.h>
#include <string.h>

char screen(char c[]);

int main(){

    char b[] = "Hallo";
    //screen(b);
    printf("%s",screen(b));
}

char screen(char c[]){

    strcat(c, "world");
    return c;
}

A:

The declaration of strcat() returns a pointer to char (char *).  So your function screen() must also.
Another thing is, you can't do this char b[] = "Hallo";, because then the character array b is only large enough to handle Hallo.  You'll need it larger than Hallo, and the rest will be filled with 0x00, or NUL.  Like so:
48 61 6C 6C 6F 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00
And then after you strcat() the characters world onto the end:
48 61 6C 6C 6F 20 77 6F 72 6C 64 00 00 00 00 00 00 00 00 00
The first left over 0x00 will act as a null terminator when passed to printf().
#include <stdio.h>
#include <string.h>

char* screen(char c[])
{
    strcat(c, "world");
    return c;
}

int main()
{
    char b[20] = "Hallo ";
    screen(b);
    printf("%s",b);

    return 0;
}


Q:

Where is the svnbook for latest Subversion (1.9.4)?

The official svnbook site contains online versions of the book for 1.7 and for the "nightly build" 1.8. Not sure how 1.8 counts as nightly when 1.9.4 exists, but whatever :)
Where can I find an online version of the svnbook for the latest Subversion (1.9.4)?

A:

Use SVNBook 1.8 for now, it's mostly ready. SVNBook 1.9 hasn't been started yet and there are not so much differences between 1.8 and 1.9.


Q:

WPF Toolkit Color Picker edit template now no available colors

I have looked for a solution to my problem on Google for hours, but there isnt much information to find.
I am using WPF Toolkit v2.2.1.
I have a Color Picker control in my WPF application, which needs to be custom styled. I am editing the control template of the Color Picker in App.xaml to apply to all color pickers.
As soon as I choose to use the template all available colors dissapear from the Color Picker. I have tried to assign new available colors from code with no success.
The Collection of colors are there, they are just not displayed it seems.
This is how the CP is defines in my mainwindow.xaml
<xctk:ColorPicker x:Name="cpRing" SelectedColorChanged="cpRing_Changed" HorizontalAlignment="Left" Margin="238,5,0,0" VerticalAlignment="Top" Height="20" Width="39" Foreground="Black"/>

The control template is too large to paste here unfortunately. But this should be easily reproduceable by adding a CP to a wpf window and rightclick it in designview and choose Edit Template. As soon as it is applied the colors will dissapear, without changing anything.
Does anybody know what to do to get the avaiable colors to display when editing the control template?
Best regards

A:

yep, it has something wrong with it's style. But if you observe it's style carefully you will find out the problem:
search key word StandardColors or AvailableColors in xaml, here is StandardColors's template:
<ListBox x:Name="PART_StandardColors"  Grid.Row="1">
        <ListBox.Style>
            <Style TargetType="{x:Type ListBox}">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="ItemsPanel">
            ....
        </ListBox.Style>
</ListBox>

you can see the listbox has not set itemsource, so you can add it by yourself:
<ListBox x:Name="PART_StandardColors" ItemsSource="{TemplateBinding StandardColors}"  Grid.Row="1">

edit listbox of AvailableColors :
 <ListBox x:Name="PART_AvailableColors" ItemsSource="{TemplateBinding AvailableColors}" Grid.Row="1">

now it works.


Q:

CSS word wrapping causes huge spaces between words

Hi! When the window is resized, the text automatically wraps to fit its container nicely. For this, I'm using this CSS code:
article {
    overflow: auto;
    word-wrap: break-word;
}

Though it seems, that this has no effect at all. When I remove this piece of code, the behavior doesn't change: the text is still wrapped near the end of the line.
I'm complaining about the huge gaps between words. I've observed a few webpages where no extra code is used for this and it still works nicely. Can you please help me get rid of the space? Thank you!

A:

I agree that the text-align: justify has been inherited from the parent html tags.
You could also try modifying the CSS as follows:
article {
    overflow: auto;
    word-wrap: break-word;
    text-align: start;
}


Q:

Let two different item use same adapter and each data of item will not to be replaced by other item in RecyclerView

I want to make my app with two item(Post and Ad) in the same RecyclerView.
But my item will be replaced by another item, not insert it.
How can I fix it!
I want the right side, but now my code is the left side and will be crashed!

Here is my Adapter:
public class PostCardImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static final int Post_Layout = 0;
    public static final int AD_Layout = 1;

    private Context mContext;
    private ArrayList<PostCard> mData;

    private int mAdCount;
    public static NativeAd nativeAd = HomePageActivity.nativeAd;

    public PostCardImageAdapter(Context context, ArrayList<PostCard> data) {
        this.mContext = context;
        this.mData = data;
    }

    public int getmAdCount(){
        mAdCount = mData.size() / 2;
        return mAdCount;
    }

    @Override
    public int getItemViewType(int position) {

        /*if(mAdCount != 0 && position >= dataItemCount){
            return AD_Layout;
        }

        else{
            return Post_Layout;
        }*/

        if(position!=0 && (position % 2 == 0)){
            return AD_Layout;
        }

        else{
            return Post_Layout;
        }
    }

    public static class PostViewHolder extends RecyclerView.ViewHolder {
        private ImageView postcard_userIcon;
        private TextView postcard_name;
        private TextView postcard_time;
        private TextView postcard_postText;
        private ImageView postcard_postPic;
        private TextView postcard_likes;
        private TextView postcard_comments;

        public PostViewHolder(View postView) {
            super(postView);
            postcard_userIcon = (ImageView) postView.findViewById(R.id.postcard_userIcon);
            postcard_name = (TextView) postView.findViewById(R.id.postcard_name);
            postcard_time = (TextView) postView.findViewById(R.id.postcard_time);
            postcard_postText = (TextView) postView.findViewById(R.id.postcard_postText);
            postcard_postPic = (ImageView) postView.findViewById(R.id.postcard_postPic);
            postcard_likes = (TextView) postView.findViewById(R.id.postcard_likes);
            postcard_comments = (TextView) postView.findViewById(R.id.postcard_comments);
        }
    }

    public static class AdViewHolder extends RecyclerView.ViewHolder {

        NativeAdLayout nativeAdContainer;
        TextView nativeAdTitle;
        TextView sponsoredLabel;
        TextView nativeAdBody;
        TextView nativeAdSocialContext;

        AdIconView nativeAdIcon;
        MediaView nativeAdMedia;

        Button nativeAdCallToAction;

        //LinearLayout adChoicesContainer;

        public AdViewHolder(View adView) {
            super(adView);
            nativeAdContainer = adView.findViewById(R.id.native_ad_container);
            nativeAdTitle = adView.findViewById(R.id.native_ad_title);
            sponsoredLabel = adView.findViewById(R.id.native_ad_sponsored_label);
            nativeAdBody = adView.findViewById(R.id.native_ad_body);
            nativeAdSocialContext = adView.findViewById(R.id.native_ad_social_context);

            nativeAdIcon = adView.findViewById(R.id.native_ad_icon);
            nativeAdMedia = adView.findViewById(R.id.native_ad_media);

            nativeAdCallToAction = adView.findViewById(R.id.native_ad_call_to_action);

            /*adChoicesContainer = adView.findViewById(R.id.ad_choices_container);
            AdOptionsView adOptionsView = new AdOptionsView(mLayoutInflater.this, nativeAd, nativeAdContainer);
            adChoicesContainer.removeAllViews();
            adChoicesContainer.addView(adOptionsView, 0);*/
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if(viewType == Post_Layout){
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.postcard_layout, parent, false);
            return new PostViewHolder(v);
        }

        else {
          View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.native_ad_layout, parent, false);
          return new AdViewHolder(v);
      }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

        if(holder instanceof PostViewHolder){
            PostCard post = mData.get(position);

            ((PostViewHolder) holder).postcard_name.setText(post.name);
            ((PostViewHolder) holder).postcard_time.setText(post.time);
            ((PostViewHolder) holder).postcard_postText.setText(post.postText);
            ((PostViewHolder) holder).postcard_likes.setText(post.likes);
            ((PostViewHolder) holder).postcard_comments.setText(post.comments);
            Glide.with(mContext)
                    .load(post.userIconUrl)
                    .into(((PostViewHolder) holder).postcard_userIcon);
            Glide.with(mContext)
                    .load(post.postPicUrl)
                    .into(((PostViewHolder) holder).postcard_postPic);
        }

        else if(holder instanceof AdViewHolder){

            AdViewHolder adViewHolder = (AdViewHolder) holder;

            View adView = NativeAdView.render(mContext, nativeAd);
            adViewHolder.nativeAdTitle.setText(nativeAd.getAdvertiserName());
            adViewHolder.sponsoredLabel.setText(nativeAd.getSponsoredTranslation());
            adViewHolder.nativeAdBody.setText(nativeAd.getAdBodyText());
            adViewHolder.nativeAdSocialContext.setText(nativeAd.getAdSocialContext());

            adViewHolder.nativeAdCallToAction.setVisibility(nativeAd.hasCallToAction() ? View.VISIBLE : View.INVISIBLE);
            adViewHolder.nativeAdCallToAction.setText(nativeAd.getAdCallToAction());

            List<View> clickableViews = new ArrayList<>();
            clickableViews.add(adViewHolder.nativeAdTitle);
            clickableViews.add(adViewHolder.nativeAdCallToAction);

            nativeAd.registerViewForInteraction(
                    adView,
                    adViewHolder.nativeAdMedia,
                    adViewHolder.nativeAdIcon,
                    clickableViews);
        }
    }

    @Override
    public int getItemCount() {
        return mData.size() + getmAdCount();
    }
}

Here is the Log:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: playground.com.pgapp, PID: 29719
    java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
        at java.util.ArrayList.get(ArrayList.java:411)
        at playground.com.pgapp.PostCardImageAdapter.onBindViewHolder(PostCardImageAdapter.java:156)
        at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
        at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
        at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:286)
        at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:343)
        at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:359)
        at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:366)
        at android.support.v7.widget.GapWorker.run(GapWorker.java:397)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:241)
        at android.app.ActivityThread.main(ActivityThread.java:6274)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

A:

    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

            if(holder instanceof PostViewHolder){
                int index = position - position / 2;
                PostCard post = mData.get(index);

                ((PostViewHolder) holder).postcard_name.setText(post.name);
                ((PostViewHolder) holder).postcard_time.setText(post.time);
                ((PostViewHolder) holder).postcard_postText.setText(post.postText);
                ((PostViewHolder) holder).postcard_likes.setText(post.likes);
                ((PostViewHolder) holder).postcard_comments.setText(post.comments);
                Glide.with(mContext)
                        .load(post.userIconUrl)
                        .into(((PostViewHolder) holder).postcard_userIcon);
                Glide.with(mContext)
                        .load(post.postPicUrl)
                        .into(((PostViewHolder) holder).postcard_postPic);
            }

            ...
}


Q:

cvs2git blob and dump file

I am trying to import a cvs project in git using cvs2git.
I am using following command
cvs2git --username=reza -v --blobfile=./blob.txt  --dumpfile=./dump.txt ./localCVSTree/repo

I see the blob file getting created and I do not see the dump file getting created.
Why does that happen? Is that an error?
Any experience with this issue?

A:

For some reason cvs2git must not have run to completion.  It is impossible to tell why without more information.


Q:

What is the passcode?

Another unsolved case for you to investigate.  This one concerns a robbery of very sensitive government information, along with the murder of several former government secret agents.  The CIA has captured the culprit, but they have not found any affiliations with other suspects, but you know this was not a lone wolf attack.  The only thing you have is the suspect's phone, but it is locked by a four character passcode, which is a combination of letters and numbers (not case sensitive).  Once you have found the passcode, you will be closer to finding out who else is responsible for this crime and bring them to justice.  Good luck.
What is (*)?

Order of sequence...

Character #1: About me will tell you what you need.  It has sown the seed to what great thing? (7)
Character #2: Hiroshima and Nagasaki, for what when? (3)
Character #3: For the readers and gamers, this one's a number.  Clancy's Roy G. Biv
Character #4: Note 5 in the key of C.

A:

The passcode is

   A46G

Character 1

    In the 'About Me' section of your profile, you have the name, "General Sherman". There is a tree called the General Sherman Tree. It is a sequoia tree. The 7th letter in 'sequoia' is 'a'. 'A' is the first character of the passcode.

Character 2

Hiroshima and Nagasaki were both bombed because of the attack on Pearl Harbor. The bombing of Pearl Harbor happened in the year 1941, and the order of sequence is 3. So Character two must be the third digit in 1941, which is 4. Character 2 is 4.

Character 3

  The clue said that this one was a number. Roy G. Biv refers to the rainbow, and the game that is implied by this clue is Tom Clancy's Rainbow Six Siege. The third character of the passcode is 6.

Character 4

  The fifth note in the key of C is G. G is the fourth character of the passcode.


Q:

Sending form data to 2 places

I have inherited a system running on PHP4.4.9, however I'm needing to do something that requires 5.0 or higher, at current we cannot upgrade as it's part of a "package" (Hornbill Supportworks) that will break various feature and functionality.
What I have done is added the php 5+ stuff to my personal webspace for now.
An example of the form I have is:
<form action="./ChangeStatusSubmit.php" method="post" name="main">
<input type="text" size="15" maxlength="43" name="GappsMailTextS">
<button type="submit">
Submit status changes
</button>
</form>

In the form action I'm also wanting it to post to http://www.externalurl/test.php, can anyone help with this? I've not found anything that works online as it requires "curl" or ajax (I've never used/seen ajax so I would have no idea how to put that in to the file! any help appreciated.

A:

You need to use AJAX for this. There isn't way to add two actions to the form. You can ajax your first action and then submit the declared form action in .done handler. Hopefully you have jquery, it's lot more difficult to use plain js for ajax.
Some links:
http://api.jquery.com/jquery.ajax/#example-0
How to make an AJAX call without jQuery?
So based on above examples the jquery solution could be this:
$('form[name=main]').submit(function() {
  return false;
  $.ajax({
    type: "POST",
    url: "http://www.externalurl/test.php",
    data: { GappsMailTextS: $('input[name=GappsMailTextS]').value() }
  })
  .done(function( msg ) {
    $('form[name=main]').submit();
  });
)};