text:
Q: Reading zipped ESRI BIL files with Python I have precipitation data from the PRISM Climate Group which are now offered in .bil format (ESRI BIL, I think)  and I'd like to be able to read these datasets with Python.
I've installed the spectral package, but the open_image() method returns an error:
def ReadBilFile(bil):
    import spectral as sp
    b = sp.open_image(bil)
ReadBilFile(r'G:\truncated\ppt\1950\PRISM_ppt_stable_4kmM2_1950_bil.bil')

IOError: Unable to determine file type or type not supported.
The documentation for spectral clearly says that it supports BIL files, can anyone shed any light on what's happening here? I am also open to using GDAL, which supposedly supports the similar/equivalent ESRI EHdr format, but I can't find any good code snipets to get started.

A: Ok, I'm sorry to post a question and then answer it myself so quickly, but I found a nice set of course slides from Utah State University that has a lecture on opening raster image data with GDAL. For the record, here is the code I used to open the PRISM Climate Group datasets (which are in the EHdr format).
import gdal

def ReadBilFile(bil):

    gdal.GetDriverByName('EHdr').Register()
    img = gdal.Open(bil)
    band = img.GetRasterBand(1)
    data = band.ReadAsArray()
    return data

if __name__ == '__main__':
    a = ReadBilFile(r'G:\truncated\ppt\1950\PRISM_ppt_stable_4kmM2_1950_bil.bil')
    print a[44, 565]

EDIT 5/27/2014
I've built upon my answer above and wanted to share it here since the documentation seems to be lacking. I now have a class with one main method that reads the BIL file as an array and returns some key attributes.
import gdal
import gdalconst

class BilFile(object):

    def __init__(self, bil_file):
        self.bil_file = bil_file
        self.hdr_file = bil_file.split('.')[0]+'.hdr'

    def get_array(self, mask=None):
        self.nodatavalue, self.data = None, None
        gdal.GetDriverByName('EHdr').Register()
        img = gdal.Open(self.bil_file, gdalconst.GA_ReadOnly)
        band = img.GetRasterBand(1)
        self.nodatavalue = band.GetNoDataValue()
        self.ncol = img.RasterXSize
        self.nrow = img.RasterYSize
        geotransform = img.GetGeoTransform()
        self.originX = geotransform[0]
        self.originY = geotransform[3]
        self.pixelWidth = geotransform[1]
        self.pixelHeight = geotransform[5]
        self.data = band.ReadAsArray()
        self.data = np.ma.masked_where(self.data==self.nodatavalue, self.data)
        if mask is not None:
            self.data = np.ma.masked_where(mask==True, self.data)
        return self.nodatavalue, self.data

I call this class using the following function where I use GDAL's vsizip function to read the BIL file directly from a zip file.
import prism
def getPrecipData(years=None):
    grid_pnts = prism.getGridPointsFromTxt()
    flrd_pnts = np.array(pd.read_csv(r'D:\truncated\PrismGridPointsFlrd.csv').grid_code)
    mask = prism.makeGridMask(grid_pnts, grid_codes=flrd_pnts)
    for year in years:
        bil = r'/vsizip/G:\truncated\PRISM_ppt_stable_4kmM2_{0}_all_bil.zip\PRISM_ppt_stable_4kmM2_{0}_bil.bil'.format(year)
        b = prism.BilFile(bil)
        nodatavalue, data = b.get_array(mask=mask)
        data *= mm_to_in
        b.write_to_csv(data, 'PrismPrecip_{}.txt'.format(year))
    return

# Get datasets
years = range(1950, 2011, 5)
getPrecipData(years=years)

A: You've already figured out a good solution to reading the file so this answer is just in regard to shedding light on the error you encountered.
The problem is that the spectral package does not support the Esri multiband raster format. BIL (Band Interleaved by Line) is not a specific file format; rather, it is a data interleave scheme (like BIP and BSQ), which can be used in many file formats. The spectral package does support BIL for the file formats that it recognizes (e.g., ENVI, Erdas LAN) but the Esri raster header is not one of those.

A: It's now 2017 and there is a slightly better option. The package rasterio supports bil files.
>>>import rasterio
>>>tmean = rasterio.open('PRISM_tmean_stable_4kmD1_20060101_bil.bil')
>>>tmean.affine
Affine(0.041666666667, 0.0, -125.0208333333335,
       0.0, -0.041666666667, 49.9375000000025)
>>> tmean.crs
CRS({'init': 'epsg:4269'})
>>> tmean.width
1405
>>> tmean.height
621
>>> tmean.read().shape
(1, 621, 1405)


text:
Q: Call php artisan migrate using Artisan Is it possible to create an Artisan call or command for
php artisan migrate

like Artisan::call('migrate);
So i can migrate missing tables to my database when connection is changed dynamically.
  Config::set('database.connections.dynamicdb', array(
        'driver'    => 'mysql',
         'host'      => '127.0.0.1',
         'database'  =>  $database_name,
         'username'  =>  'test_user',
         'password'  =>  '123456',
         'charset'   => 'utf8mb4',
         'collation' => 'utf8mb4_unicode_ci',
         'strict'    => false,
         'options'   => [
               \PDO::ATTR_EMULATE_PREPARES => true
            ]
       ));

  Artisan::call('migrate');

Or is there a way to create a command for it? Please suggest some solution.

A: Try this code:
\Artisan::call('migrate',
 array(
   '--path' => 'database/migrations',
   '--database' => 'dynamicdb',
   '--force' => true));

Because my default it takes /app as path and the migrations are placed in database/migrations. So this will work as it worked for me when creating new project.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ignore file with similar name using regex I have a problem using regex
I have a folder that contains 3 files
 Test.log
 Test.log.1
 Test.log.2

I want to catch only the test.log file
I tried a lot of combinations like:
Test.log
^Test.log
Test.log[^0-3]

Etc...
What can I do?

A: Test.log$

$ means end of string.
Your three matches didn't suffice because

*

*Test.log = anything that contains Test.log

*^Test.log = anything that starts with Test.log

*Test.log[^0-3] = anything that contains Test.log, followed by something that isn't 0, 1, 2, or 3. However, in this case the next character that you didn't want was the literal dot.

Another alternative if you want to expand on your last solution is to use negative lookahead:
Test.log(?!\.[0-3])


text:
Q: Installing BioConductor in Linux I know this has been asked a number of times but I cant figure out the answer from the answers here on StackOverflow or on the BioConductor install page here. I have installed and updated R to the latest 3.1.3 version which is explicitly stated to work with BioConductor 3.0 on the install page.
I then installed BioConductor and made sure everything was up to date using the following commands:
source("http://bioconductor.org/biocLite.R")
biocLite(ask=FALSE)
biocLite("BiocUpgrade")

Everything up to this point works just fine, but then when I go to install any of the BioConductor packages using, for example:
biocLite(c("flowCore"))

I will get a handful of errors like the following:
1: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
installation of package 'robustbase' had non-zero exit status

My understanding is that this error is indicative of a version mismatch between R and the package and yet it sounds like everything from BioConductor should work with the R version 3.1.3.
When I try to install the the packages listed in the errors manually using, for example:
install.packages("robustbase", dependencies=TRUE)

And I will get the same type of error as above with the non-zero exit status.
Does anybody know the best way of getting around this? I assume I don't need to downgrade to a previous version of R or anything but I'm really not sure what to do at this point. Thanks.
As requested in the comments below, the full output of the install of a package flowCore using the following code is below:
biocLite(c("flowCore"))

Output:
    BioC_mirror: http://bioconductor.org
Using Bioconductor version 3.0 (BiocInstaller 1.16.2), R version 3.1.3.
Installing package(s) 'flowCore'
also installing the dependencies 'robustbase', 'mvtnorm', 'cluster', 'pcaPP', 'rrcov'

trying URL 'http://cran.rstudio.com/src/contrib/robustbase_0.92-3.tar.gz'
Content type 'application/x-gzip' length 3144393 bytes (3.0 MB)
opened URL
==================================================
downloaded 3.0 MB

trying URL 'http://cran.rstudio.com/src/contrib/mvtnorm_1.0-2.tar.gz'
Content type 'application/x-gzip' length 155092 bytes (151 KB)
opened URL
==================================================
downloaded 151 KB

trying URL 'http://cran.rstudio.com/src/contrib/cluster_2.0.1.tar.gz'
Content type 'application/x-gzip' length 280102 bytes (273 KB)
opened URL
==================================================
downloaded 273 KB

trying URL 'http://cran.rstudio.com/src/contrib/pcaPP_1.9-60.tar.gz'
Content type 'application/x-gzip' length 191565 bytes (187 KB)
opened URL
==================================================
downloaded 187 KB

trying URL 'http://cran.rstudio.com/src/contrib/rrcov_1.3-8.tar.gz'
Content type 'application/x-gzip' length 992215 bytes (968 KB)
opened URL
==================================================
downloaded 968 KB

trying URL 'http://bioconductor.org/packages/3.0/bioc/src/contrib/flowCore_1.32.2.tar.gz'
Content type 'application/x-gzip' length 8962871 bytes (8.5 MB)
opened URL
==================================================
downloaded 8.5 MB

* installing *source* package 'robustbase' ...
** package 'robustbase' successfully unpacked and MD5 sums checked
** libs
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c R-rng4ftn.c -o R-rng4ftn.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c eigen.f -o eigen.o
/bin/bash: gfortran: command not found
make: *** [eigen.o] Error 127
ERROR: compilation failed for package 'robustbase'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/robustbase'
* installing *source* package 'mvtnorm' ...
** package 'mvtnorm' successfully unpacked and MD5 sums checked
** libs
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c C_FORTRAN_interface.c -o C_FORTRAN_interface.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c miwa.c -o miwa.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c mvt.f -o mvt.o
/bin/bash: gfortran: command not found
make: *** [mvt.o] Error 127
ERROR: compilation failed for package 'mvtnorm'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/mvtnorm'
* installing *source* package 'cluster' ...
** package 'cluster' successfully unpacked and MD5 sums checked
** libs
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c clara.c -o clara.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c daisy.f -o daisy.o
/bin/bash: gfortran: command not found
make: *** [daisy.o] Error 127
ERROR: compilation failed for package 'cluster'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/cluster'
ERROR: dependency 'mvtnorm' is not available for package 'pcaPP'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/pcaPP'
ERROR: dependencies 'robustbase', 'mvtnorm', 'cluster', 'pcaPP' are not available for package 'rrcov'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/rrcov'
ERROR: dependency 'rrcov' is not available for package 'flowCore'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/flowCore'

The downloaded source packages are in
    '/tmp/RtmpB8elmi/downloaded_packages'
Warning messages:
1: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'robustbase' had non-zero exit status
2: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'mvtnorm' had non-zero exit status
3: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'cluster' had non-zero exit status
4: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'pcaPP' had non-zero exit status
5: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'rrcov' had non-zero exit status
6: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'flowCore' had non-zero exit status

So I installed gfortran and still get similar errors, though it does appear to get a little further (looks like a problem with llapack and lblas but I'm not sure what those are, I don't find them with apt-cache search:
> biocLite(c("flowCore"))
BioC_mirror: http://bioconductor.org
Using Bioconductor version 3.0 (BiocInstaller 1.16.2), R version 3.1.3.
Installing package(s) 'flowCore'
also installing the dependencies 'robustbase', 'mvtnorm', 'cluster', 'pcaPP', 'rrcov'

trying URL 'http://cran.rstudio.com/src/contrib/robustbase_0.92-3.tar.gz'
Content type 'application/x-gzip' length 3144393 bytes (3.0 MB)
opened URL
==================================================
downloaded 3.0 MB

trying URL 'http://cran.rstudio.com/src/contrib/mvtnorm_1.0-2.tar.gz'
Content type 'application/x-gzip' length 155092 bytes (151 KB)
opened URL
==================================================
downloaded 151 KB

trying URL 'http://cran.rstudio.com/src/contrib/cluster_2.0.1.tar.gz'
Content type 'application/x-gzip' length 280102 bytes (273 KB)
opened URL
==================================================
downloaded 273 KB

trying URL 'http://cran.rstudio.com/src/contrib/pcaPP_1.9-60.tar.gz'
Content type 'application/x-gzip' length 191565 bytes (187 KB)
opened URL
==================================================
downloaded 187 KB

trying URL 'http://cran.rstudio.com/src/contrib/rrcov_1.3-8.tar.gz'
Content type 'application/x-gzip' length 992215 bytes (968 KB)
opened URL
==================================================
downloaded 968 KB

trying URL 'http://bioconductor.org/packages/3.0/bioc/src/contrib/flowCore_1.32.2.tar.gz'
Content type 'application/x-gzip' length 8962871 bytes (8.5 MB)
opened URL
==================================================
downloaded 8.5 MB

* installing *source* package 'robustbase' ...
** package 'robustbase' successfully unpacked and MD5 sums checked
** libs
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c R-rng4ftn.c -o R-rng4ftn.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c eigen.f -o eigen.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c init.c -o init.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c lmrob.c -o lmrob.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c mc.c -o mc.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c monitor.c -o monitor.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c qn_sn.c -o qn_sn.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c rf-common.f -o rf-common.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c rffastmcd.f -o rffastmcd.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c rfltsreg.f -o rfltsreg.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c rllarsbi.f -o rllarsbi.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c rob-utils.c -o rob-utils.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c rowMedians.c -o rowMedians.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c wgt_himed.c -o wgt_himed.o
gcc -std=gnu99 -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o robustbase.so R-rng4ftn.o eigen.o init.o lmrob.o mc.o monitor.o qn_sn.o rf-common.o rffastmcd.o rfltsreg.o rllarsbi.o rob-utils.o rowMedians.o wgt_himed.o -llapack -lblas -lgfortran -lm -lquadmath -lgfortran -lm -lquadmath -L/usr/lib/R/lib -lR
/usr/bin/ld: cannot find -llapack
/usr/bin/ld: cannot find -lblas
collect2: error: ld returned 1 exit status
make: *** [robustbase.so] Error 1
ERROR: compilation failed for package 'robustbase'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/robustbase'
* installing *source* package 'mvtnorm' ...
** package 'mvtnorm' successfully unpacked and MD5 sums checked
** libs
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c C_FORTRAN_interface.c -o C_FORTRAN_interface.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c miwa.c -o miwa.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c mvt.f -o mvt.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c mvtnorm-init.c -o mvtnorm-init.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c tvpack.f -o tvpack.o
gcc -std=gnu99 -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o mvtnorm.so C_FORTRAN_interface.o miwa.o mvt.o mvtnorm-init.o tvpack.o -lgfortran -lm -lquadmath -L/usr/lib/R/lib -lR
installing to /home/alex/R/x86_64-pc-linux-gnu-library/3.1/mvtnorm/libs
** R
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded
* DONE (mvtnorm)
* installing *source* package 'cluster' ...
** package 'cluster' successfully unpacked and MD5 sums checked
** libs
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c clara.c -o clara.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c daisy.f -o daisy.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c dysta.f -o dysta.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c fanny.c -o fanny.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c init.c -o init.o
gfortran   -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4  -c mona.f -o mona.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c pam.c -o pam.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c sildist.c -o sildist.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c spannel.c -o spannel.o
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c twins.c -o twins.o
gcc -std=gnu99 -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o cluster.so clara.o daisy.o dysta.o fanny.o init.o mona.o pam.o sildist.o spannel.o twins.o -lgfortran -lm -lquadmath -L/usr/lib/R/lib -lR
installing to /home/alex/R/x86_64-pc-linux-gnu-library/3.1/cluster/libs
** R
** data
*** moving datasets to lazyload DB
** inst
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
* DONE (cluster)
* installing *source* package 'pcaPP' ...
** package 'pcaPP' successfully unpacked and MD5 sums checked
** libs
g++ -I/usr/share/R/include -DNDEBUG -DR_PACKAGE_FILE     -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c L1Median_HoCr.cpp -o L1Median_HoCr.o
/bin/bash: g++: command not found
make: *** [L1Median_HoCr.o] Error 127
ERROR: compilation failed for package 'pcaPP'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/pcaPP'
ERROR: dependencies 'robustbase', 'pcaPP' are not available for package 'rrcov'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/rrcov'
ERROR: dependency 'rrcov' is not available for package 'flowCore'
* removing '/home/alex/R/x86_64-pc-linux-gnu-library/3.1/flowCore'

The downloaded source packages are in
    '/tmp/RtmpB8elmi/downloaded_packages'
Warning messages:
1: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'robustbase' had non-zero exit status
2: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'pcaPP' had non-zero exit status
3: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'rrcov' had non-zero exit status
4: In install.packages(pkgs = pkgs, lib = lib, repos = repos, ...) :
  installation of package 'flowCore' had non-zero exit status

A: According to the Ubuntu forums (you don't say which Linux flavour you are using but since you mentioned apt-cache I'm assuming this is relevant although the answer is several years old) the required packages to install LAPACK and BLAS are
libblas3gf
libblas-doc
libblas-dev

liblapack3gf
liblapack-doc
liblapack-dev

However, I was under the impression that R ships with its own version of these libraries so it may just be a matter of setting your LD_LIBRARY_PATH correctly.
Also note that you seem to be missing g++ as well.


text:
Q: Composition of Transpositions Proof Here is the question that I'm working on:

Show that if $n \geq 2$, then every permutation of $\{1,2,...,n\}$ can be expressed as the composition of transpositions of the form ($1$ $a$), where $a = 2,3,...,n$.

We'll, let's say that we call such a set $S$ such that it has the elements $$S = \{1,2,3\}.$$
Then it's obvious that the composition of transpositions for this set if given by $$(13),(12)$$
That's the case only when $n = 3$ and $a = 2,3$. Visually, I know that this result will happen for other values of $n$ and $a$, but describing this observation as a proof is where I'm stuck on. How should I start the proof?
EDIT It seems the way to handle this problem is to give a proof by induction on $n$.


text:
Q: Overwrite CSS of Instaemail plugin popup I am using instaemail plugin on my wordpress for sending a post by email and I am trying to customize popup window, but seems that I can not overwrite Id or I don't know how to do it. Same popup you can find on link above if you click on email (try it)
I had success with changing wraper color and classes by putting in style.css
div#pf-email-wrapper {
    background-color: rgba(09, 85, 3, 0.50);
}

but how to change (overwrite URL)
.email-sprite{
  background: url('/images/email/email-app-sprite.png') no-repeat;
}

or change color of
.pf-email label {
  color:#356da9; }

So the CSS in style.css would overwrite default CSS of Instamail script
It is not problem in priority  It is in calling the class in style.css probably

P.S. Is there any plugin which for "send to friend" button and to
  customization of popup and customization of email template

A: This is a CSS-related question, more than a Wordpress related one. In your case all the rules that apply for normal CSS overriding are usable to solve your problem:

*

*Cascade: Apply the rules with the same specificity (same number and types of selectors) after the rules written by your plugin. The way to achieve this depends on which hook your plugin uses to enqueue its styles; you can look at the source code and check for that and then use the priority argument of the hook to achieve proper cascading.

*Specificity: Simply be more specific than the rule you want to overwrite. Read more about specificity.

*Use !important: add !important after the rule you want to display and you will win all specificity/cascade wars… ever. Hence, this is not really recommended when you have other options.

*Use inline styles: This is strongly not recommended, because it's usually a bad practice. I am putting it out there just for the sake of completeness, hence I will not elaborate on that.


text:
Q: log4j2 writing in file when testing, not when deploying I'm building a web service using jax-rs and wanted to log some stuff when urls are called. I found about log4j 2 and decided to use it.
I dont know why but it works when I do some tests
Response response = target("user/v1/"+alfred.getPseudo()).request().get();
assertTrue(response.getStatus() < 300);

This will put the log String in logs/logs.log (I love logs).
Yet, when I deploy (with glassfish 4.1.1), it doesn't write a single char in the file when I call the same URL.
Here's my log4j2.xml (located in src/main/resources) :
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
       <File name="File" fileName="logs/logs.log">
           <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS}[%t] %c{1} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="File"/>
        </Root>
   </Loggers>
</Configuration>

My web.xml is empty :

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     version="3.0">
</web-app>

I have the lo4j-api and log4j-core, both 2.5, in my pom.xml.
Finally, here's the code :
private final static Logger logger = LogManager.getLogger(MyClass.class);

on which I just call logger.info(String) and logger.error(String).
What am I doing wrong, and what should I do to create logs when deploying ?
Thanks.
EDIT : Perhaps this will help. I previously had
<File name="File" fileName="logs/logs.log" bufferedIO="false">

When I was testing, I had a warning "Hey, you set bufferedIO to false but the default buffer size is 8192, wtf". And this warning was being shown when i was calling the urls during real deployment. I guess that means my configuration was detected when deploying aswell.

A: You need to tell the location in web.xml, I suppose.
<context-param>
  <param-name>log4jConfiguration</param-name>
  <param-value>WEB-INF/classes/log4j2.xml</param-value>
</context-param>
Please check the deployment for the location of log4j2.xml and change the param-value accordingly.
But it is recommended to use a log4j2.xml at WAR level. So it is easy to find and change.

A: Okay, so I understood my mistake from this :
https://stackoverflow.com/a/8486370/5670024
I was trying to write the file inside the application's directory.
Changed
<File name="File" fileName="logs/logs.log">
    <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS}[%t] %c{1} - %msg%n"/>
</File>

to
<File name="File" fileName="c:/logs.log">
     <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS}[%t] %c{1} - %msg%n"/>
</File>

and it works !


text:
Q: JQuery overlay - issues with opening twitter "Allow Access" box I'm using Jquery flowplayer tools overlay to open external links.
External links are working fine with this piece of code shown in the link:
http://www.demiseonline.com/misc/Iframeoverlay.html
Now using this overlay - I wanted to open the twitter dialog which asks users to Allow access to their account.
So in the code below, I replaced http://www.google.com with https://twitter.com/oauth/authenticate?oauth_token=VPVRIsnRz9IX4CAab7brert3jHiEs

<div class="apple_overlay black" id="Overlay1">
   <iframe src ="http://www.google.com" width="100%" height="595px" frameborder="0">
   </iframe>
</div>

When I replace the code, as soon as I load the page, even before I click on the link to open the overlay - the page gets redirected to the twitter URL.
Any idea why that happens for this URL.
Thanks

A: Their page is probably checking if it's in an iframe with something like
var isInIFrame = (window.location != window.parent.location) ? true : false;

-edit
Take a deeper look into the twitter API to connect to their services (https://apiwiki.twitter.com/OAuth-Examples) - You're going to need to be a go between, authenticating the user yourself and sending/retrieving data between the user and twitter.
See also:
http://github.com/jmathai/twitter-async


text:
Q: Compilation of Total with compensated summation I sometimes obtain an unexpected error when trying to call a compiled version of Total with compensated summation turned on. More specifically I define
f1 = Compile[{{x,_Real,1}},Total[x],CompilationTarget->"C"];
f2 = Compile[{{x,_Real,1}},Total[x,Method->"CompensatedSummation"],CompilationTarget->"C"];

When I call the functions via
x=RandomReal[{0,1},10^5]
f1[x]
f2[x]

I sometimes, but not always, obtain a CompiledFunction::cfte error, informing me that the

"Compiled expression [some large number of order $10^{5}$] should be a
  rank 1 tensor of machine-size real numbers."

I have studied the documentation of that error but have been unable to isolate the problem any further. The results of f1 and f2 differ by up to $1\times 10^{-9}$ and the difference becomes even larger for larger input vectors, so I'd quite like to be able to use the (presumably more accurate) version with compensated summation turned on.
Question: What causes the CompiledFunction::cfte error and how can I avoid it when compiling Total with compensated summation?
In case it matters I am using version 9.0 for Linux x86 (64-bit).

A: Compilation of Total
As pointed out in a comment, it seems that the compensated summation form of Total can't be compiled. You can check this using CompilePrint - note the call to MainEvaluate.
Needs["CompiledFunctionTools`"]
CompilePrint@f2  (* from your question *)

Summation in Mathematica
There seem to be plenty of options for summing a list in Mathematica. For example, you can use Plus, which apparently will always do compensated summation, or Tr[], inspired by this question.
uncompiledTotal[x_] := Total[x];
compiledTotal = Compile[{{x, _Real, 1}}, Total[x], CompilationTarget -> "C"];
compensatedTotal[x_] := Total[x, Method -> "CompensatedSummation"];

plus[x_] := Apply[Plus, x];
compiledPlus = Compile[{{x, _Real, 1}}, Apply[Plus,x], CompilationTarget -> "C"];

uncompiledTr[x_] := Tr[x];

Compiled Kahan summation
There is another option, of course, which is to make your own machine-precision compiled implementation of Kahan summation.
kahanSummation = Compile[{{x, _Real, 1}},
  Module[{s, c, y, t, i},
   s = 0.;
   c = 0.;
   For[i = 1, i <= Length@x, i++,
     y = x[[i]] - c;
     t = s + y;
     c = (t - s) - y;
     s = t;];
   s],
  CompilationTarget -> "C",
  RuntimeOptions -> "Speed"]

Comparison: Accuracy
Now let's test the performance of these options, first in terms of the actual result, compared to the built-in compensated summation method (which I assume to be correct).
x = N@RandomReal[{0, 1}, 10^6];
TableForm[MapThread[{#1, NumberForm[Abs[#2 - compensatedTotal[x]], 16]} &,
   {{"Uncompiled total", "Compiled total", "Compensated summation",
     "Kahan summation", "Uncompiled plus", "Compiled plus", "Uncompiled Tr"},
    {uncompiledTotal[x], compiledTotal[x], compensatedTotal[x],
     kahanSummation[x], plus[x], compiledPlus[x], uncompiledTr[x]}}],
 TableHeadings -> {None, {"Function", "Error"}}]

Clearly the behaviours of both Total and Plus depend on whether they are compiled or not. The key thing to note here is that the above compiled implementation of kahanSummation[] gives the same result as Mathematica's own compensated summation approach.
Graphically, we can use the code from ybeltukov's answer here to look at the residuals. See if you can spot the difference between my compiled Kahan method and the built-in!

Comparison: Speed
Finally, it's also worth comparing the timings of each of the methods above, since that's typically a reason to use Compile[] in the first place.

The compiled implementation of kahanSummation[] is much faster than either Plus or Total with compensated summation, and the extra operations it utilises are only a small performance hit compared to the built-in implementation of Total.


text:
Q: MLflow saving a run to a specific experiment id I am trying to save runs called from MLflow Projects to specific experiment names/ids.
Currently, my MLflow project looks like this:
name: Echo NLP Project

entry_points:
    generate:
        parameters:
            ...
        command: "python scripts/generate_data.py ... --exp_name {exp_name}"

The project calls in the command to the script generate_data.py where I would do some functions and record a run in the function.
I would like to specify where this run would be saved with the exp_name parameter and I am doing this by having this code in generate_data.py:
mlflow.set_experiment(experiment_name)
mlflow.run(uri=os.getcwd(), experiment_name=experiment_name)

However, it is giving me this error:
2021/11/12 15:45:06 INFO mlflow.projects.utils: === Created directory /tmp/tmp3jx68uph for downloading remote URIs passed to arguments of type 'path' ===
2021/11/12 15:45:06 INFO mlflow.projects.backend.local: === Running command 'source /.../profile.d/conda.sh && conda activate mlflow-667a7951db8b0b02e9ac567ea087405cbc28af02 1>&2 && python scripts/generate_data.py ... --exp_name test' in run with ID 'cd2b5b20f00344e5a6257deafabc4791' ===
Traceback (most recent call last):
  File "scripts/generate_data.py", line 32, in <module>
    x = tm(json_folder=args.json_folder, spacy_folder=args.spacy_folder, report_source=args.reports, experiment_name=args.exp_name)
  File "/mnt/c/Users/username/Documents/echo-nlp-model/scripts/train_class.py", line 157, in __init__
    mlflow.run(uri=os.getcwd(), experiment_name=experiment_name)
  File "/mnt/c/Users/username/Documents/venv/lib/python3.8/site-packages/mlflow/projects/__init__.py", line 293, in run
    submitted_run_obj = _run(
  File "/mnt/c/Users/username/Documents/venv/lib/python3.8/site-packages/mlflow/projects/__init__.py", line 92, in _run
    submitted_run = backend.run(
  File "/mnt/c/Users/username/Documents/venv/lib/python3.8/site-packages/mlflow/projects/backend/local.py", line 45, in run
    work_dir = fetch_and_validate_project(project_uri, version, entry_point, params)
  File "/mnt/c/Users/username/Documents/venv/lib/python3.8/site-packages/mlflow/projects/utils.py", line 126, in fetch_and_validate_project
    project.get_entry_point(entry_point)._validate_parameters(parameters)
  File "/mnt/c/Users/username/Documents/venv/lib/python3.8/site-packages/mlflow/projects/_project_spec.py", line 132, in get_entry_point
    raise ExecutionException(
mlflow.exceptions.ExecutionException: Could not find main among entry points ['generate', 'train', 'complete'] or interpret main as a runnable script. Supported script file extensions: ['.py', '.sh']
2021/11/12 15:45:21 ERROR mlflow.cli: === Run (ID 'cd2b5b20f00344e5a6257deafabc4791') failed ===


text:
Q: Word VBA building blocks not immediately available at program start I am using some shapes in a document, and recently switched from creating these on the fly (slow!) to using building blocks. I insert the blocks via VBA code, from a form.
The building blocks are located in a separate file.
This all works, but for some reason the building blocks are not present when I load the document, or any new document.  I get Error 5941 "Member of collection does not exist".
The VBA code explicitly references the building block file, which exists.
Const blockpath = "C:\Users\XXX\AppData\Roaming\Microsoft\Document Building Blocks\1030\16\Building Blocks.dotx"

Dim r As Range
Set r = Application.Templates(blockpath).BuildingBlockEntries("XYZ").Insert(Selection.Range, True) ' range containing inserted block

When I click ONCE on building blocks from the ribbon, the VBA code works, and the elements are available.

Question What can I do in code to check for this, and make the blocks available from start ?
Edit:

*

*No "attach template" or similar is added to VBA when I insert the building blocks with macro recorder.

*Before clicking the building blocks button, the VBA project does not contain the building blocks. After, it does.

A: Word's behavior is to not load Building Blocks until one is called.
You can force loading with the following command:
application.Templates.LoadBuildingBlocks

If they are already loaded, this is redundant but it doesn't hurt anything.
You could also load your building blocks holder as an Add-In.
This could be done by placing it in your Word Startup Folder or through vba.

When the template holding the BB is loaded as an Add-In, it is immediately available to vba. I routinely add my custom building blocks to my template Add-Ins rather than in the generic Building Blocks.dotx. That way if I have code referring to them in the Add-In they are always there. The same would be true if I added it to a document template.
Here is my writing on where Building Blocks can (and should) be stored.
Here is my writing on code to insert a building block. The code to use depends on the storage location.


text:
Q: Get audio bit rate of playback in kernel For the last few weeks I have been reading into the ALSA documentations, but still cannot figure this out so my question: Is there a function be able to derive the current playback audio?
E.g.: If a new song is played, I want to first get the bitrate before ALSA does anything (set clk dividers etc.).
This is on an am335x embedded board, so with aSoC.


text:
Q: Using variable declared in one method to open webpage in another method I am working on a CLI Project and trying to open up a web page by using url variable declared in another method.
def self.open_deal_page(input)
  index = input.to_i - 1
  @deals = PopularDeals::NewDeals.new_deals
  @deals.each do |info|
  d = info[index]
  @product_url = "#{d.url}"
  end
  @product_url.to_s
  puts "They got me!"
end

def self.deal_page(product_url)
  #self.open_deal_page(input)
  deal = {}
  html = Nokogiri::HTML(open(@product_url))
  doc = Nokogiri::HTML(html)
  deal[:name] = doc.css(".dealTitle h1").text.strip
  deal[:discription] = doc.css(".textDescription").text.strip
  deal[:purchase] = doc.css("div a.button").attribute("href")
  deal
  #binding.pry
end

but I am receiving this error.
  `open': no implicit conversion of nil into String (TypeError)

any possible solution? Thank you so much in advance.

A: Try returning your @product_url within your open_deal_page method, because now you're returning puts "They got me!", and also note that your product_url is being created inside your each block, so, it won't be accessible then, try creating it before as an empty string and then you can return it.
def open_deal_page(input)
  ...
  # Create the variable
  product_url = ''
  # Assign it the value
  deals.each do |info|
    product_url = "#{info[index].url}"
  end
  # And return it
  product_url
end

In your deal_page method tell to Nokogiri to open the product_url that you're passing as argument.
def deal_page(product_url)
  ...
  html = Nokogiri::HTML(open(product_url))
  ...
end


text:
Q: "Object can be disposed of more than once" error When I run code analysis on the following chunk of code I get this message:
Object 'stream' can be disposed more than once in method 'upload.Page_Load(object, EventArgs)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.
using(var stream = File.Open(newFilename, FileMode.CreateNew))
using(var reader = new BinaryReader(file.InputStream))
using(var writer = new BinaryWriter(stream))
{
    var chunk = new byte[ChunkSize];
    Int32 count;
    while((count = reader.Read(chunk, 0, ChunkSize)) > 0)
    {
        writer.Write(chunk, 0, count);
    }
}

I don't understand why it might be called twice, and how to fix it to eliminate the error. Any help?

A: The BinaryReader/BinaryWriter will dispose the underlying stream for you when it disposes. You don't need to do it explicitly.
To fix it you can remove the using around the Stream itself.

A: A proper implementation of Dispose is explicitly required not to care if it's been called more than once on the same object.  While multiple calls to Dispose are sometimes indicative of logic problems or code which could be better written, the only way I would improve the original posted code would be to convince Microsoft to add an option to BinaryReader and BinaryWriter instructing them not to dispose their passed-in stream (and then use that option).  Otherwise, the code required to ensure the file gets closed even if the reader or writer throws in its constructor would be sufficiently ugly that simply letting the file get disposed more than once would seem cleaner.

A: Your writer will dispose your stream, always.

A: I struggled with this problem and found the example here to be very helpful.  I'll post the code for a quick view:
using (Stream stream = new FileStream("file.txt", FileMode.OpenOrCreate))
{
    using (StreamWriter writer = new StreamWriter(stream))
    {
        // Use the writer object...
    }
}

Replace the outer using statement with a try/finally making sure to BOTH null the stream after using it in StreamWriter AND check to make sure it is not null in the finally before disposing.
Stream stream = null;
try
{
    stream = new FileStream("file.txt", FileMode.OpenOrCreate);
    using (StreamWriter writer = new StreamWriter(stream))
    {
        stream = null;
        // Use the writer object...
    }
}
finally
{
    if(stream != null)
        stream.Dispose();
}

Doing this cleared up my errors.

A: To illustrate, let's edit your code
using(var stream = File.Open(newFilename, FileMode.CreateNew))
{
    using(var reader = new BinaryReader(file.InputStream))
    {
        using(var writer = new BinaryWriter(stream))
        {
            var chunk = new byte[ChunkSize];
            Int32 count;
            while((count = reader.Read(chunk, 0, ChunkSize)) > 0)
            {
                writer.Write(chunk, 0, count);
            }
        } // here we dispose of writer, which disposes of stream
    } // here we dispose of reader
} // here we dispose a stream, which was already disposed of by writer

To avoid this, just create the writer directly
using(var reader = new BinaryReader(file.InputStream))
    {
        using(var writer = new BinaryWriter( File.Open(newFilename, FileMode.CreateNew)))
        {
            var chunk = new byte[ChunkSize];
            Int32 count;
            while((count = reader.Read(chunk, 0, ChunkSize)) > 0)
            {
                writer.Write(chunk, 0, count);
            }
        } // here we dispose of writer, which disposes of its inner stream
    } // here we dispose of reader

edit: to take into account what Eric Lippert is saying, there could indeed be a moment when the stream is only released by the finalizer if BinaryWriter throws an exception. According to the BinaryWriter code, that could occur in three cases
  If (output Is Nothing) Then
        Throw New ArgumentNullException("output")
    End If
    If (encoding Is Nothing) Then
        Throw New ArgumentNullException("encoding")
    End If
    If Not output.CanWrite Then
        Throw New ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"))
    End If

*

*if you didn't specify an output, ie if stream is null. That shouldn't be a problem since a null stream means no resources to dispose of :)

*if you didn't specify an encoding. since we don't use the constructor form where the encoding is specified, there should be no problem here either (i didn't look into the encoding contructor too much, but an invalid codepage can throw)

*

*if you don't pass a writable stream. That should be caught quite quickly during development...

Anyway, good point, hence the edit :)

A: Suppress CA2202 whenever you are sure that the object in question handles multiple Dispose calls correctly and that your control flow is impeccably readable.  BCL objects generally implement Dispose correctly.  Streams are famous for that.
But don't necessarily trust third party or your own streams if you don't have unit tests probing that scenario yet.  An API which returns a Stream may be returning a fragile subclass.


text:
Q: Evenly distribute task slots across flink task managers I have a flink job(2 task-managers) with a job parallelism of 64 and task slot of 64.
I have a parallelism set for one of the operators as 16. This operator(16 parallelism) slots are not getting evenly distributed across two task managers. It often takes higher task slots like 10/11 in one task manager and 5/6 in other task manager.
I'am using flink version 1.11.2. I tried adding cluster.evenly-spread-out-slots: true but it didn't work. Any solution is greatly appreciated

A: I don't believe there's anything more you can do. The Flink scheduler will try to co-locate consumer tasks with their producers, in order to leverage optimizations in the network stack. (Shared memory is used instead of netty whenever two communicating tasks are in the same JVM.) As I understand it, cluster.evenly-spread-out-slots: true is really only relevant for sources, which don't have input preferences.
It's often the case that reducing the parallelism for part of the job is counter-productive, as it forces a network shuffle (perhaps preventing operator chaining), and creates skew in the load on the task slots.


text:
Q: Visual Studio C# App Version in .NET CORE 6 (used to do in in .Net Framework 4.6.2) I have searched every Google search combinations I know, and I have tried multiple ways to accomplish the following:
In .Net Framework 4.6.2, I could use:
       ApplicationDeployment currentAppDeploy = ApplicationDeployment.CurrentDeployment;

       string version = "v" + currentAppDeploy.CurrentVersion.Major + "." +
            currentAppDeploy.CurrentVersion.Minor + "." +
            currentAppDeploy.CurrentVersion.Revision;

       return version;

How can I get the version from Visual studio of a .NET CORE 6 app?
I have searched every Google search combination I know, and I have tried multiple ways to accomplish it.

A: We can define the version numbers for AssemblyVersion, FileVersion and Version in the project file (.csproj).
 <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <AssemblyVersion>1.1.1</AssemblyVersion>
    <FileVersion>2.2.2</FileVersion>
    <Version>3.3.3-xyz</Version>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

AssemblyVersion
1. GetType().Assembly.GetName().Version.ToString()
2. Assembly.GetEntryAssembly().GetName().Version

Both two methods will return 1.1.1

FileVersion

Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version
It will return 2.2.2

Version

Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion
It will return 3.3.3

using System;
using System.Reflection;

    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine($"Assembly.GetEntryAssembly().GetName().Version: " +
                              $"{Assembly.GetEntryAssembly().GetName().Version}");

            Console.WriteLine($"Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version:" +
                              $"{Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyFileVersionAttribute>().Version}");

            Console.WriteLine($"Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion:" +
                              $"{Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute> ().InformationalVersion}");

            Console.ReadKey();
        }
    }

A: So far, this cannot be done in .NET 6, but there is a ussue on github where this revision is discussed and the developers promise to release it together with support.NET8
https://github.com/dotnet/deployment-tools/issues/27

A: Thank you for the responses. Much appreciated. Based on an answer provided by @lomobit, I read through the GitHub posts and found a class I was able to include in my code. Here is the information and an example:
GitHub Post: https://github.com/dotnet/deployment-tools/issues/27
Class to include: https://github.com/dotnet/deployment-tools/blob/dfb0a98c68da39fc9cd1d82e200a19badf4e7112/Documentation/dotnet-mage/ApplicationDeployment.cs (I currently embedded it in another Helper class, but will likely create a class of its own.)
            if (Helper.ApplicationDeployment.IsNetworkDeployed)
            {
                Helper.ApplicationDeployment current = Helper.ApplicationDeployment.CurrentDeployment;
                this.Text = GlobalCode.GetApplicationName() + $" v{current.CurrentVersion}" + "   |   " +
                    oEmp.NickName + " " + oEmp.LastName + ", " + oEmp.JobCodeDescription;
            }
            else
            {
                this.Text = GlobalCode.GetApplicationName() + $" Dev_Version" + "   |   " +
                    oEmp.NickName + " " + oEmp.LastName + ", " + oEmp.JobCodeDescription;
            }

A: not sure whether ystem.Runtime.InteropServices.RuntimeInformation.FrameworkDescription; is you looking for.
in net7, it return : ".NET 7.0.0"
you can also use the System.Environment.Version


text:
Q: Parse.com Push Notification Service with cocos2d-javascript native project I am trying to add push notification from the parse.com service which has its android sdk and following settings to cocos2d-JS project
Add parse sdk to lib ( I added it to runtime-src/proj.android/lib) and added as build path
Call Parse.initialize from the onCreate method of your Application class to set your application id and client key:
public void onCreate() {
Parse.initialize(this, "app_key", "client_key");
}

For this , I created a package name of com.mycompany.myapp in runtime-src/proj.android/src/
Now android manifest where I have to following things
    <?xml version="1.0" encoding="UTF-8" standalone="no"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" android:versionCode="1" android:versionName="1.0" package="com.mycompany.myapp">
  <uses-sdk android:minSdkVersion="9"/>
  <uses-feature android:glEsVersion="0x00020000"/>
  <application android:name="MyApplication" android:debuggable="false" android:icon="@drawable/icon" android:label="@string/app_name">
    <!-- Tell NativeActivity the name of our .so -->
    <meta-data android:name="android.app.lib_name" android:value="cocos2djs"/>
    <activity android:configChanges="orientation" android:label="@string/app_name" android:name="org.cocos2dx.javascript.AppActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
   <activity android:name="com.flurry.android.FlurryFullscreenTakeoverActivity"
             android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode"
             android:hardwareAccelerated="false" >
        </activity>
   <!-- Flurry permissions and settings -->
   <meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version" />

  <!-- parse.com Requires this  -->
  <service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver">
  <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    <action android:name="android.intent.action.USER_PRESENT" />
  </intent-filter>
</receiver>
<receiver android:name="com.parse.ParsePushBroadcastReceiver"
    android:exported="false">
  <intent-filter>
    <action android:name="com.parse.push.intent.RECEIVE" />
    <action android:name="com.parse.push.intent.DELETE" />
    <action android:name="com.parse.push.intent.OPEN" />
    </intent-filter>
</receiver>
<receiver android:name="com.parse.GcmBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND">
  <intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

    <!--
      IMPORTANT: Change "com.parse.starter" to match your app's package name.
    -->
    <category android:name="com.mycompany.myapp" />
  </intent-filter>
</receiver>
<!-- End of the receivers for Push Notifications -->
  </application>
  <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:xlargeScreens="true"/>
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  <!-- Required for Android Id -->
  <uses-permission android:name="android.permission.READ_PHONE_STATE" />
  <!-- Required for InApp  -->
  <uses-permission android:name="com.android.vending.BILLING" />

  <!-- Parse push notifications permisison -->
  <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

<!--
  IMPORTANT: Change "com.parse.starter.permission.C2D_MESSAGE" in the lines below
  to match your app's package name + ".permission.C2D_MESSAGE".
-->
<permission android:protectionLevel="signature"
    android:name="com.mycompany.myapp.permission.C2D_MESSAGE" />
<uses-permission android:name="com.mycompany.myapp.permission.C2D_MESSAGE" />
  <!-- end of permission for parse push notif -->

</manifest>

But still this app is not getting registered for notification , I am trying to use parse.com push service with cocos2d-JS native project anyone where am I going wrong?


text:
Q: GnuPG encrypting all file uploads I would like to encrypt a file as it gets uploaded, generally what happens is that it gets written to disk and then you can encrypt it from there, I would like to encrypt it before that happens.
Is there any module for a http server or for an application framework that would allow me to do that, I don't want to spend a lot of time working on writing the software for this, but if needs must I'll do it.
The important thing is that no unencrypted record ever touches the hard disk.
The hard drive is already encrypted using aes but as the server can be accessed by a third party without my knowledge I would prefer if there was some way to prevent the actual data being /that/ easily compromised.

A: Sysadmin answer: ramdisk holding area for pre-encrypted data.  Never touches the disk, problem solved.  No?

A: Here is the answer I have received but haven't tested yet, I'm not going to mark it as the answer until I have tested exactly what it does.
The answer is this django project, it's for leaking websites, it reads the entire file into memory and then encrypts it.
http://gitorious.org/deaddrop/deaddrop/blobs/master/drop/views.py
There is however a way to chunk the data
http://docs.djangoproject.com/en/1.3/topics/http/file-uploads/
There is also a problem that the httpd is handling the file upload and can ignore the application framework depending... so I need to test it out a lot before I'm sure what it's doing.
However that said I'm pretty sure you can do it with wsgi which I'm pretty sure that django does when you use mod_wsgi with apache... not sure what other web servers use and I'd prefer to use something more light weight.
edit: if someone does happen to test this out rigorously, and posts it as an answer I'll mark that as the answer.

A: What I ended up doing was using mod_wsgi..
with that I'm able to take the upload as a stream and then encrypt it using PyCrypto
works nicely
        inputLength  = int(environ.get('CONTENT_LENGTH', 0))
        input = environ['wsgi.input']
        f = open(dropDir + '/input','w')
        while 1:
                remain = inputLength - f.tell()
                if remain <= 0: break
                chunk = input.read(min(chunksize, remain))
                if  not chunk: break
                f.write(crypt.encrypt(chunk))
        f.close()

When I do that I end up encrypting the entire postdata using a stateful cipher and writing it into a file, I then save the key to another file after using GnuPG to encrypt that.


text:
Q: Microsoft crash upon reaching "End Sub" in VBA for MSAccess I'm having a problem with a form that adds a source association to a company record. In the main form, the user specifies the source name to be associated, and then this form opens to allow the user to confirm the name, and pick a year, if that name has more than 1 year associated with it. When the user clicks on "Continue", the code checks if the association already exists, whether the source has multiple years, and if so, if the user has selected which year to put with the associated name. When there are not multiple records (ie the name has only one year,) the continue button works just fine, but when the user has to pick a value of the year, the continue buttons works fine and does its job, entering the new association into the database, until it gets to the Exit sub line under the Exit_cmdAssign_Click line, and then the whole Access stops. I get a message box saying "Microsoft has stopped working", it backs up the database and eventually reopens it. At one point, as it stopped it gave me an option to debug in Visual Studio, but there, there were problems finding necessary files for the debug. Before I tried to debug, it said, "An unhandled win32 exception occurred in DWWIN.EXE [8940]."
Does anyone know how an exit sub can cause such a crash when one extra variable is included in an equation, which actually performs as it should, but then seems to cause problems exiting the sub?

A: Crashes of Access are not regular errors that you can fix by changing your VBA code. No matter what your code is, under no circumstances should this happen.
That said, from time to time Access does crash. Most of the time the cause lies in an inconsistent compilation state. That can be easily remedied by decompiling the database. Follow the instructions over here: https://stackoverflow.com/a/3266849/6216216
And make sure you have a backup copy of the database before you decompile.


text:
Q: Starting and ending position of subarray with given sum Problem Statement:
Given an unsorted array arr of size n of non-negative integers, find a continuous sub-array which adds to a given number s.

I have used sliding window technique to compute the sum of sub-array and then to compare it with the given number (s).

Here's my code that takes an array arr of size n, required sum s from the user and returns the starting and ending position of the subarray if it exist or -1 if it doesn't:

Note: Position of array elements is starting from 1 in the required output. Hence, for index say i=0, position will be (i+1)
vector<int> subarraySum(int arr[], int n, int s){
    int l=0,r=0;
    vector<int>v;
    long long sum=0;
    while(r<n)
    {
        sum=sum+arr[r];
        if(sum==s)
        {
            v.push_back(l+1);
            v.push_back(r+1);
            break;
        }
        else if(sum<s)
        {
            r++;
        }
        else{
            sum-=arr[l];
            l++;
            if(sum==s)
            {
                v.push_back(l+1);
                v.push_back(r+1);
                break;
            }
            r++;
        }

    }
    if(v.empty())
    {
        v.push_back(-1);
    }
    return v;
}

The first test case where this code fails is
Input:
42 468 //n=42,s=468 and rest of the values are the array elements
135 101 170 125 79 159 163 65 106 146 82 28 162 92 196 143 28 37 192 5 103 154 93 183 22 117 119 96 48 127 172 139 70 113 68 100 36 95 104 12 123 134

Its Correct output is:
38 42

And above Code's output is:
-1

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 10^5,
1 <= Ai <= 10^10
Can someone please enlighten me with this and where I'm getting wrong ? And also what is the best approach to solve such questions ?


text:
Q: Android GPS tracker какие средства использовать? Здравствуйте! Я начинающий разработчик. Одна из функций приложения должна вести мониторинг местоположения пользователя с отправкой координат местоположения на сервер. В 2018 году какими средствами актуальнее реализовывать данный функционал? Стандартные средства ос android или воспользоваться Google api?

A: Стоит прочитать
это и
вот это, и картина должна прояснится


text:
Q: non-lipschitz fourier transform As is well known the Fourier transform of a $L^1(\mathbb R)$ function is continuous, bounded and vanishes at infinity. It is also well-known that not every such function is a Fourier transform of some $L^1(\mathbb R)$. Can You provide me with an example (as explicit and as simple as possible) of a $L^1(\mathbb R)$ function, whose Fourier transform is continuous, bounded, vanishes at infinity but is not Lipschitz. Or this is impossible (?)

A: Let
$$
f(x)=\frac{J_1(x)}{x}\text{ if }x\ne0,\quad f(0)=\lim_{x\to0}\frac{J_1(x)}{x}=\frac12,
$$
where $J_1$ is a Bessel function. Then $f\sim x^{-3/2}$ as $x\to\infty$, so that $f\in L^1(\mathbb{R})$.
$$
\hat f(\xi)=\sqrt{\frac2\pi}\,\sqrt{1-\xi^2}\text{ if }|\xi|\le1,\quad \hat f(\xi)=0\text{ if }|\xi|>1.
$$
$\hat f$ fails to be Lipschitz at $\xi=\pm1$.


text:
Q: Why do we use fixed effects and controls at the same time? When we run a regression model (say OLS for simplicity) of y ~ x, we might have to use several control variables say z1 and z2. Now our model is y ~ x + z1 + z2, we may believe that z1 and z2 are not perfect controls then we introduce fixed effect dummies.
Now our model is y ~ x + z1 +z2 + fixed effects; but if the fixed effects take into account all control information then surely they must be seriously correlated with z1 and z2. Otherwise, by definition z1 and z2 are junk. Is this not going to introduce multi-collinearity?

A: It's not possible to identify the parameters of a model when the fixed effects take into account all of the variation in the control variables.  When you include fixed effects, the control variables that remain in the equations can only be variables that vary within each fixed effect group.  Otherwise there will be perfect collinearity, and no variation with which to identify the coefficients of the control variables.


text:
Q: Received invalid field length error in nodejs with mysql application I'm getting below error while fetching records (apx 50 rows) from my sql database. My application is developed in nodejs with express.

var common = require(__base + 'routes/common.js');
var dbhelper = require(__base + 'routes/dbhelper.js');

exports.GetStates = function (callback) {
    dbhelper.pool.getConnection(function (err, connection) {
        // Use the connection
        connection.query('CALL GetStates()',
            function (err, res) {
                connection.release();
                if (err) {
                    common.ActionOutput.Status = common.ActionStatus.Error;
                    common.ActionOutput.Message = 'System Error: ' + err.message;
                } else {
                    common.ActionOutput.Status = common.ActionStatus.Success;
                    common.ActionOutput.Result = res[0][0];
                }
                return callback(JSON.stringify(common.ActionOutput));
            });
    });
};

dbhelper.js is

// Database connection
var mysql = require('mysql');

var pool = mysql.createPool({
    connectionLimit: 10,
    host: 'my ip',
    user: 'user',
    password: 'pass',,
    database: 'ssdsdas'
});

exports.pool = pool;

A: I ran into the same error message but the causes of our issues might be different. Ultimately, the cause of my issue is that the column names in my stored procedure did not have back ticks (`) resulting in them being treated as variables.
Adding back ticks in my stored procedure body for column names fixed it.


text:
Q: __declspec(noinline) on lambda function inside template class throws syntax error in VS2017 While trying to debug an issue with an assert macro I came across this problem.  Using __declspec(noinline) on a lambda function in a template class generates a syntax warning in Visual Studio 2017:

error C2760: syntax error: unexpected token '__declspec', expected '{'

This is the failing code:
template<class R>
class test
{
public:
    void DoStuff()
    {
        []() __declspec(noinline) { }; // syntax error
    }
};

int WinMain(void)
{
    return 0;
}

If I go to my project settings and switch my platform toolset from v141 (vs2017) to v140 (vs2015) in the general section of the project properties dialog the error goes away .
If I change the class to not be a template class it also compiles correctly:
class test
{
public:
    void DoStuff()
    {
        []() __declspec(noinline) { }; // compiles fine
    }
};

int WinMain(void)
{
    return 0;
}

I'm curious why this wouldn't succeed using the v141 platform toolset.  Is there some other project setting that could be affecting this?

A: I was able to fix this by updating Visual Studio 2017 to the latest version (15.9.7).  Previously I was running version 15.6.7.  Thanks to everyone who looked in and commented! :)

A: It works in VC++ 2019, so may just be a regression in 2017?


text:
Q: Going back to previous activity using ActionBar navigation In my app, I model Lists of items. In MainActivity, I see ListView containing Lists. I can click on each list to see its items (DisplayListActivity). On DisplayListActivity, I have button in the ActionBar to display the list properties. This launches the third activity (EditListPropertiesActivity).
              Main
              | ^
              V |
      DisplayListActivity (listId is passed with Intent, default=1)
              | ^
              V |
   EditListPropertiesActivity (listId is passed with Intent, default=1)

The problem appears, when I select List id=2 on the MainActivity, and then I select the properties button on the DisplayListActivity. Once I am done with the EditListPropertiesActivity, i click '<' (back) on the ActionBar: .
I return to the DisplayListActivity, but instead of going back to the list id=2, I see the list with id=1 (which is default).
How to pass the ListId back form EditListPropertiesActivity to the DisplayListActivity?

*

*startActivityForResult and return the id - would work, but I see it ugly

*use the SharedPreferences and store sth like lastVisitedList - ugly

*store the lastVisitedList information in the db - even uglier

What is the usual solution for that problem?
Code snippets below.
MainActivity
public class MainActivity extends Activity {
...
listView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    MetaList mlist = (MetaList) listView.getItemAtPosition(i);

                    final Intent intent;
                    intent = new Intent(getApplicationContext(), DisplayListActivity.class);
                    intent.putExtra(META_LIST_SELECTED, mlist.getId());
                    startActivity(intent);
                }
            }
    );
...

DisplayListActivity
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_list);

    intent = getIntent();
    metaListId = intent.getLongExtra(MainActivity.META_LIST_SELECTED, 1); //read the data or take 1 as default
    ...
    //start the third activity
    final Intent intent;
    intent = new Intent(getApplicationContext(), EditListPropertiesActivity.class);
    intent.putExtra(META_LIST_SELECTED, metaListId);
    startActivity(intent);
    ....

EditListPropertiesActivity
public class EditListPropertiesActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_list_parameters);

    getActionBar().setDisplayHomeAsUpEnabled(true);  //this enables the '<' (back) button

    intent = getIntent();
    metaListId = intent.getLongExtra(DisplayMetaListActivity.META_LIST_SELECTED, 1);
    ...

Manifest
<application>
    <activity
            android:name=".MainActivity">
    </activity>
    <activity
            android:name="com.example.tutorial1.DisplayListActivity"
            android:parentActivityName="com.example.tutorial1.MainActivity" >
        <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.tutorial1.MainActivity" />
    </activity>
    <activity
            android:name="com.example.tutorial1.EditListPropertiesActivity"
            android:parentActivityName="com.example.tutorial1.DisplayListActivity" >
        <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.tutorial1.DisplayListActivity" />
    </activity>
</application>

A: try this to finish an activity
Intent intent = new Intent();
intent.putExtra(EXTRA, value);
setResult(RESULT_OK, output);
finish();

and this for getting the result in the previous activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(data.getExtras().containsKey(EXTRA)){

       // do stuff with data from finished activity

       String bla = data.getStringExtra(EXTRA)

    }
}

EDIT: read comments! need to use startActivityForResult

A: try to call finish(); that you should call on destroy of the current activity and display the previous activity.

A: I have found the solution that works. I post it here, because it is cleaner (in my opinion) and different than the other proposed. I set the launch mode of the second activity to singleTask in the manifest file: android:launchMode="singleTask"
    ...
    <activity
        android:name="com.example.tutorial1.DisplayListActivity"
        android:label="Meta List"
        android:parentActivityName="com.example.tutorial1.MainActivity"
        android:launchMode="singleTask">
        <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.tutorial1.MainActivity" />
    </activity>
    ...

If there is a better solution for the stated problem, I am open for discussion :)


text:
Q: Off screen absolute positioned Div causing horizontal scrolling EDIT/UPDATE: 7th June 2019
I've determined this is a bug in Safari, as the CSS works perfectly in all other browser. For anyone who finds this, if you're creating a sliding menu (which slides offscreen to the right of the viewport), as of Safari 12.1.1, adding overflow-x to the body tag will not work (it does work on Chrome, Firefox etc) - this means that when your menu div is positioned offscreen to the right, the user can scroll horizontally and see the menu.
I've found a (sort of) workaround is to give the parent container of the menu dive a position:fixed attribute - this obviously only works if you intend for your header to be fixed.
Original Question
I'm building a simple header with a menu that slides from right to left when the menu button is pressed. However, when I position the menu div offscreen (left: 100%), on Safari, I can scroll horizontally right to see the menu div. (No scroll bars appear, but I can scroll right via the Mouse)
If I set overflow-x:hidden on the header, then it hides the offscreen div, but also won't show it if you set the left:0 (ie. overflow-x seems to be hiding x and y directions).
Even more perplexing, if I change the header to position:fixed, then it works and you can't scroll right to see the offscreen menu div.

html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.header {
  width: 100%;
  padding: 10px;
  background: #CCC;
  position: relative;
}

.slideMenu {
  position: absolute;
  top: 100%;
  left: 100%;
  width: 100%;
  padding: 10px;
  background: #666;
}

  Header ---> Scroll to Right

    Menu is visible offscreen- :(

Here's an example of the problem: https://jsfiddle.net/ar7qyfgt/

A: I ran into a similar issue with Safari. Solution that appears to be working is to apply overflow-x: hidden; to the html AND body tags.
Adding to body resolved issue in all browsers expect Safari. Applying it to both seems to do the trick with Safari while still supporting the other browsers.

A: I have the same issue in my Safari(Version 12.1.1) when I set my div to position: absolute and right: -15rem;
To fix it, I added a  to include all elements within  and have the CSS like this:
.wrapper {
  position: relative;
  overflow-x: hidden;
}

Hope this help.

A: What you currently have works, you just need to set overflow-x:hidden on the body instead of the .header

A: What are you trying to accomplish? This?:

JSFiddle: (https://jsfiddle.net/pzeqfb51/)
HTML:

  Header ---> Scroll to Right

    Menu is visible offscreen- :(

CSS:
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}

.header {
  width: 100%;
  padding: 10px;
  background: #CCC;
  position: relative;
}

.slideMenu {
  position: absolute;
  top: 100%;
  left: 100%;
  width: 100%;
  padding: 10px;
  background: #666;
}

div {
  display:inline-block;
}


text:
Q: How do I dock a resizable ExtJS Ext.Panel within another resizable docked panel I have a Modern ExtJS Ext.Panel docked left with resizable set with edge 'east'.
IN this left panel, I want

*

*Flex upper panel

*docked bottom panel with edge 'north' within the docked left panel.

The "flex" upper left panel does not flex.  See Sencha fiddle

A: Just turned out that the docked left panel needed a layout: 'vbox'.


text:
Q: Node js make request to SQL Server, return result Working with Node.js and am having some trouble understanding how to return the result after making a request to SQL Server. When running independently and writing to the console, I can get the result just fine, however using it as a function and having it return the result is where I am running into problems.
I'm pretty sure I have to use a callback/promise, but don't really understand how either of those are set up. Hoping someone on here can help me out!
Here is my code:
var sql = require("mssql");

var config = {
    user: 'username',
    password: 'password',
    server: 'localhost',
    database: 'Master'
};

function updateTable() {
    var connection = new sql.ConnectionPool(config, function(err) {
        var request = new sql.Request(connection);
        request.query('select LastName from Persons', function(err, result) {
           return result.recordset;
        });
    });
};

console.log(updateTable());

Basically trying to print the result to the console by calling the function through console.log. Right now it's printing 'undefined', but I assume putting in a callback would do the trick. Again, just need some help understanding how it works and getting it set up. Thanks!

A: If you just want to print it to the console then you can simply tweak your code as follows:
var sql = require("mssql");

var config = {
    user: 'username',
    password: 'password',
    server: 'localhost',
    database: 'Master'
};

function updateTable(callback) {
    var connection = new sql.ConnectionPool(config, function(err) {
        var request = new sql.Request(connection);
        request.query('select LastName from Persons', function(err, result) {
           callback(result.recordset);
        });
    });
};

updateTable(console.log);

To send the result from an express handler, assuming >= NodeJS v8:
Wrap the actual database interfacing logic inside an async function which will not block the main thread and export it from your module.
sqlConnector.js
const sql = require('mssql');

const config = {
    user: 'username',
    password: 'password',
    server: 'localhost',
    database: 'Master'
};

const updateTable = async () => {
    try {
        const pool = await sql.connect(config);
        const sqlQuery = 'SELECT LastName FROM Persons';
        const result = await pool.request().query(sqlQuery);
        return result;
    } catch (err) {
        throw err;
    }
};

export.updateTable = updateTable;

In express handler
Import your module which talks with MS-SQL (assumed sqlConnector.js) and mark your handler with the async keyword and return it from res.json at the end.
const sqlConnector = require('sqlConnector');

app.get('/someroute', async (req, res, next) => {
  try {
    const result = await sqlConnector.updateTable();
    return res.status(200).json(result);
  } catch (error) {
    next(error);
  }
});


text:
Q: How to calculate age in python from a file? Here's how my file looks like
Name  Gender Birth Death
John  Male   1940  1990
Steve Male  1953  1985
John  Male  1933  1965
Sara  Female 1917 1955
I have tried these methods and getting some errors.
file = pd.read_csv('file')

df.insert(6, "Age", file['Death - Birth'])
age = pd.Series([])

and
for i in range(len(df)):
age[i] = df['Death Year - Birth Year']

I want to add a age column which would calculate the age based on birth and death year.

A: The following should be a simple fix:
df = pd.read_csv('file.csv')

df['age'] = df['death'] - df['birth']


text:
Q: How to fix for /f loop in batch file to run multiple powershell scripts in directory I am trying to make the following command run multiple powershell script files located in a specified directory:
@echo off
for /F %%f in ('dir /b "C:\ProgramData\MyScripts\"') do Powershell.exe -ExecutionPolicy Bypass -NoLogo -WindowStyle Hidden -File C:\ProgramData\Scripts\%%f
pause

It works fine in the command line, however it doesn't work in a batch file (even though the "%" has been changed to "%%"). Any ideas how I can make this work?

A: The following is a method I would suggest you try:
@If Exist "C:\ProgramData\MyScripts\*.ps1" For %%A In (
    "C:\ProgramData\MyScripts\*.ps1"
)Do @Powershell -NoP -NoL -Ex Bypass -W Hidden -F "C:\ProgramData\MyScripts\%%A"

I have filtered to ensure that only .ps1 files are parsed, to exclude any non PowerShell scripts from being run. I have also changed the location of the files to run, because it appeared that you were parsing files in one directory, C:\ProgramData\MyScripts, but trying to run them in another, C:\ProgramData\Scripts.
Note also that this will not run every file in the directory, those which are for instance hidden will not be parsed. To do that you'd be better advised to use a For /F loop and choose the files using the Dir command:
@For /F Delims^=^ EOL^= %%A In ('
    Dir /B/A-D-L "C:\ProgramData\MyScripts\*.ps1" 2^>Nul
')Do @Powershell -NoP -NoL -Ex Bypass -W Hidden -F "C:\ProgramData\MyScripts\%%A"

Please take account that each script will be run after the previous one has ended, if you wished to run each immediately after beginning the previous one, I'd suggest you open a Command Prompt window and take a look at the help information output from Start /?, for a method of doing so.

A: I suggest you restructure your approach so as to avoid having to duplicate the scripts' directory path - which may well be the source of your problem:
Let PowerShell do the file enumeration:
@echo off
powershell -ExecutionPolicy Bypass -WindowStyle Hidden -Command ^
  "dir C:\ProgramData\MyScripts\*.ps1 | foreach { & $_ }"
pause

Note that switching from -File to -Command was necessary in order to submit an entire PowerShell command; -NoLogo is then not needed.
Also consider adding -NoProfile to suppress loading of your profile file.
As for the PowerShell command:

*

*dir is used for brevity, but note that it is an alias, namely for the Get-ChildItem command.

*foreach is an alias for the ForEach-Object cmdlet, which runs the associated script block ({ ... }) for each input object (file), reflected in automatic variable $_.

*& is the call operator, which is needed to invoke a command (name or path) stored in a variable.

If you prefer to stick with your original approach and want to fix that, see Compo's helpful answer.


text:
Q: ui-route works weird juste the first time angularjs i have a problem, The first time I press my button every works fine but when I close the modal and I want to re-press the button(open me) , It does not work anymore
where is the problem ?
this is my route
angular.module('ui.bootstrap.demo').config(function($stateProvider, $urlRouterProvider,$qProvider){
      $stateProvider

          .state("connexion", {
              url: "/",
               views: {

                // for column two, we'll define a separate controller
                'Principal': {

                    abstract :true,
                   templateUrl: 'connexion.html'

                }
               }

          })

          .state('agenda', {

            url: "/agenda",
            views: {

                // for column two, we'll define a separate controller
                'Principal': {

                    abstract :true,
                   // templateUrl: 'agenda.html'
                    template:'Open me!'

                }
            }

        })
        .state('modal', {
        abstract: true,
        parent: 'agenda',
        url: '/modal',
        onEnter: ['$uibModal', '$state', function($uibModal, $state) {
            $uibModal.open({
            animation: true,
            ariaLabelledBy: 'modal-title',
            ariaDescribedBy: 'modal-body',
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            resolve: {

            }
          })
        }]
      })
      .state('view', {
        url: ':id1',
        parent: 'modal',
        views: {
          'modal@': {
            template: '
'+
                          '
'+
                          '
Quick Start
'+
                          '
'+
                          '
Route 1
'+
                          '
Route 2
'+
                          '
'+
                          '
'+
                          '
'
          }
        }
      })
      .state('foo', {
        url: ':id2',
        parent: 'modal',
        views: {
          'modal@': {
            template: '
foo
back menu'
          }
        }
      })
      .state('bar', {
        url: ':id3',
        parent: 'modal',
        views: {
          'modal@': {
            template: '
bar
back menu'
          }
        }
      })

      $urlRouterProvider.otherwise("/");
       $qProvider.errorOnUnhandledRejections(false);

    })

and this is a plunker
http://plnkr.co/edit/4D6fsQv0FiPqtjoNiebS?p=preview
if someone can help me
thanks in advance

A: This had two issues.

*

*You were not having a reference to controller in your modal template. Which is why the buttons Ok and Cancel don't work! So, using the controllerAs syntax,
$uibModal.open({
  animation: true,
  ariaLabelledBy: 'modal-title',
  ariaDescribedBy: 'modal-body',
  templateUrl: 'myModalContent.html',
  controller: 'ModalInstanceCtrl',
  controllerAs: '$ctrl',
  resolve: {}
})

*You were remaining in the same state of modal even after closing it. Fixed that by following,
$ctrl.ok = function() {
  alert(2)
  $uibModalInstance.close();
  $state.go("agenda");
};

$ctrl.cancel = function() {
  $uibModalInstance.dismiss('cancel');
  $state.go("agenda");
};

Edit: In order to cover all kinds of modal close and visit agenda state, you can make use of modalInstance.closed.then. Like this:
var modalInstance = $uibModal.open({
    ...
})

modalInstance.closed.then(function() {
    $state.go("agenda")
})

You can remove the $state.go from the $ctrl.ok and cancel buttons.
updated working plunker

A: There were two issues. One was that you didn't have controllerAs syntax going in your modal. This meant that when your "Ok" button in the modal was clicked, the ok function wasn't firing.
The second issue was that you weren't reverting your route back from "agenda/modal" back to "agenda" when closing the modal. So when you clicked, "Open me!" again, it was just staying on "agenda/modal/", and no route change was taking place to trigger the modal's "onEnter".
http://plnkr.co/edit/KyyUS6Y5lwVRr2fYfxNq?p=preview
To fix it I wired up the controllerAs like this
 onEnter: ['$uibModal', '$state', function($uibModal, $state) {
        $uibModal.open({
        animation: true,
        ariaLabelledBy: 'modal-title',
        ariaDescribedBy: 'modal-body',
        templateUrl: 'myModalContent.html',
        controller: 'ModalInstanceCtrl',
        controllerAs: '$ctrl',
        resolve: {

        }

and then had the buttons change the route back like this
 <button class="btn btn-primary" type="button" ng-click="$ctrl.ok()" ui-sref="agenda">OK</button>
 <button class="btn btn-warning" type="button" ng-click="$ctrl.cancel()" ui-sref="agenda">Cancel</button>


text:
Q: What is the connection limit to S3 using AWS SDK Ruby gem? Is there a connection pool for aws-sdk?
How many concurrent connections can I have to S3 from a single app instance? Is there a config for this?

A: Not sure what you trying to do but check this: https://docs.aws.amazon.com/AmazonS3/latest/dev/request-rate-perf-considerations.html that is also mentioned in the answer here: https://stackoverflow.com/a/37432967/177154
Also not sure if you have already checked this:
https://github.com/aws/aws-sdk-ruby/blob/master/gems/aws-sdk-core/lib/seahorse/client/net_http/connection_pool.rb ?
As a protip - fairly early in the S3 doc article, there is a link to open a support case on AWS support. This might seem odd and it is often neglected by devs but there are reports that opening a case like this could end up with a really good info/solution for whatever the extraordinary case you might have.


text:
Q: How to use a conditional array formula in Google Sheets? I want my spreadsheet user to be able to choose between two different options for an array formula. I have tried to put it in an IF statement but I can't get it to work. I do not want to cut and paste it down the column because I want it to be applies when a new row is added. I don't really know what I'm doing but I've been fiddling with it for a couple of hours now. Here is the code I currently have:
=IF($B$6="alternating days",ARRAYFORMULA(IF(ISBLANK(indirect("OVERVIEW!$A" & row())),IF($C2:C="l","l","d"),IF($C2:C="l","d","l"))),IF($B$6="weekdays/weekends",ARRAYFORMULA(IF(ISBLANK(indirect("OVERVIEW!$A" & row())),IF($C2:C="l","l","d"),IF(OR(WEEKDAY
(indirect("OVERVIEW!$A" & row()))=1,WEEKDAY(indirect("OVERVIEW!$A" & row()))=7),"l","d"))),"none"))
It's a long formula so please scroll along.
I attempted to have the ARRAYFORMULA at the beginning but it wouldn't let me reference just $B$6.
Thanks for any help you can provide.

A: I recommend something like this:
=ARRAYFORMULA(IF($B$6="alternating days",if(isodd(row(indirect("C4:C"&counta(OVERVIEW!A3:A)+3))),"l","d"),IF($B$6="weekdays/weekends",ARRAYFORMULA(IF(WEEKDAY(OVERVIEW!A3:A)=1,"d",if(WEEKDAY(OVERVIEW!A3:A)=7,"d","l"))))))

If the days are alternating, use odd rows to alternate the letter, otherwise just combine 2 IF statements to determine if it is a weekday or not.


text:
Q: Trasform a datatable in pivot for datagrid I need to transform a datatable into a pivot table, but I can't value the fields, at least in the datagrid in WPF I don't see it this is my code
my select data
"SELECT [Giorno] ,[Turno] ,[Ispettori] ,[Totale] FROM TABLE WHERE Giorno >= '2020.02.29' and Giorno <= '2020.02.29' ORDER BY [Giorno], [Turno]";

With the result I enhance my datatable
DataTable dt = new DataTable();

Add a column for calc
dt.Columns.Add("TotalTurno");

foreach (DataRow row in dt.Rows)
  {
      row["TotalTurno"] = row[dt.Columns[3]] + "/" + row[dt.Columns[2]];
  }

Remove the column that I don't need
 dt.Columns.Remove("Ispettori");
 dt.Columns.Remove("Totale");

I extrapolate the columns that I have to add to the datatable (they must be unique)
string[] uniqueAncType = dt.AsEnumerable().Select(x => x.Field<System.DateTime>("Giorno").ToString("dd/MM/yyyy")).Distinct().ToArray();

DataTable pivot = new DataTable();
pivot.Columns.Add("Turno");
Add the column to a pivot datatable
foreach (string col in uniqueAncType)
{
    pivot.Columns.Add(col, typeof(string));
}

I group the data to put it in the datatable pivot
var groups = dt.AsEnumerable()
                .GroupBy(x => new {
                    opr_dt = x.Field<DateTime>("Giorno").ToString("dd/MM/yyyy"),
                    opr_tt = x.Field<string>("TotalTurno"),
                    opr_turno = x.Field<string>("Turno"),
                }).ToList();

Add value to the pivot
foreach (var group in groups)
{
    DataRow newRow = pivot.NewRow();
    newRow["Turno"] = group.Key.opr_turno;

    foreach (DataRow ancType in group)
    {
         newRow[group.Key.opr_dt] = group.Key.opr_tt;
          pivot.Rows.Add(newRow);
     }
}

Obtain this ... :(((
I don't have the values in the column .. can you help me understand why?


text:
Q: Add free text/comment to Freeplane Mindmap Is it possible to add a free unconnected text or node as a comment to a mind map?
I've seen images in the web looking comparable, but I can only add nodes that are connected to the mind map.


text:
Q: ¿Por qué la consulta devuelve 7 filas pero la variable devuelve un count de 1? ¿Por qué si la consulta en sql(phpMyAdmin) devuelve 7 filas, la variable $numero_filas2 saca un echo de 1?
$consultaContar="SELECT count(*) FROM preguntas";
$resultado = mysqli_query($con,$consultaContar);
$numero_filas = mysqli_num_rows($resultado);
echo $numero_filas;

Gracias.

A: declara tu Consulta colocándole a la función de agregación un alias, que será el que recuperaremos después
$consultaContar = $con->query("SELECT count(*) AS Total FROM preguntas");

Una vez hecho lo anterior, pasamos la variable que contiene la consulta, al método mysqli_fetch_assoc()
$resultado = mysqli_fetch_assoc($consultaContar);

Por último como solo estamos obteniendo un resultado que es el que genera la función de agregación, de este modo
var_dump($resultado["Total"]);

Si te fijas al momento de mandar a imprimir a la variable $resultado al mismo tiempo le indico que acceda al valor que pusimos como alias mas arriba llamada Total
Que al final te debe devolver 7
Ahora para respetar la estructura de código que manejas en tu pregunta, te dejo como debería de ir
$consultaContar = mysqli_query($con,"SELECT count(*) AS Total FROM preguntas");
$resultado = mysqli_fetch_assoc($consultaContar);
var_dump($resultado["Total"]);


text:
Q: Timestamp error when attempting to run mysqld When I attempt to run mysqld through the Command Prompt to enter that, I get an error saying:
[Warning] TIMESTAMP with implicit DEFAULT value is deprecated.
Please use --explicit_defaults_for_timestamp server option (see documentation for
more details).

I've tried pasting explicit_defaults_for_timestamp = TRUE into the my.ini file, but that didn't work.

A: Even I faced the same issue
Try passing

explicit_defaults_for_timestamp = 1

A: Try this
Go to mysql server installation directory
C:\program files\mysql\mysql server 5.6\
check for file my.ini
if it is not there duplicate my-default.ini file any rename it to my.ini and add
explicit_defaults_for_timestamp = 1
and save it.

A: You can read more here.
http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_explicit_defaults_for_timestamp
but I guess you only need to run Command Prompt as Administrator
also look at this question How to enable explicit_defaults_for_timestamp?

A: Add the following command and should work. Make sure add --
d:\Program Files\MySQL\MySQL Server 5.6\bin>mysqld.exe --init-file=D:\\mysql-ini
t.txt --explicit_defaults_for_timestamp = 1


text:
Q: SQL Multiple Many-to-many Self-referencing Associations (Sequelize.js) just wondering if the following thing is the proper thing to do.
I have a User table, in which a user can be a buyer or a seller. I have a Sale table to record the item sold/purchased by a user.
Im currently planning to give User a starting schema that looks like this:
id
user_name
display_name
... (other attrs)

A Sale would have a starting schema like this:
id
product_id
price
... (other relevant attrs)

The part I'd like to ask about is the associations. There are two ways of doing it from what I see. We could either establish 2 many-to-many rules for buyer and sellers respectively, or to have sale belong to User twice once as buyer and once as seller. The end state is the same, but I'm not sure which way is better/recommended, and why.
Option 1 (using Sequelize.js format):
User.belongsToMany(User, {
    through: Sale,
    as: 'buyer',
    foreignKey: 'buyer_id',
}

User.belongsToMany(User, {
    through: Sale,
    as: 'seller',
    foreignKey: 'seller_id',
}

Option 2:
Sale.belongsTo(User, {
    foreignKey: 'seller_id',
}

Sale.belongsTo(User, {
    foreignKey: 'buyer_id',
}

In the end, both options result in the foreign key columns buyer_id and seller_id added to the Sale model. But which approach would you recommend? And why?

A: Sale is the association table that implements among other things the many-to-many relation between sellers and buyers.
id
product_id
price
seller_id
buyer_id
... (other attrs)

Note that Sale table is usually used in OLAP, hence it is slightly denormalized.
In OLTP you have usually document or event tables which contains seller and buyer IDs in the headers. I.e.
orders
----
id
date
seller_id
buyer_id
...

order_items
----
order_id
item_index
product_id
price
qty
....


text:
Q: "How to debug 'server side code' in Powerbuilder" I have a powerbuilder application and it is 3 tier architecture. The business objects are written in server side. How to debug the server side scripts? I tried to insert the break point in the server side calling function from the client side script. But it is not step into the server side script.

A: I would try to instantiate the objects locally and debug them that way.


text:
Q: filter object with date within the range I have a list of objects:
listings = [{
    title: "Place 1",
    price: "100",
    availability: [
        {
            startDate: "2022-11-15T13:00:00.000Z",
            endDate: "2022-11-23T13:00:00.000Z",
            key: "selection"
        },
        {
            startDate: "2022-11-30T13:00:00.000Z",
            endDate: "2022-12-02T13:00:00.000Z",
            key: "selection"
        },
        {
            startDate: "2022-12-18T13:00:00.000Z",
            endDate: "2022-12-20T13:00:00.000Z",
            key: "selection"
        }
    ]},
    {
     title: "Place 2",
     price: "100",
     availability: [
        {
            startDate: "2022-11-30T13:00:00.000Z",
            endDate: "2022-12-30T13:00:00.000Z",
            key: "selection"
        }]
  }
]

And a list
range = [
    {
        startDate: "2022-12-01T13:00:00.000Z",
        endDate: "2022-12-25T13:00:00.000Z",
        key: "selection"
    }
]

And I would like to get the object side of my listings available during my date range. i.e. startDate smaller than my range[0].startDate and endDate greater than my range[0].endDate.
I have tried doing:
listings.filter(listItem => {
  return parseInt(listItem.price) >= parseInt(minPrice) && parseInt(listItem.price) <= parseInt(maxPrice)
}).filter(listItem => {
  return listItem.availability.map((i) => new Date(i.startDate).setHours(0, 0, 0, 0) <= new Date(range[0].startDate).setHours(0, 0, 0, 0) && new Date(i.endDate).setHours(0, 0, 0, 0) >= new Date(range[0].endDate).setHours(0, 0, 0, 0))
})

However, it did not filter the listItem with availability outside the range as I was expecting, thanks in advance!

A: range[0].endDate.setHours(0, 0, 0, 0)
This expression blows up - you can't invoke setHours() on it (because at this point it's a string literal).
What you probably want to do is to turn it into a Date instance first:
new Date(range[0].endDate).setHours(0, 0, 0, 0)

A: .filter(...) should return a boolean for each item, indicating if this item should stay in the list or not. You are returning the result of .map(...), which is an array of transformed values.
If you look at one example: listings[0].availability.map(a => a.startDate < range[0].startDate) it returns Array(3) [ true, true, false ] and not a single boolean. This array is evaluated to true so your listings are all true and none is removed.
You could use a filter on availability to remove availablities that are not from interest and then check the resulting availabilities if there are more than zero remaining.
listings.filter(listing =>
    listing.availability.filter(availability =>
        new Date(availability.startDate) <= new Date(range[0].startDate) && new Date(availability.endDate) >= new Date(range[0].endDate))
    .length > 0)


text:
Q: Elastic Search - Lookup Nodes I am going through the documentation of network settings - I had few queries with respect to the best practices .

*

*Should the nodes be assigned static ip address for other nodes to reach out reliably or

*DNS lookup

*Doesn't matter the nodes going up or down

What should be the best practise