text:
Q: How to deal with this exception? 'ERROR: Cannot uninstall 'wrapt'. It is a distutils installed project etc.' I am trying to update wrapt in order to update tensorflow 2.0 to its latest version but I am running into the following exception:

ERROR: Cannot uninstall 'wrapt'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

How can I deal with this?
For the full error message:
(base) D:\DIGITAL_LIBRARY\Jupyter_Notebook_Files>pip install wrapt --upgrade
Collecting wrapt
  Using cached https://files.pythonhosted.org/packages/23/84/323c2415280bc4fc880ac5050dddfb3c8062c2552b34c2e512eb4aa68f79/wrapt-1.11.2.tar.gz
Building wheels for collected packages: wrapt
  Building wheel for wrapt (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Alienware\\AppData\\Local\\Temp\\pip-install-4116x4uj\\wrapt\\setup.py'"'"'; __file__='"'"'C:\\Users\\Alienware\\AppData\\Local\\Temp\\pip-install-4116x4uj\\wrapt\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Alienware\AppData\Local\Temp\pip-wheel-yzv7oa9k' --python-tag cp36
       cwd: C:\Users\Alienware\AppData\Local\Temp\pip-install-4116x4uj\wrapt\
  Complete output (46 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.6
  creating build\lib.win-amd64-3.6\wrapt
  copying src\wrapt\decorators.py -> build\lib.win-amd64-3.6\wrapt
  copying src\wrapt\importer.py -> build\lib.win-amd64-3.6\wrapt
  copying src\wrapt\wrappers.py -> build\lib.win-amd64-3.6\wrapt
  copying src\wrapt\__init__.py -> build\lib.win-amd64-3.6\wrapt
  running build_ext
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "C:\Users\Alienware\AppData\Local\Temp\pip-install-4116x4uj\wrapt\setup.py", line 101, in <module>
      run_setup(with_extensions=True)
    File "C:\Users\Alienware\AppData\Local\Temp\pip-install-4116x4uj\wrapt\setup.py", line 71, in run_setup
      setup(**setup_kwargs_tmp)
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\core.py", line 148, in setup
      dist.run_commands()
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\dist.py", line 955, in run_commands
      self.run_command(cmd)
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\dist.py", line 974, in run_command
      cmd_obj.run()
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages\wheel\bdist_wheel.py", line 202, in run
      self.run_command('build')
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\dist.py", line 974, in run_command
      cmd_obj.run()
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\command\build.py", line 135, in run
      self.run_command(cmd_name)
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\dist.py", line 974, in run_command
      cmd_obj.run()
    File "C:\Users\Alienware\AppData\Local\Temp\pip-install-4116x4uj\wrapt\setup.py", line 25, in run
      build_ext.run(self)
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\command\build_ext.py", line 308, in run
      force=self.force)
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\ccompiler.py", line 1031, in new_compiler
      return klass(None, dry_run, force)
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\cygwinccompiler.py", line 285, in __init__
      CygwinCCompiler.__init__ (self, verbose, dry_run, force)
    File "c:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\distutils\cygwinccompiler.py", line 129, in __init__
      if self.ld_version >= "2.10.90":
  TypeError: '>=' not supported between instances of 'NoneType' and 'str'
  ----------------------------------------
  ERROR: Failed building wheel for wrapt
  Running setup.py clean for wrapt
Failed to build wrapt
Installing collected packages: wrapt
  Found existing installation: wrapt 1.10.11
ERROR: Cannot uninstall 'wrapt'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

A: I fixed the same error using
pip install wrapt --upgrade --ignore-installed

A: I fixed that problem by:
conda remove --yes wrapt

then :
pip install --upgrade tensorflow


text:
Q: conditional formatting of entire row from a cell's value in that particular row in Excel 2007 I have viewed the answer for a similar question. If I have several rules for a particular row, (e.g. if cell A2 is 1 then the row is red, if 2 then row is blue, if 3 then row is green, etc...). Having 40 rows and 5 coloring rules, I will have to create 200 rules that is not efficient in my view.
Can I use one rule for all 40 rows, rather than 5 rules for a row?

A: Sure.  Apply the rule to all 40 rows and use a formula like this for each rule:
=$A2=1

That should only require five rules.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bullets not showing in beamer I copied a presentation in which everything worked fine, and now in this new presentation there are no bullets showing on slide!
MWE:
\documentclass[xcolor=dvipsnames,hyperref={breaklinks=true},mathserif,professionalfont,12pt]{beamer}
\usecolortheme[named=RoyalBlue]{structure}
\useoutertheme{infolines}
\usetheme[height=7mm]{Rochester}
\setbeamertemplate{items}[ball]
\setbeamertemplate{blocks}[rounded][shadow=true]
\setbeamertemplate{navigation symbols}{}
%\usefonttheme{serif}
\usefonttheme{professionalfonts}

\usepackage{amsmath,amssymb,amsthm,amssymb}
\usepackage{mathtools}
\usepackage{bbm}
\usepackage{graphicx}
\usepackage{float}
\usepackage[croatian]{babel}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage{txfonts}
\usepackage{subfigure}
\usepackage{color}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{time}
\usepackage{extarrows}

\title{Random title}
\subtitle{Random subtitle}
\author{Random Randofsky}
\institute{Random institute, Random City 1000, Randomia}
\date{\today}

\begin{document}
\maketitle

\section{Random section1}

\begin{frame}
\frametitle{About}
\begin{itemize}
\item Random stuff Random stuff
\item \itshape{more random stuff}
\item Random stuff...
\end{itemize}
\end{frame}

\begin{frame}
\frametitle{Reference}
\begin{thebibliography}{99}
\end{thebibliography}
\end{frame}

\begin{frame}
\begin{center}
Thank you for listening\\

The End
\end{center}
\end{frame}

\end{document}

What seems to be the problem? I didn't change anything in the preamble.

A: EDIT: The problem based on the compilation. dingo_d uses dvipdfm. By changing to pdflatex everything works well.

I have no problem with your example.
Some packages of your header are obsolote. Have a look at this post:
How to keep up with packages and know which ones are obsolete?
You don't need to load color and xcolor together (In beamer the package will be load by default).
Maybe there is a problem with you versions. Here my file list:
 *File List*
  beamer.cls    2011/09/12 development version 3.12 A class for typesetting pre
sentations (rcs-revision 70f9d8411e54)
beamerbasercs.sty    2011/09/21 (rcs-revision 42a2c9debdc3)
beamerbasemodes.sty    2010/05/01 (rcs-revision efa082c6111d)
beamerbasedecode.sty    2010/05/01 (rcs-revision efa082c6111d)
   ifpdf.sty    2011/01/30 v2.3 Provides the ifpdf switch (HO)
beamerbaseoptions.sty    2010/04/27 (rcs-revision 982469101dd6)
  keyval.sty    1999/03/16 v1.13 key=value parser (DPC)
geometry.sty    2010/09/12 v5.6 Page Geometry
  ifvtex.sty    2010/03/01 v1.5 Switches for detecting VTeX and its modes (HO)
 ifxetex.sty    2010/09/12 v0.6 Provides ifxetex conditional
  size12.clo    2007/10/19 v1.4h Standard LaTeX file (size option)
 pgfcore.sty    2010/04/11 v2.10 (rcs-revision 1.7)
graphicx.sty    1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR)
graphics.sty    2009/02/05 v1.0o Standard LaTeX Graphics (DPC,SPQR)
    trig.sty    1999/03/16 v1.09 sin cos tan (DPC)
graphics.cfg    2010/04/23 v1.9 graphics configuration of TeX Live
  pdftex.def    2011/05/27 v0.06d Graphics/color for pdfTeX
infwarerr.sty    2010/04/08 v1.3 Providing info/warning/message (HO)
 ltxcmds.sty    2011/04/18 v1.20 LaTeX kernel commands for general use (HO)
  pgfsys.sty    2010/06/30 v2.10 (rcs-revision 1.37)
  pgfrcs.sty    2010/10/25 v2.10 (rcs-revision 1.24)
everyshi.sty    2001/05/15 v3.00 EveryShipout Package (MS)
  pgfrcs.code.tex
  pgfsys.code.tex
pgfsyssoftpath.code.tex    2008/07/18  (rcs-revision 1.7)
pgfsysprotocol.code.tex    2006/10/16  (rcs-revision 1.4)
  xcolor.sty    2007/01/21 v2.11 LaTeX color extensions (UK)
   color.cfg    2007/01/18 v1.5 color configuration of teTeX/TeXLive
dvipsnam.def    1999/02/16 v3.0i Driver-dependant file (DPC,SPQR)
 pgfcore.code.tex
 xxcolor.sty    2003/10/24 ver 0.1
hyperref.sty    2011/10/01 v6.82j Hypertext links for LaTeX
hobsub-hyperref.sty    2011/04/23 v1.4 Bundle oberdiek, subset hyperref (HO)
hobsub-generic.sty    2011/04/23 v1.4 Bundle oberdiek, subset generic (HO)
  hobsub.sty    2011/04/23 v1.4 Subsetting bundle oberdiek (HO)
ifluatex.sty    2010/03/01 v1.3 Provides the ifluatex switch (HO)
 intcalc.sty    2007/09/27 v1.1 Expandable integer calculations (HO)
etexcmds.sty    2011/02/16 v1.5 Prefix for e-TeX command names (HO)
kvsetkeys.sty    2011/04/07 v1.13 Key value parser (HO)
kvdefinekeys.sty    2011/04/07 v1.3 Defining keys (HO)
pdftexcmds.sty    2011/04/22 v0.16 Utilities of pdfTeX for LuaTeX (HO)
pdfescape.sty    2011/04/04 v1.12 Provides string conversions (HO)
bigintcalc.sty    2011/01/30 v1.2 Expandable big integer calculations (HO)
  bitset.sty    2011/01/30 v1.1 Data type bit set (HO)
uniquecounter.sty    2011/01/30 v1.2 Provides unlimited unique counter (HO)
letltxmacro.sty    2010/09/02 v1.4 Let assignment for LaTeX macros (HO)
 hopatch.sty    2011/01/30 v1.0 Wrapper for package hooks (HO)
xcolor-patch.sty    2011/01/30 xcolor patch
atveryend.sty    2011/04/23 v1.7 Hooks at very end of document (HO)
atbegshi.sty    2011/01/30 v1.15 At begin shipout hook (HO)
refcount.sty    2010/12/01 v3.2 Data extraction from references (HO)
 hycolor.sty    2011/01/30 v1.7 Color options of hyperref/bookmark (HO)
kvoptions.sty    2010/12/23 v3.10 Keyval support for LaTeX options (HO)
  pd1enc.def    2011/10/01 v6.82j Hyperref: PDFDocEncoding definition (HO)
hyperref.cfg    2002/06/06 v1.2 hyperref configuration of TeXLive
     url.sty    2006/04/12  ver 3.3  Verb mode for urls, etc.
 hpdftex.def    2011/10/01 v6.82j Hyperref driver for pdfTeX
rerunfilecheck.sty    2011/04/15 v1.7 Rerun checks for auxiliary files (HO)
beamerbaserequires.sty    2010/05/01  (rcs-revision efa082c6111d)
beamerbasecompatibility.sty    2010/07/12  (rcs-revision 6648c3177e4e)
beamerbasefont.sty    2010/10/26  (rcs-revision f39336aafb3c)
 amssymb.sty    2009/06/22 v3.00
amsfonts.sty    2009/06/22 v3.00 Basic AMSFonts support
beamerbasetranslator.sty    2010/06/11  (rcs-revision 85fd1cc7fc42)
translator.sty    2010/06/12 ver 1.10
translator-language-mappings.tex
beamerbasemisc.sty    2010/06/06  (rcs-revision bff0a9294b45)
beamerbasetwoscreens.sty    2010/05/01  (rcs-revision efa082c6111d)
beamerbaseoverlay.sty    2011/09/12  (rcs-revision 70f9d8411e54)
beamerbasetitle.sty    2010/09/21  (rcs-revision f0446ed0b6ae)
beamerbasesection.sty    2010/08/29  (rcs-revision e07e85b4cd4a)
beamerbaseframe.sty    2011/09/12  (rcs-revision 70f9d8411e54)
beamerbaseverbatim.sty    2011/09/12  (rcs-revision 70f9d8411e54)
beamerbaseframesize.sty    2011/09/12  (rcs-revision 70f9d8411e54)
beamerbaseframecomponents.sty    2011/09/12  (rcs-revision 70f9d8411e54)
beamerbasecolor.sty    2010/06/06  (rcs-revision d1a9b48be06d)
beamerbasenotes.sty    2010/05/01  (rcs-revision efa082c6111d)
beamerbasetoc.sty    2010/06/11  (rcs-revision 242ecaa6783b)
beamerbasetemplates.sty    2010/05/01  (rcs-revision efa082c6111d)
beamerbaseauxtemplates.sty    2010/05/01  (rcs-revision efa082c6111d)
beamerbaseboxes.sty    2010/05/01  (rcs-revision efa082c6111d)
beamerbaselocalstructure.sty    2010/09/19  (rcs-revision 9224c5f3ce70)
enumerate.sty    1999/03/05 v3.00 enumerate extensions (DPC)
beamerbasenavigation.sty    2010/05/01  (rcs-revision efa082c6111d)
beamerbasetheorems.sty    2010/06/06  (rcs-revision 7e7cc5e53e9d)
 amsmath.sty    2000/07/18 v2.13 AMS math features
 amstext.sty    2000/06/29 v2.01
  amsgen.sty    1999/11/30 v2.0
  amsbsy.sty    1999/11/29 v1.2d
  amsopn.sty    1999/12/14 v2.01 operator names
  amsthm.sty    2009/07/02 v2.20.1
beamerbasethemes.sty    2010/05/01  (rcs-revision efa082c6111d)
beamerthemedefault.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamerfontthemedefault.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamercolorthemedefault.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamerinnerthemedefault.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamerouterthemedefault.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamercolorthemestructure.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamerouterthemeinfolines.sty    2010/07/10  (rcs-revision 445340293dde)
beamerthemeRochester.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamerouterthemesidebar.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamerinnerthemerectangles.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamercolorthemewhale.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamercolorthemeorchid.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)
beamerfontthemeprofessionalfonts.sty    2010/06/17  (rcs-revision d02a7cf4d8ae)

mathtools.sty    2011/04/06 v1.11 mathematical typesetting tools
    calc.sty    2007/08/22 v4.3 Infix arithmetic (KKT,FJ)
 mhsetup.sty    2010/01/21 v1.2a programming setup (MH)
     bbm.sty    1999/03/15 V 1.2 provides fonts for set symbols - TH
   float.sty    2001/11/08 v1.3d Float enhancements (AL)
   babel.sty    2008/07/08 v3.8m The Babel package
croatian.ldf    2005/03/29 v1.3l Croatian support from the babel system
     ucs.sty    2004/10/17 UCS: Unicode input support
uni-global.def    2004/10/17 UCS: Unicode global data
inputenc.sty    2008/03/30 v1.1d Input encoding file
   utf8x.def    2004/10/17 UCS: Input encoding UTF-8
 txfonts.sty    2008/01/22 v3.2.1
subfigure.sty    2002/03/15 v2.1.5 subfigure package
subfigure.cfg
listings.sty    2007/02/22 1.4 (Carsten Heinz)
 lstmisc.sty    2007/02/22 1.4 (Carsten Heinz)
listings.cfg    2007/02/22 1.4 listings configuration
    time.sty
extarrows.sty    2008/05/15 v1.0b Some extensible arrows
 omltxmi.fd    2000/12/15 v3.1
 omstxsy.fd    2000/12/15 v3.1
 omxtxex.fd    2000/12/15 v3.1
  utxexa.fd    2000/12/15 v3.1
 ot1txss.fd    2000/12/15 v3.1
supp-pdf.mkii
epstopdf-base.sty    2010/02/09 v2.5 Base part for package epstopdf
  grfext.sty    2010/08/19 v1.1 Managing graphics extensions (HO)
epstopdf-sys.cfg    2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Live
 nameref.sty    2010/04/30 v2.40 Cross-referencing by name of section
gettitlestring.sty    2010/12/03 v1.4 Cleanup title references (HO)
    test.out
    test.out
translator-basic-dictionary-English.dict
translator-bibliography-dictionary-English.dict
translator-environment-dictionary-English.dict
translator-months-dictionary-English.dict
translator-numbers-dictionary-English.dict
translator-theorem-dictionary-English.dict
 ucsencs.def    2003/11/29 Fixes to fontencodings LGR, T3
 ***********

A: I had a similar problem using XeLaTex, and it turned out the reason was an incompatibility with the enumitem package.


text:
Q: IPhone Any Framework available to mimic Messages app I am planning to develop a free sms app which sends sms using APIs.
To make it easy to user, i want to use same look n feel like Messages App,
Any frameworks available for that?
I have downloaded many frameworks like
Acani
TwitterFon
Samsoffes https://github.com/samsoffes/ssmessagesviewcontroller
But none of them seems to be working
Any working framework available?
Thanks


text:
Q: Add controller to a Razor Component Library for .Net Core 3.1 I am migrating to MVC Core 3.1 and thankfully it wasn't that hard until I had to migrate the RCL.
Within the RCL I am including some common controllers and in order to use the Controller base class and IActionResult type I was using the Nuget Microsoft.AspNetCore.Mvc.Abstraction but it's only available for .net Core 2.2.
Why I cannot find the newer version 3.1 in the Nuget repository?
When I navigate to the definition of IActionResult I am shown a file with version 3.1.0 so I suppose there should be a way to reference that instead of 2.2.

A: The project was based on NetStandard2.0 and I manually changed that to netcoreapp3.1 plus adding the reference to Microsoft.AspNetCore.App.
<FrameworkReference Include="Microsoft.AspNetCore.App" />

To been able to use Controllers and any other feature of the MVC framework on 3.1

*

*Create a RCL project

*Edit the .csProj file and make the appropriate changes to look like that:

<Project Sdk="Microsoft.NET.Sdk.Razor">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RazorLangVersion>3.0</RazorLangVersion>
    <AddRazorSupportForMvc>true</AddRazorSupportForMvc>
  </PropertyGroup>
  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Components" Version="3.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="3.1.3" />
  </ItemGroup>
</Project>


text:
Q: Download pdf from href link issue I am working on a wordpress. I make a meta field for upload pdf file,pdf file upload sucessfully. Now i call meta value in href link for download the pdf file.But the problem is that it can open the file but not download.For this i search a code that is
<?php
header("Content-Disposition: attachment; filename=$event_flyer");
?>

$event_flyer is used for accessing meta value.
but its not working for specific href its just working for whole page on refresh.

A: If you want your pdf file to be downloadable by anyone who could browse your website just by clicking on links, then you can use the download attribute (for  tags) which allows you to specify the linked resource :
Doc here : http://www.w3schools.com/tags/att_a_download.asp

A: Actually if you have a reader installed it will always open instead of  downloading.
If you have hosted your wordpress on a live server then you can try to open link on a PC where PDF reader is not installed. It will download the file instead of opening.

A: You need more code, check this:
header("Content-disposition: attachment; filename=$pathtopdf");
header("Content-type: application/octet-stream");
readfile($pathtopdf);


text:
Q: Git .Net files to ignore What are your best practices for Git with .Net? What files do you ignore and do not add to your project type?

A: This is not really git-specific, but rather applies to any version control.
Ignore the bin and obj folders, and the .user and .suo files (which are user-specific). That is, of course, if you're using Visual Studio.

A: An initial list excludes all temporary build files,
*.dep *.aps *.vbw *.suo *.obj *.ncb *.plg *.bsc *.ilk
*.exp *.sbr *.opt *.pdb *.idb *.pch *.res *.user

Also the build directories
 *\obj
 *\bin
 *\Debug
 *\Release

if you use Rehsarper, exclude its directories too
 ./Resharp*

Plus some special files
 Thumbs.db

Some people also exclude binary files
 *.exe
 *.dll

It might be worthwhile considering what you want to store in your SCM, rather than a long and possibly never-complete list of exclusions.

A: I exclude all binary and source files that the Visual Studio doesn't need in order to rebuilt the application.
I'm not sure if all VS versions have the same file extensions, but you can experiment if you like.
Eric Sink has a guide for source control, Source Control HOWTO, and in Chapter 4: Repositories, you can read What can be stored in a repository? section, which is related to your question.

A: I don't use Git, but I do ignore files!
bin obj *.user *.suo *.log *.vbw *.pdb *mdf *ldf
_UpgradeReport* UpgradeLog* _ReSharper* *.resharper

A: I use this as a template for all my .net git repos: .gitignore Gist for .net


text:
Q: How can I host a WCF REST service at the service root address (without trailing slash)? I have a service hosted using wsHttpBinding on an address (the host base address is http://localhost/MyService).
In my contract (IMyService), I have:
    [OperationContract]
    [WebInvoke(
        Method = "GET",
        UriTemplate = "/")]
    Stream GetRootPage();

If I run my service and browse to http://localhost/MyService/, it works fine.  If I browse to http://localhost/MyService, I am greeted with a default WCF page indicating that the metadata publishing service is not enabled for this service.
I have tried various combinations of UriTemplate:

*

*UriTemplate = ""

*UriTemplate = "/"

*UriTemplate = "*"

In combination with the service base address:

*

*http://localhost/MyService

*http://localhost/MyService/
All of them yield the same behavior.  At some point previously, I could have sworn this was working, though I think I may have been using a subpath in the UriTemplate.  I know that if I have a UriTemplate of "/abc/123/", I can browse to /abc/123 (without the trailing slash) because WCF actually issues an HTTP 307 redirect automatically.
I am using .NET 4.0.

A: I figured out how to do this:
Ensure that the default WSDL generation is disabled (or at least not using the default URL):
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />

Ensure that the help URL is disabled:
<serviceDebug httpHelpPageEnabled="false" httpsHelpPageEnabled="false" />

A: I think your question is already answered in: Simple URL routes in WCF Rest 4.0 without trailing slash.
Can you verify that?


text:
Q: Why do I have to enter length of array while using "typeid"? I am learning c++11, and while I want to test typeid syntax , I don't understand that why do I have to enter length of array to recognize it ?
For example  :
 char name[9];
 if (typeid(name) == typeid(char []) // without length
     cout<<"Okay"<<endl;             // not print

 char name[9];
 if (typeid(name) == typeid(char [9]) // with length
     cout<<"Okay"<<endl;              // okay

But if I don't write length 9 it does not work and I have to enter length9. well, Why?
Therefore :
if (typeid(name) == typeid(char))       // only char wrong | ok | logical
if (typeid(name) == typeid(char *))     // by * wrong      | ok | logical
if (typeid(name) == typeid(char []))    // onle [] wrong   | don't understand
if (typeid(name) == typeid(char [9]))   // okay            | but why ?

I expect typeid(char[]) to work. In fact what is length of array for?

A: char[2] is something else than char[3]. They are totally separated types. The number of element is not just a parameter. It is part of the type itself.
You can consider the number of element as follow:
template <class T, size_t N>
class array{
public:
    T[N] data;
}

if you want to use this class,you should write:
array<int,6> foo;
array<int,7> bar;

At compile time array type will be converted to something like this:
array_int_6 foo;
array_int_7 bar;

It is obvious that array_int_6 != array_int_7. Thus leads to : typeid(foo) != typeid(bar) and typeid(array<int,6>) != typeid(array<int,7>)

A: The size of an array is part of its type.  A char[7] is not the same thing as a char[8].  We can demonstrate that with
void foo(char (&arr)[6]) {}

Now with that function we could only pass an array of the type char[6].  looking at this example you can see the compiler will complain for arrays that do not match the size specified in the function.


text:
Q: Why does my spinner GIF stop while jQuery ajax call is running? I'm just starting to wean myself from ASP.NET UpdatePanels. I'm using jQuery and jTemplates to bind the results of a web service to a grid, and everything works fine.
Here's the thing: I'm trying to show a spinner GIF while the table is being refreshed (à la UpdateProgress in ASP.NET) I've got it all working, except that the spinner is frozen. To see what's going on, I've tried moving the spinner out from the update progress div and out on the page where I can see it the whole time. It spins and spins until the refresh starts, and stays frozen until the refresh is done, and then starts spinning again. Not really what you want from a 'please wait' spinner!
This is in IE7 - haven't had a chance to test in other browsers yet. Any thoughts? Is the ajax call or the client-side databinding so resource-intensive that the browser is unable to tend to its animated GIFs?
Update
Here's the code that refreshes the grid. Not sure if this is synchronous or asynchronous.
updateConcessions = function(e) {
    $.ajax({
        type: "POST",
        url: "Concessions.aspx/GetConcessions",
        data: "{'Countries':'ga'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            applyTemplate(msg);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

applyTemplate = function(msg) {
    $('div#TemplateTarget').setTemplate($('div#TemplateSource').html());
    $('div#TemplateTarget').processTemplate(msg);
}

Update 2
I just checked the jQuery documentation and the $.ajax() method is asynchronous by default. Just for kicks I added this
$.ajax({
    async: true,
    ...

and it didn't make any difference.

A: I don't remember precisely what caused it, but we had a similar issue with IE6 in a busy box and we fixed it with this incredible hack in the Javascript:
setTimeout("document.images['BusyImage'].src=document.images['BusyImage'].src",10);

That just sets the image source to what it was before, but it is apparently enough to jostle IE out of its stupor.
edit: I think I remember what was causing this: We were loading the animation into a div with display: none. IE loads it and doesn't start the animation, because it's hidden. Unfortunately it doesn't start the animation when you set the containing block to display: block, so we used the above line of code to trick IE into reloading the image.

A: The image freezes because while it is hidden the animation is disabled by IE.
To fix this, append the loading image instead of unhiding it:
function showLoader(callback){
    $('#wherever').append(
        ''
    );

    callback();
}

function finishForm(){
    var passed = formValidate(document.forms.clientSupportReq);

    if(passed)
    {
        $('input#subm')
            .val('Uploading...')
            .attr('disabled','disabled');
        $('input#res').hide();
    }

    return passed;
}
$(function(){
    // on submit
    $('form#formid').submit(function(){
        var l = showLoader( function(){
                         finishForm()
                    });

        if(!l){
            $('.waiting').remove();
        }

        return l;
    });
});

A: Are you sure that its during the AJAX call that the GIF isn't spinning?
In your concessions.aspx place this line somewhere in the handling of GetConcessions:-
System.Threading.Thread.Sleep(5000);

I suspect that the gif spins for 5 seconds then freezes whilst IE renders and paints the result.

A: I know the question was regarding asynchronous ajax calls. However I wanted to add that I have found the following in my tests regarding synchronous ajax calls:
For Synchronous ajax calls. While the call is in progress (i.e. waiting for the server to respond). For the test i put a delay in the server response on the server.
Firefox 17.0.1 - animated gif continues to animate properly.
Chrome v23 - animated gif stops animation while the request is in progress.

A: It's not the Ajax call that's freezing the browser. It's the success handler (applyTemplate). Inserting HTML into a document like that can freeze IE, depending on how much HTML there is. It's because the IE UI is single threaded; if you notice, the actual IE menus are frozen too while this is happening.
As a test, try:
applyTemplate = function(msg) {
   return;
}

A: well, this is for many reasons. First at all, when the ajax call back of the server, you will sense a few miliseconds your gif frozen, but not many relevant. After you will start to process information, and depending of the objects that you manipulate and how you do it, you will have more o less time your gif frozen. This is because the thread is busy processing information. Example if you have 1000 objects and your do a order, and move information, and also you use jquery and append, insert, $.each commands, you will senses  a gif frozen. Sometimes it's imposible avoid all the frozen gifs, but yu can limit the time to a few miliseconds doing this: Make a list of response ajax, and process it each 2 seconds (with this you will have the results in a alone array and you wil call it with one setInterval and you avoid the bottle neck of try process one response when the before response is still processing). if you use JQuery don't use $.each, use for. Don't use dom manipulation (append,insert,etc..), use html(). In resume do less code, refactor, and procdess all the response (if you did more of 1) like only 1. Sorry for my english.

A: I had a similar problem with the browser freezing.  If you are developing and testing locally, for some reason it freezes the web browser. After uploading my code to a web server it started to work. I hope this helps, because it took me hours to figure it out for myself.

A: I have seen this behavior in the past when making AJAX calls. I believe this is related to the fact that browsers are only single threaded, so when the AJAX call is returned the thread is working on the call, so consequentially the animated GIF needs to stop momentarily.

A: dennismonsewicz's answer is greate. Use spin.js and the site http://fgnass.github.com/spin.js/ shows the step which is quite easy.
Under heavy process we should use CSS animations.
No JS driven animations and GIFs should be used becacuse of the single thread limit otherwise the animation will freeze. CSS animations are separated from the UI thread.

A: Are you doing a synchronous call or asynchronous call?  synchronous calls do cause the browser to seemingly lock up for the duration of the call.  The other possibility is that the system is very busy doing whatever work it is doing.

A: Wrapping ajax call in setTimeout function helped me to prevent freezing of gif-animation:
setTimeout(function() {
    $.get('/some_link', function (response) {
        // some actions
    });
}, 0);

A: Browsers are single-threaded and multi-threaded.
For any browser :
When you a called a function that contains a nested ajax function
java/servlet/jsp/Controller >
keep Thread.sleep(5000); in servlet to understand the async in ajax when
true or false.
    function ajaxFn(){
    $('#status').html('WAIT... ');
    $('#status').css("color","red");
    $.ajax({
        url:"MyServlet",
        method: "POST",
        data: { name: $("textarea").val(),
                id : $("input[type=text]").val() },
        //async: false,
        success:function(response){
            //alert(response);  //response is "welcome to.."
            $("#status").text(response);
            $('#status').css("color","green");
        },
        complete:function(x,y){
            //alert(y)
        },
        error:function(){
            $("#status").text("?");
        }
    });
}


text:
Q: Reach server via ssh tunnel and nginx proxy I'm new to nginx. I've inherited a fully functional and configured Ubuntu server with nginx and would like to tune it additionally to support a somewhat weird configuration, described below.
Basic info. My Ubuntu server (let's name it server.corp.com) runs in an internal corporate network. It hosts Gerrit and Jenkins, each of which has www-interface, listening on its own port (8081 and 8082), and nginx proxies requests to respective locations. For example requests to http://server.corp.com/gerrit are proxied to http://server.corp.com:8081
Unfortunately, I cannot show nginx config right now, since I am writing this question from home. I remember that it contains lines with proxy_pass clause.
Now, here comes that weird configuration.
server.corp.com, ports 80, 22 and 29418  <--> other Linux <--> Windows

Other Linux and Windows PC also belong to the corporation network (it's large). Other Linux can connect to my server on ports 80, 22 and 29418. Other ports are blocked by firewalls, which I cannot affect. Windows PC can connect to Other Linux with SSH, and probably other ports and protocols are available. I don't have neither login, nor superuser privileges on Other Linux.
My colleague, WindowsPC user, already successfully uses Putty and its SSH tunnel on port 29418 to connect to our Gerrit (which also listens on port 29418). The respective tunnel is localhost:29418 -> server.corp.com:29418.
My goal is to give my colleague access to www-interfaces of Gerrit and Jenkins at server.corp.com.
I can instruct him to establish one or several more SSH tunnels to my server.
However, I guess, it also requires some tuning of nginx, because simple SSH tunnel localhost:80 -> server:80 doesn't work. Chrome complained about SSL connection timeout on attempt to connect to localhost:80.
UPDATE2: I've tried to model this setup on my PC (Windows also) and use wget from Git distro. I've also created one more location for experiments.
Here is the relevant (I hope) part of nginx config
# file nginx.conf

include /etc/nginx/conf.d/*.conf;
# ...

# file conf.d/tunnel.conf
# This server clause is contained in conf.d/tunnel.conf
server {
    listen 80;
    server_name "localhost:1234" xxx.xxx.xxx.xxx;
    server_name_in_redirect off;

    location /gerrit2 {
        proxy_set_header  X-Forwarded-For $remote_addr;
        proxy_set_header  Host $http_host;
        proxy_pass   http://127.0.0.1:8081;
    }
}
# end of tunnel.conf

# again, file nginx.conf
server {
        listen 80 default;
        rewrite ^ http://server.corp.com$request_uri permanent;
}

server {
    listen 80;
    server_name server.corp.com;

    location ~ "^/$" {
        rewrite / /redmine;
    }

    location /gerrit/ {
        proxy_pass   http://localhost:8081;
        proxy_set_header  X-Forwarded-For $remote_addr;
        proxy_set_header  Host $http_host;
    }
}

The output from wget -d was the following:
$ wget -d http://localhost:1234/gerrit2
DEBUG output created by Wget 1.11.4 on Windows-MSVC.

--2015-11-12 11:20:51--  http://localhost:1234/gerrit2
Resolving localhost... seconds 0.00, 127.0.0.1
Caching localhost => 127.0.0.1
Connecting to localhost|127.0.0.1|:1234... seconds 0.00, connected.
Created socket 900.
Releasing 0x029773e8 (new refcount 1).

---request begin---
GET /gerrit2 HTTP/1.0
User-Agent: Wget/1.11.4
Accept: */*
Host: localhost:1234
Connection: Keep-Alive

---request end---
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.6 (Ubuntu)
Date: Thu, 12 Nov 2015 08:20:51 GMT
Content-Type: text/html
Content-Length: 193
Connection: keep-alive
Location: http://server.corp.com/gerrit2

---response end---
301 Moved Permanently
Registered socket 900 for persistent reuse.
Location: http://server.corp.com/gerrit2 [following]
Skipping 193 bytes of body: [
<title>301 Moved Permanently</title>

301 Moved Permanently

nginx/1.4.6 (Ubuntu)

] done.
--2015-11-12 11:20:51--  http://server.corp.com/gerrit2
Resolving server.corp.com... seconds 0.00, xxx.xxx.xxx.xxx
Caching server.corp.com => xxx.xxx.xxx.xxx
Connecting to server.corp.com|xxx.xxx.xxx.xxx|:80... seconds 0.00, connected.
Created socket 896.
Releasing 0x02977428 (new refcount 1).

---request begin---
GET /gerrit2 HTTP/1.0
User-Agent: Wget/1.11.4
Accept: */*
Host: server.corp.com
Connection: Keep-Alive

---request end---
HTTP request sent, awaiting response...
---response begin---
HTTP/1.1 404 Not Found
Server: nginx/1.4.6 (Ubuntu)
Date: Thu, 12 Nov 2015 08:20:51 GMT
Content-Type: text/html
Content-Length: 177
Connection: keep-alive

---response end---
404 Not Found
Disabling further reuse of socket 900.
Closed fd 900
Registered socket 896 for persistent reuse.
Skipping 177 bytes of body: [
<title>404 Not Found</title>

404 Not Found

nginx/1.4.6 (Ubuntu)

] done.
2015-11-12 11:20:51 ERROR 404: Not Found.

A: Found solution.
One needs to add to hosts
127.0.0.1 server.corp.com


text:
Q: How to use `profile.managed_images_allowed_for_urls` for chrome with selenium? I want to disable the loading of images in chrome, except for some URL which is needed to allow to load images.
After I googled and see the code, I found profile.managed_images_allowed_for_urls may be usable.
But I don't know how to use the option correctly.
The chromedriver's log show:
"prefs": {
               "profile.managed_default_content_settings.images": 2,
               "profile.managed_images_allowed_for_urls": "http://pic.example.com"
            }

My code with python selenium lib:
options = webdriver.ChromeOptions()

prefs = {
    'disk-cache-size': 4096,
    'profile.managed_default_content_settings.images':  2,
    'profile.managed_images_allowed_for_urls': 'http://pic.example.com'
}

options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=options, service_args=["--verbose", "--log-path=/tmp/chromedriver.log"])

I have tried managed_images_allowed_for_urls with value:
http://pic.example.com, pic.example.com, *. All of patterns is not work correctly.
I found some test code from test1
test2, and try to guess some useful info.
I also have tried to find a solution in code, but I cannot find where is handle the pattern. My c++ is poor :(


text:
Q: After using Vpython, couldn't connect to console process in Pycharm I am using Pycharm which worked perfectly well for over a couple of months. I recently used Vpython for an animation, which opened a new tab in the active Chrome video (with localhost:<port number> as the address) to run the animation when called. This all went well, but after having used it, whenever I try to open the console via pycharm, it doesn't work with the following error.
C:\Users\abc\AppData\Local\Programs\Python\Python36-32\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\pydevconsole.py" 62780 62781
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\pydevconsole.py", line 517, in <module>
    pydevconsole.start_server(host, int(port), int(client_port), client_host)
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\pydevconsole.py", line 338, in start_server
    interpreter = InterpreterInterface(client_host, client_port, threading.currentThread())
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\_pydev_bundle\pydev_ipython_console.py", line 24, in __init__
    self.interpreter = get_pydev_frontend(host, client_port)
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\_pydev_bundle\pydev_ipython_console_011.py", line 494, in get_pydev_frontend
    _PyDevFrontEndContainer._instance = _PyDevFrontEnd()
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\_pydev_bundle\pydev_ipython_console_011.py", line 326, in __init__
    self.ipython = PyDevTerminalInteractiveShell.instance()
  File "C:\Users\Thesatwik13\AppData\Local\Programs\Python\Python36-32\lib\site-packages\traitlets\config\configurable.py", line 412, in instance
    inst = cls(*args, **kwargs)
  File "C:\Users\Thesatwik13\AppData\Roaming\Python\Python36\site-packages\IPython\terminal\interactiveshell.py", line 430, in __init__
    super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
  File "C:\Users\Thesatwik13\AppData\Roaming\Python\Python36\site-packages\IPython\core\interactiveshell.py", line 516, in __init__
    self.init_completer()
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\_pydev_bundle\pydev_ipython_console_011.py", line 246, in init_completer
    self.Completer = self._new_completer_500()
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\_pydev_bundle\pydev_ipython_console_011.py", line 208, in _new_completer_500
    parent=self
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2017.3.2\helpers\pydev\_pydev_bundle\pydev_ipython_console_011.py", line 89, in __init__
    self.matchers.remove(self.python_matches)
ValueError: list.remove(x): x not in list
Process finished with exit code 1
Couldn't connect to console process.

I can run python via command prompt and from outside Pycharm. The chrome tab Vpython script runs perfectly well still.I tried restarting pycharm and the computer, but I actually have no clue about the problem here. I am using Windows 10.
PS: Went through multiple problems of this sort on this site. But non had a list.remove(x) x not in list type problem.

A: The problem is caused by IPython 6.3.0 version (ticket in PyCharm bug tracker: PY-29313). Either update PyCharm or IPython (6.3.1 works fine).


text:
Q: i want output in sql fromdate                 todate

1/5/2017                1/7/2017

1/5/2017                1/5/2017

1/5/2017                1/7/2017

1/5/2017                1/7/2017

1/5/2017                1/6/2017

by this syntax:- datediff(day,fromdate,todate)
I want output in this way:-
 0_days     1_days    2_days
1         1           3

A: use this query
select datediff(day, start_date, end_date) as days
from table1;

working exmaple here
above query would give the total days between start_date and end_date


text:
Q: Why is the SS(A|B) larger than SS(A) in anova analysis **Analysis 1**
Code: anova(lm(y~A+B))
Result:
Analysis of Variance Table

Response: y
              Df Sum Sq Mean Sq F value    Pr(>F)
          A   1  40.58  40.583  214.11 < 2.2e-16 ***
          B   4 171.31  42.829  225.96 < 2.2e-16 ***
Residuals       1994 377.94   0.190

**Analysis 2**
Code: anova(lm(y~B+A))
Result:
Analysis of Variance Table

Response: y
               Df Sum Sq Mean Sq F value    Pr(>F)
          B    4  87.10  21.774  114.88 < 2.2e-16 ***
          A    1 124.80 124.800  658.43 < 2.2e-16 ***
Residuals        1994 377.94   0.190

From analysis 1, SS(A) = 40.58, while from analysis 2, SS(A|B) = 124.80, which is larger than SS(A) from analysis 1. If I want to evaluate the effect of A after excluding the effect of B, I should use analysis 2. However, in analysis 2, I get a larger SS(A|B) and F value than SS(A) and F value obtained from analysis 1. From my understanding, SS(A|B) should always be smaller than SS(A) since the variance accounted by B has been taken away. This leads to the conclusion that after accounting for the effect of B, I get a more significant A effect, which makes me confused.

A: I screwed around in R and managed to get a similar phenomenon with the following code.
set.seed(0)
X = list()
X$a = rnorm(50)
X$y = rnorm(50)
X$b = with(X, 10*a + y) + rnorm(50)
anova(lm(y~a+b, X))
anova(lm(y~b+a, X))
X$lp = with(X, b - 10*a)
pairs(X)

Here's my read. There's one scenario in which A and B are correlated and correcting for B leaves less association between A and y. This is often taught and it seems to be what you had in mind. But, there's another possible scenario which seems to be applicable here: what if A and B are not very useful individually, but are very useful jointly? Then whatever gets added to the model second gives a big leap in the explanatory power of the model. You can see in the last line of code that the linear predictor $b-10a$ (lp) explains $y$ far better than $a$ or $b$ alone.
As Michael M notes, this example does not leave $a$ and $b$ dependent.


text:
Q: Php условие в echo Есть код
 $end_result     .= '
' . str_ireplace($word, $bold, $result) . '	'.$r['id_category'].'	'.$r['item_infinity'].'	'.$r['item_type'].'	'.$r['item_user'].'	'.$r['item_type'].'	'.$r['item_cost'].' руб.
';

Как создать внутри него условие? к примеру if ($r['id_category'] == 0) { что-то написать }
A: Это называется тернарный оператор.
echo $r['id_category'] == 0 ? 'ветка then' : 'ветка else';

A: Код будет читаемее, если вместо echo воспользоваться ф-ей printf() – у вас будет отдельно html темплейт, и в него, там где %s впечатаются соотв. значения.
%s – это место для текстовой строки, есть ещё варианты для чисел и пр. - смотрите документацию.
$tmpl = <<<EOF

        %s
        %s
        %s
        %s
        %s
        %s
        %s руб.

EOF;

$end_result .= sprintf(
    $tmpl,
    $r['id_item'],
    str_ireplace($word, $bold, $result),
    $r['id_category'] == 0 ? "на случай нуля" : $r['id_category'],
    $r['item_infinity'],
    $r['item_type'],
    $r['item_user'],
    $r['item_type'],
    $r['item_cost']
);

работающий пример


text:
Q: Sending keras model as an argument to external function in Python I want to send the Keras model after training to another python function which is saved in another python file? How can I send the model as an argument? Thank you.

A: If I understand it correctly, you want to transfer the model created in script A to script B so it can be used there.
To my experience, the easiest way of using a Keras model in a different script, is to save the model to disk as a file. As described here in the Keras docs:.
from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

Passing on the model to a different Python file (i.e. via a commandline argument), can be then be done by passing the filename of where you saved that model to the second script. This script can then load the model from disk and use it.
In case you only have 1 model at a time, you could pick a filename and hardcode it into your functions. For example:
Script A
# assuming you already have a model stored in 'model'
model.save('my_stored_model.h5')

Script B (which accesses the saved model)
from keras.models import load_model

def function_a():
    model = load_model('my_stored_model.h5')
    return model.predict(...)


text:
Q: How to solve $\int_{0}^{\beta}\frac{e^{ax-\frac{b}{x}}}{\alpha-x}dx$ I'm facing with this integral in my thesis. I have 'dejavu' that I have seen this kind of integral before but I can't remember exactly. Can anyone guide me to solve this one?
$$\int_0^\beta \frac{e^{ax-\frac{b}{x}}}{\alpha-x} \, dx$$


text:
Q: How to handle nested arrays in PHP (Laravel) I have a data in array format like this :
    Array
    (
        [0] => Array
            (
                [@attributes] => Array
                    (
                        [Domain] => domain1.com
                        [Available] => true
                        [ErrorNo] => 0
                        [Description] =>
                        [IsPremiumName] => false
                        [PremiumRegistrationPrice] => 0
                        [PremiumRenewalPrice] => 0
                        [PremiumRestorePrice] => 0
                        [PremiumTransferPrice] => 0
                        [IcannFee] => 0
                        [EapFee] => 0
                    )

            )

        [1] => Array
            (
                [@attributes] => Array
                    (
                        [Domain] => domain2.com
                        [Available] => true
                        [ErrorNo] => 0
                        [Description] =>
                        [IsPremiumName] => false
                        [PremiumRegistrationPrice] => 0
                        [PremiumRenewalPrice] => 0
                        [PremiumRestorePrice] => 0
                        [PremiumTransferPrice] => 0
                        [IcannFee] => 0
                        [EapFee] => 0
                    )

            )

        [2] => Array
            (
                [@attributes] => Array
                    (
                        [Domain] => domain3.com
                        [Available] => true
                        [ErrorNo] => 0
                        [Description] =>
                        [IsPremiumName] => false
                        [PremiumRegistrationPrice] => 0
                        [PremiumRenewalPrice] => 0
                        [PremiumRestorePrice] => 0
                        [PremiumTransferPrice] => 0
                        [IcannFee] => 0
                        [EapFee] => 0
                    )

            )
)

I want to use this data on my blade view in Laravel.
So I did this :
@foreach($results as $result => $datas)
                        @foreach($datas as $data => $attributes )
                            @foreach($attributes as $attribute => $value)

                                    @foreach($attribute["Domain"] as $domain)
                                    {{ $domain }}
                                    @endforeach
                                    .COM
                                    .NET
                                    .ORG

                            @endforeach
                        @endforeach
                    @endforeach

But when I use it like : {{ $attribute['Domain'] }} it says :

illegal string offset ...

And when I use it like : {{ $attribute->Domain }} it says

Trying to get property of non-object ...

I don't know what else should I try! please help me. thanks.
P.S: I know , It's not necessary to use four foreachs here. There should be a better way to do this.

A: If $results is a  provided array, then you can simplify your code to:
@foreach($results as $result)

        {{ $result['@attributes']['Domain'] }}
        .COM
        .NET
        .ORG

@endforeach


text:
Q: Problem build cordova app with cordova-plugin-qrscanner I have installed cordova-plugin-qrscanner in an (old) cordova application.
The installation works correctly but when I try to build the app for Android, the console outputs errors like those
[javac] Compiling 5 source files to C:\Users\christian.benseler\dev\testemob\platforms\android\ant-build\classes
    [javac] C:\Users\christian.benseler\dev\testemob\platforms\android\src\com\bitpay\cordova\qrscanner\QRScanner.java:27: error: package android.support.v4.app does not exist
    [javac] import android.support.v4.app.ActivityCompat;
    [javac]                              ^
    [javac] C:\Users\christian.benseler\dev\testemob\platforms\android\src\com\bitpay\cordova\qrscanner\QRScanner.java:356: error: cannot find symbol
    [javac]                     boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(cordova.getActivity(), permission);

it seems my android sdk is missing something, but I cannot figure out what. The readme from the repo does not specify anything about requirements, and I do not have full expertise in configuring Android/Java applications with its dependencies. Anyone can help me to find out what is missing in my environment?

A: Looks like the plugin is missing a dependency to android support v4, as that's the one that contains ActivityCompat class
https://developer.android.com/reference/android/support/v4/app/ActivityCompat


text:
Q: Create a customer from Devise User How can I create a customer class I want to be a Devise User with a role = 1.
I have my User model:
class User < ActiveRecord::Base
  enum role: [:user, :customer, :admin, :producer]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :user
  end

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable, :registerable
  devise :invitable, :database_authenticatable, :confirmable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

And my Customer model
class Customer < User

end

I can specify in the customersController what is a customer like this :
# GET /customers
def index
  @customers = Customer.where(:role => 1).page(params[:page])
end

But How can I modify my Customer model to self know he is a User with role = 1 so I can only get my Customers like this :
@customers = Customer.all

A: if you exactly need Customer.all you should looking for STI(single table inheritance) which already resolve what you trying to do


text:
Q: How to remove zero-width space characters  from the text I have text which contains the  Zero width joiner which is not visible in UI, But when I send it as an SMS, it shows as ? question mark in iPhone.
I have tried removing it by using gsub but its not getting removed.
text.gsub("&zwj\;", "")

Is there any way to remove such invisible character from the text?

Update:
In addition to @matt's answer
Unicode has the following zero-width characters:

*

*U+200B zero width space

*U+200C zero width non-joiner Unicode code point

*U+200D zero width joiner Unicode code point

*U+FEFF zero width no-break space Unicode code point

To replace them in a text, you can use a simple regex:
text = text.gsub(/[\u200B-\u200D\uFEFF]/, '')

A: The string  is the HTML character entity for the zero-width joiner. When a web browser sees it it will replace it with an actual zero-width joiner, but as far as Ruby is concerned it is just a 5 character string.
What you want to do is to specify the actual zero-width joiner character. It has the codepoint U+200D, so you can use it like this, using Ruby's Unicode escape:
text.gsub("\u200D", "")

This should remove the zero-width joiner characters, rather than looking for the string  which your original code was doing.

A: "blah blah blah".gsub(/[^[:print:]]/, '')

Should remove all non-printable characters.


text:
Q: Alfresco Custom Metadata Extractor I have developed a custom metadata extractor to extract detailed metadata for audio and video files. The extractor extends AbstractMappingMetadataExtracter and it needs to map extracted fields into a custom type. The extractor class is named AudioMetadataExtractor and a corresponding properties file contains the mappings. Following is the code for the class
public class AudioMetadataExtractor extends AbstractBaseMetadataExtractor {

public static ArrayList<String> SUPPORTED_MIMETYPES = addMimeTypes(new String[] { MimeTypes.MIMETYPE_MP3, MimeTypes.MIMETYPE_WMA });

public AudioMetadataExtractor() {
    this(SUPPORTED_MIMETYPES);
}

public AudioMetadataExtractor(ArrayList<String> supportedMimeTypes) {
    super(supportedMimeTypes);
}

@Override
protected Map<String, Serializable> extractRaw(ContentReader reader) throws Throwable {

    Map<String, Serializable> rawProperties = newRawMap();

    File file = TempFileProvider.createTempFile("DCM", "MINFO");
    reader.getContent(file);

    MediaInfoJNA mediaInfoLib = new MediaInfoJNA();
    mediaInfoLib.Open(file.getAbsolutePath());

    String album = mediaInfoLib.Get(StreamKind.General, 0, "Album", MediaInfoJNA.InfoKind.Text, MediaInfoJNA.InfoKind.Name);
    System.out.println("Album1 " + album);
    String title = mediaInfoLib.Get(StreamKind.General, 0, "Title", MediaInfoJNA.InfoKind.Text, MediaInfoJNA.InfoKind.Name);
    System.out.println("Title " + title);
    String duration = mediaInfoLib.Get(StreamKind.General, 0, "Duration", MediaInfoJNA.InfoKind.Text, MediaInfoJNA.InfoKind.Name);
    System.out.println("Duration " + duration);

    putRawValue("album", album, rawProperties);

    mediaInfoLib.Close();

    return rawProperties;
}
}

The configuration for the extractor is as follows
<bean id="metadata.extractor.AudioAsset" class="com.diipl.moviebeam.dcm.alfresco.metadata.AudioMetadataExtractor" parent="baseMetadataExtracter">
    <property name="inheritDefaultMapping">
        <value>true</value>
    </property>
</bean>

Problem: When uploading a new file the extractor is being called and I can see all the sysouts with correct values. However, the properties are not filled with any values. But if I run the "Extract Common Metadata" action on the file the extractor gets called and the fields get the correct values.


text:
Q: How to run a command from terminal so that it will be executed without tty? The situation: I have a bash script that is intended to run with cron. I tested the script on the terminal and it was running fine. As I configured the script to be executed by cron, the script started failing.
It took me a LOT of effort to find out that one of the commands in the script required TTY to run, which is not provided in the cron's execution environment. (For the curious: the command was docker-compose failing with the message the input device is not a TTY)
The question: I still would like to find a way to test my shell scripts from the terminal before configuring them for cron. Is there a way to run a shell script from a terminal so as if it is run by cron? Like cron run_my_command_now 'echo 123'. Or may be there is just a way to run a shell script from the terminal, so that the script thinks there is no terminal?

A: IMO the easiest way is probably to use ssh with '-T' to disable the pseudo TTY.
ssh -T localhost "command"

Should run it with no TTY.

A: See the at(1) man page.
at -f /path/to/script_or_command now +5 min
Or something similar to (EOT is Ctrl-D):
$ at 16:05
warning: commands will be executed using /bin/sh
at> source /my/environment/file
at> /path/to/script
at> <EOT>
job 1 at Mon Feb 14 16:05:00 2022


text:
Q: Owl carousel slider : If you keep the owl carousel slider on for a long time, it gets slower I made an owl carousel slider to float as a webview in an Android app.
The slider is composed of a general items and a video.
The general items are displayed for 6 seconds using autoplayTimeout option and the video is developed to be displayed for 3 seconds using javascript.
At first, the slide goes well for 6 seconds and 3 seconds respectively, but if you turn on the android app webview for a few hours, the sliding time exceeds 6 seconds and 3 seconds.
Below is the code I developed. I am not sure if it is a problem with the owl carousel slider infinite loop or the problem with the Android app webview. I'd appreciate it if you could let me know what could be the cause.
$(document).ready(function(){
    var owl = $('.owl-carousel');
    owl.owlCarousel({
        slideBy: 4,
        items: 4,
        loop:true,
        margin:0,
        autoplayTimeout:6000,
        autoplayHoverPause:false,
        autoWidth:true,
        onChanged: callBack
    });

    function callBack(event) {
        var slideBy = 4;
        var current = (event.item.index + 1) - event.relatedTarget._clones.length / 2;
        var allItems = event.item.count;
        if (current > allItems || current <= 0) {
            current = allItems - (current % allItems);
        }
        if (current > 1) {
            current = (current + (slideBy - 1)) / slideBy;
        }
        console.log("current : " + current);
        if (current==2) {
            console.log("inin!!");
            owl.trigger('stop.owl.autoplay');
            // setTimeout(() => {
            //  owl.trigger('next.owl.carousel');
            //  owl.trigger('play.owl.autoplay');
            // }, 3000);
            setTimeout(function(){
                owl.trigger('next.owl.carousel');
                owl.trigger('play.owl.autoplay');
            }, 3000);
        }

        owl.on('translate.owl.carousel', function (e) {
            $('.owl-item .item video').each(function (index, item) {
              // pause playing video - after sliding
              $(item).get(0).pause();
              $(item).get(0).currentTime = 0;
            });
        });

        owl.on('translated.owl.carousel', function (e) {
            // check: does the slide have a video?
            if ($('.owl-item.active').find('video').length !== 0) {
                // play video in active slide
                $('.owl-item.active .item video').get(0).play();
            }
        });
    }
});


text:
Q: Browsing multiple photos in flash for android I am trying to develop  an application for android phone using flash/as3, I want to know How to browse multiple photos from gallery using media promise or camera roll. Right now I am able to browse only one photo at a time.
       var mediaFile:CameraRoll = new CameraRoll();
       var imagePromise:MediaPromise;
       CameraRoll(mediaFile).browseForImage();

is there any code or resources that I can look at.

A: You have to create the "browser".
You have to read/write the camera roll files one at a time (how all systems work) but your app can save the images and file references and do whatever with the images - user can select multiple images.
Import a file from camera roll, convert to bitmap, manipulate in any way and push into an array.  If you're making a gallery, resize the bitmaps to thumbnail size. Your app should only stores the thumbnail bitmap in gpu, the original bmp is the camera roll file.
Here is an example of converting camera roll files to bmp: http://www.flashandmath.com/mobile/cameraroll/


text:
Q: glsl pass through geometry shader issue At this point I have a working vertex and fragment shader. If I remove my geometry shader completely, then I get the expected cube with colors at each vertex. But with the geometry shader added, no geometry shows up at all.
Vertex Shader:
#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;

out VertexData
{
    vec3 color;
} vertex;

uniform mat4 MVP;

void main(){

    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);
    vertex.color = vertexColor;
}

Geometry Shader:
#version 330

precision highp float;

in VertexData
{
    vec3 color;
} vertex[];

out vec3 fragmentColor;

layout (triangles) in;
layout (triangle_strip) out;
layout (max_vertices = 3) out;

void main(void)
{
    for (int i = 0; i > gl_in.length(); i++) {

        gl_Position = gl_in[i].gl_Position;
        fragmentColor = vertex[i].color;
        EmitVertex();
    }

    EndPrimitive();
}

Fragment Shader:
#version 330 core

in vec3 fragmentColor;

out vec3 color;

void main(){
    color = fragmentColor;
}

My graphics card supports OpenGL 3.3 from what I can tell. And, as I said. It works without the Geometry shader. As data, I am passing in two arrays of GLfloat's where each is a vertex or a vertex color respective.

A: for (int i = 0; i > gl_in.length(); i++)   //note the '>'

This loop condition will be false right from the start, so you won't ever emit any vertices. What you most probably meant is i < gl_in.length().


text:
Q: What is the difference between synchronous and asynchronous programming (in node.js) I've been reading nodebeginner
And I came across the following two pieces of code.
The first one:
    var result = database.query("SELECT * FROM hugetable");
    console.log("Hello World");

The second one:
    database.query("SELECT * FROM hugetable", function(rows) {
       var result = rows;
    });
    console.log("Hello World");

I get what they're supposed to do, they query the database to retrieve the answer to the query. And then console.log('Hello world').
The first one is supposedly synchronous code.
And the second one is asynchronous code.
The difference between the two pieces is very vague to me. What would the output be?
Googling on asynchronous programming didn't help me either.

A: The difference between these two approaches is as follows:
Synchronous way:
It waits for each operation to complete, after that only it executes the next operation.
For your query:
The console.log() command will not be executed until & unless the query has finished executing to get all the result from Database.
Asynchronous way:
It never waits for each operation to complete, rather it executes all operations in the first GO only. The result of each operation will be handled once the result is available.
For your query:
The console.log() command will be executed soon after the Database.Query() method. While the Database query runs in the background and loads the result once it is finished retrieving the data.
Use cases

*

*If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way.

*In Asynchronous way you can show some Progress indicator to the user while in background you can continue with your heavy weight works. This is an ideal scenario for GUI apps.

A: In the synchronous case, the console.log command is not executed until the SQL query has finished executing.
In the asynchronous case, the console.log command will be directly executed. The result of the query will then be stored by the "callback" function sometime afterwards.

A: The main difference is with asynchronous programming, you don't stop execution otherwise. You can continue executing other code while the 'request' is being made.

A: Asynchronous programming in JS:
Synchronous

*

*Stops execution of further code until this is done.

*Because it this stoppage of further execution, synchronous code is called 'blocking'. Blocking in the sense that no other code will be executed.

Asynchronous

*

*Execution of this is deferred to the event loop, this is a construct in a JS virtual machine which executes asynchronous functions (after the stack of synchronous functions is empty).

*Asynchronous code is called non blocking because it doesn't block further code from running.

Example:

// This function is synchronous
function log(arg) {
    console.log(arg)
}

log(1);

// This function is asynchronous
setTimeout(() => {
    console.log(2)
}, 0);

log(3)

*

*The example logs 1, 3, 2.

*2 is logged last because it is inside a asynchronous function which is executed after the stack is empty.

A: This would become a bit more clear if you add a line to both examples:
var result = database.query("SELECT * FROM hugetable");
console.log(result.length);
console.log("Hello World");

The second one:
database.query("SELECT * FROM hugetable", function(rows) {
   var result = rows;
   console.log(result.length);
});
console.log("Hello World");

Try running these, and you'll notice that the first (synchronous) example, the result.length will be printed out BEFORE the 'Hello World' line.
In the second (the asynchronous) example, the result.length will (most likely) be printed AFTER the "Hello World" line.
That's because in the second example, the database.query is run asynchronously in the background, and the script continues straightaway with the "Hello World". The console.log(result.length) is only executed when the database query has completed.

A: The difference is that in the first example, the program will block in the first line. The next line (console.log) will have to wait.
In the second example, the console.log will be executed WHILE the query is being processed. That is, the query will be processed in the background, while your program is doing other things, and once the query data is ready, you will do whatever you want with it.
So, in a nutshell: The first example will block, while the second won't.
The output of the following two examples:
// Example 1 - Synchronous (blocks)
var result = database.query("SELECT * FROM hugetable");
console.log("Query finished");
console.log("Next line");

// Example 2 - Asynchronous (doesn't block)
database.query("SELECT * FROM hugetable", function(result) {
    console.log("Query finished");
});
console.log("Next line");

Would be:

*

*Query finished
Next line

*Next line
Query finished
Note
While Node itself is single threaded, there are some task that can run in parallel. For example, File System operations occur in a different process.
That's why Node can do async operations: one thread is doing file system operations, while the main Node thread keeps executing your javascript code. In an event-driven server like Node, the file system thread notifies the main Node thread of certain events such as completion, failure, or progress, along with any data associated with that event (such as the result of a database query or an error message) and the main Node thread decides what to do with that data.
You can read more about this here: How the single threaded non blocking IO model works in Node.js

A: First, I realize I am late in answering this question.
Before discussing synchronous and asynchronous, let us briefly look at how programs run.
In the synchronous case, each statement completes before the next statement is run. In this case the program is evaluated exactly in order of the statements.
This is how asynchronous works in JavaScript. There are two parts in the JavaScript engine, one part that looks at the code and enqueues operations and another that processes the queue. The queue processing happens in one thread, that is why only one operation can happen at a time.
When an asynchronous operation (like the second database query) is seen, the code is parsed and the operation is put in the queue, but in this case a callback is registered to be run when this operation completes. The queue may have many operations in it already. The operation at the front of the queue is processed and removed from the queue. Once the operation for the database query is processed, the request is sent to the database and when complete the callback will be executed on completion. At this time, the queue processor having "handled" the operation moves on the next operation - in this case
    console.log("Hello World");

The database query is still being processed, but the console.log operation is at the front of the queue and gets processed. This being a synchronous operation gets executed right away resulting immediately in the output "Hello World". Some time later, the database operation completes, only then the callback registered with the query is called and processed, setting the value of the variable result to rows.
It is possible that one asynchronous operation will result in another asynchronous operation, this second operation will be put in the queue and when it comes to the front of the queue it will be processed. Calling the callback registered with an asynchronous operation is how JavaScript run time returns the outcome of the operation when it is done.
A simple method of knowing which JavaScript operation is asynchronous is to note if it requires a callback - the callback is the code that will get executed when the first operation is complete. In the two examples in the question, we can see only the second case has a callback, so it is the asynchronous operation of the two. It is not always the case because of the different styles of handling the outcome of an asynchronous operation.
To learn more, read about promises. Promises are another way in which the outcome of an asynchronous operation can be handled. The nice thing about promises is that the coding style feels more like synchronous code.
Many libraries like node 'fs', provide both synchronous and asynchronous styles for some operations. In cases where the operation does not take long and is not used a lot - as in the case of reading a config file - the synchronous style operation will result in code that is easier to read.

A: The function makes the second one asynchronous.
The first one forces the program to wait for each line to finish it's run before the next one can continue. The second one allows each line to run together (and independently) at once.
Languages and frameworks (js, node.js) that allow asynchronous or concurrency is great for things that require real time transmission (eg. chat, stock applications).

A: Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this case, the program is evaluated exactly in order of the statements and execution of the program is paused if one of the statements take a very long time.
Asynchronous functions usually accept a callback as a parameter and execution continue on the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).
Orginal Posted on Github: Link

A: Sync Programming
Programming languages like C, C#, Java are sync programming, what so ever you write will be execute in order of your writing.
-GET DATA FROM SQL.
//Suppose fetching data take 500 msec

-PERFORM SOME OTHER FUNCTION.
//Performing some function other will take 100 msec, but execution of other
//task start only when fetching of sql data done (i.e some other function
//can execute only after first in process job finishes).

-TOTAL TIME OF EXECUTION IS ALWAYS GREATER THAN (500 + 100 + processing time)
msec

Async
NodeJs comes up with async feature, it's non-blocking in nature, suppose in any I/O task which is taking time (fetching, writing, reading), nodejs won't kept idle and wait for the task to be finish, it'll start executing next tasks in the queue, and whenever that time taking task completed it will notify using callback.
Following example will help:
//Nodejs uses callback pattern to describe functions.
//Please read callback pattern to understand this example

//Suppose following function (I/O involved) took 500 msec
function timeConsumingFunction(params, callback){
  //GET DATA FROM SQL
  getDataFromSql(params, function(error, results){
    if(error){
      callback(error);
    }
    else{
      callback(null, results);
    }
  })
}

//Suppose following function is non-blocking and took 100 msec
function someOtherTask(){
  //some other task
  console.log('Some Task 1');
  console.log('Some Task 2');
}

console.log('Execution Start');

//Start With this function
timeConsumingFunction(params, function(error, results){
    if(error){
      console.log('Error')
    }
    else{
      console.log('Successfull');
    }
  })

//As (suppose) timeConsumingFunction took 500 msec,
//As NodeJs is non-blocking, rather than remain idle for 500 msec, it will start
//execute following function immediately
someOtherTask();

In Short, Output is as:
Execution Start
//Roughly after 105 msec (5 msec it'll take in processing)
Some Task 1
Some Task 2
//Roughly After 510 msec
Error/Successful //depends on success and failure of DB function execution

Difference is clear where sync will definitely take more than 600 (500 + 100 + processing time) msec, async saves time.


text:
Q: How to get all combinations of comma separated values in a T-SQL query I have table  with three columns: column 2 and 3 contains comma-separated values.
   -col1----col2---col3--
   | 1  |  1,2,3  | 4,5 |
   ----------------------

What is the most efficient way to  get a table of three columns that contains all the combinations of values of these three columns, like this:
1 | 1 | 4
1 | 2 | 4
1 | 3 | 4
1 | 1 | 5
1 | 2 | 5
1 | 3 | 5

A: Using query and nodes:
DECLARE @t TABLE (col1 VARCHAR(100), col2 VARCHAR(100), col3 VARCHAR(100))
INSERT @t VALUES ('1', '1,2,3', '4,5')

;WITH cte AS
(
    SELECT
        col1 = CAST('<x>' + REPLACE(col1, ',','</x><x>') + '</x>' AS XML),
        col2 = CAST('<x>' + REPLACE(col2, ',','</x><x>') + '</x>' AS XML),
        col3 = CAST('<x>' + REPLACE(col3, ',','</x><x>') + '</x>' AS XML)
    FROM @t
)
SELECT
    col1.n.query('.[1]').value('.', 'int'),
    col2.n.query('.[1]').value('.', 'int'),
    col3.n.query('.[1]').value('.', 'int')
FROM
    cte
CROSS APPLY col1.nodes('x') AS col1(n)
CROSS APPLY col2.nodes('x') AS col2(n)
CROSS APPLY col3.nodes('x') AS col3(n)

SQL Fiddle

A: Try this:
DECLARE @T1 TABLE (COL1 VARCHAR(25), COL2 VARCHAR(25), COL3 VARCHAR(25))

INSERT INTO @T1 (COL1,COL2,COL3)
VALUES ('1','1,2,3','4,5')

DECLARE @COL1 TABLE (VAL1 VARCHAR(25))
DECLARE @COL2 TABLE (VAL2 VARCHAR(25))
DECLARE @COL3 TABLE (VAL3 VARCHAR(25))

INSERT INTO @COL1 (VAL1)
SELECT DISTINCT Split.a.value('.', 'VARCHAR(max)') AS String
FROM  (SELECT CAST ('<M>' + REPLACE(CAST(COL1 AS VARCHAR), ',', '</M><M>') + '</M>' AS XML) AS String
       FROM @t1) AS A
CROSS APPLY String.nodes ('/M') AS Split(a)

INSERT INTO @COL2 (VAL2)
SELECT DISTINCT Split.a.value('.', 'VARCHAR(max)') AS String
FROM  (SELECT CAST ('<M>' + REPLACE(CAST(COL2 AS VARCHAR), ',', '</M><M>') + '</M>' AS XML) AS String
       FROM @t1) AS A
CROSS APPLY String.nodes ('/M') AS Split(a)

INSERT INTO @COL3 (VAL3)
SELECT DISTINCT Split.a.value('.', 'VARCHAR(max)') AS String
FROM  (SELECT CAST ('<M>' + REPLACE(CAST(COL3 AS VARCHAR), ',', '</M><M>') + '</M>' AS XML) AS String
       FROM @t1) AS A
CROSS APPLY String.nodes ('/M') AS Split(a)

SELECT *
FROM @COL1
CROSS APPLY @COL2
CROSS APPLY @COL3
ORDER BY VAL1,VAL2,VAL3


text:
Q: Bar Plot does not Display in Shiny App, I have developed a code I am new to the shiny app and trying to write simple code.
I changed the codes so many times but my bar chart doesn't work.
I have this problem in my other trying. That the UI works and also the codes in the server work part by part in R but not in the shiny app. I know some part of my server is not what I want, I just want to know what should I do to run the code which works in R but not in Shiny
#Graph 2
server<-#Graph 2
library("tidyverse")
library("leaflet")
library("leaflet.extras")
library("rnaturalearthdata")
library("sf")
library("DT")
library("ggplot2")

N <- read.csv("https://data.ontario.ca/dataset/f4112442-bdc8-45d2-be3c-12efae72fb27/resource/455fd63b-603d-4608-8216-7d8647f43350/download/conposcovidloc.csv")

function(input, output, session){

  if(input$data.Gender){

     City ="Ottawa"

     N %>% subset(Reporting_PHU_City == City) %>%
       select(Case_Reported_Date, Age_Group, Client_Gender, Outcome1)%>%
       rename(Date = Case_Reported_Date)%>%
       arrange(Age_Group, Client_Gender, Outcome1)

     Data.N <- as.data.frame(N)
     Data.N %>%
       group_by(Age_Group) %>%
       summarise(Age = n_distinct(Age_Group)) %>%
       arrange(desc(Age))

     w = table(N$Age_Group)

     t = as.data.frame(w)

 }

 output$Plot <- renderPlot({

       ggplot() +
         geom_bar(stat = "identity",data = t,mapping = aes(x = N$Client_Gender , y =Freq))

 })

}

A: Sorry, the site didn't let me share the UI too. This is Ui
UI<- #Graph 2

library("leaflet")
library("DT")

fluidPage(
  sidebarLayout(
    sidebarPanel(
      radioButtons("data.Gender", "",
                   c("Data female" = "Gender.Female",
                     "Data male" = "Gender.Male"))
    ),

    enter code here
      mainPanel(
        plotOutput("Plot")
      )
  ))

A: Perhaps you should group by Client_Gender.  Your present group by of Age_Group will give 1 as the value for all groups.
Try this
server <- function(input, output, session){

 t <- reactive({
    input$data.Gender

    City ="Toronto"

    aa <- N %>% subset(Reporting_PHU_City == City) %>%
      select(Case_Reported_Date, Age_Group, Client_Gender, Outcome1)%>%
      rename(Date = Case_Reported_Date)%>%
      arrange(Age_Group, Client_Gender, Outcome1)

    bb <- aa %>%
      group_by(Client_Gender) %>%
      summarise(Age = n_distinct(Age_Group)) %>%
      arrange(desc(Age))

    bb
  })

  output$Plot <- renderPlot({

    ggplot(data=t()) +
      geom_bar(stat = "identity",mapping = aes(x = Client_Gender , y = Age))

  })

}


text:
Q: Javascript fine grain performance tweaking I have been writing my first jQuery plugin and struggling to find a means to time how long different pieces of code take to run.
I can use firebug and console.time/profile. However, it seems that because my code executes so fast I get no results with profile and with time it spits out 0ms. (Firebug profiling issue: "no activity to profile")
Is there a way to get the time at a greater level of detail that milliseconds in javascript?
UPDATE: I've put code that I want to test in a loop that loops it a million times, but it's not an ideal solution.

A: You need to run your tests a number of times and then calculate how many operations per second are executed.
The easiest way to create such a test case is to use the jsPerf website. It will generate a test case like this: http://jsperf.com/prime-numbers

A: var startTime = new Date();
// do something
var totalTime = new Date() - startTime;
alert(totalTime);

A: It sounds a bit weird but: Buy a really old computer. A Pentium 2 would do nicely. It is not an expensive solution and you get to dedicate a whole machine to your perfectionism. It's lovely seeing the scripts run and build up the page elements slow enough to see it.


text:
Q: How to best automate deployment of NPM-dependent project? I'm used to deploy code depending on Composer (PHP's NPM cousing), that sports .json and .lock files. The first one describes the package and your version constraints, and the second one lists exactly what was installed. Always there's a lock file and you run composer install you're sure to receive the same set of packages; running composer update will re-read the json file, install new versions, and update the lock file.
That's awesome for production deployment, since you don't need to checkout your dependencies to your versioning system and you're sure to have the exact same set of dependencies in production as you have in development.
My question is: how to best automate deployment of NPM-dependent code? Is it possible to achieve a method similar to Composer? I've noticed that npm install only installs what's first available in the package.json file. After the first run, i.e. if you change a version constraint you must manually npm update that package - and that would render automate deployment useless, as there's no way to check in to versioning "update this package here to a new version"...

A: npm shrinkwrap is a analog of composer.lock file. It will generate a npm-shrinkwrap.json, that have all deps with version in it, so you can use it to deploy to production env. Also you can try a various libs from npm to lock versions or search for updates of it without changing packages.json.


text:
Q: How do I post my Javascript to a page? This website...
http://doctorjs.org/

Says I have to post my javascript to:
http://doctorjs.org/analyze

How on Earth do I do that?

A: Pete,
It looks like that page expects a post request. therefore, you have to read the instructions on the page (http://doctorjs.org/) :). it says in the page to post it to here:
direct quote:
Just POST to http://doctorjs.org/analyze with the src field set to your source
code, and the doctor will give you an analysis in JSON. Try it out!
http://doctorjs.org/try.html
lol - give it a 'proper' try on the try.html page. good luck


text:
Q: (UE4)Check if a point lies in a collision circle is there an easy way to check if a point lies in a collision circle of other actors in the world? I am working on a project where my actor would move to a certain location and i want to check if i would get a collision even before my actor is moving.

A: If the distance between the two objects is less than the collision radius, the objects would "collide". Unless you have other criteria?


text:
Q: Get json object without JSON.parse? I found this:
Use Python output:
print 'Content-type: text/x-json\n\n'
print json.dumps([{'title':arr['title']}])

and get json string with Jquery:
$ajax(
   success: function(msg){
      if(msg[0].title) alert(msg[0].title);
   }
)

It works, who can tell me why it is? Thanks~

A: jQuery calls JSON.parse internally on modern browsers that have it if the Content-Type is json
        return window.JSON && window.JSON.parse ?
            window.JSON.parse( data ) :
            (new Function("return " + data))();

A: I believe jQuery is able to determine the response type based on the header you are sending and automatically evaluate it as JSON.

A: If you set the dataType to "json" or you don't set it and the content-type header contains the string "json", it tries to parse it, you can see the logic at work here:
if ( typeof data === "string" ) {
  // Get the JavaScript object, if JSON is used.
  if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
    data = jQuery.parseJSON( data );

  // If the type is "script", eval it in global context
  } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
    jQuery.globalEval( data );
  }
}

If you're curious, the source for jQuery.parseJSON() is here.


text:
Q: Best practices for creating a CSV file? I am working in Swift although perhaps the language is not as relevant, and I am creating a relatively simple CSV file.
I wanted to ask for some recommendations in creating the files, in particular:

*

*Should I wrap each column/value in single or double quotes? Or nothing? I understand if I use quotes I'll need to escape them appropriately in case the text in my file legitimately has those values. Same for \r\n

*Is it ok to end each line with \r\n ? Anything specific to Mac vs. Windows I need to think about?

*What encoding should I use? I'd like to make sure my csv file can be read by most readers (so on mobile devices, mac, windows, etc.)

Any other recommendations / tips to make sure the quality of my CSV is ideal for most readers?

A: I have a couple of apps that create CSV files.
Any column value that contains a newline or the field separator must be enclosed in quotes (double quotes is common, single quotes less so).
I end lines with just \n.
You may wish to give the user some options when creating the CSV file. Let them choose the field separator. While the comma is common, a tab is also common. You can also use a semi-colon, space, or other characters. Just be sure to properly quote values that contain the chosen field separator.
Using UTF-8 encoding is arguably the best choice for encoding the file. It lets you support all Unicode characters and just about any tool that supports CSV can handled UTF-8. It avoid any issues with platform specific encodings. But again, depending on the needs of your users, you may wish to give them the choice of encoding.


text:
Q: Variable with two user inputs rentalPeriod = input("Number of Weeks Rented:\n")

I need some help with using one variable and two user inputs and then to print out the rentalPeriod using the two variables with a logical operator using or. With the second string "Number of Days Rented:\n as the second input

A: This can be an option:
var1, var2 = input("Enter two numbers here: ").split()

or you can do the following:
var1, var2 = input('Two numbers please (with a comma in between): ').split(',')


text:
Q: Call Django template tag with userinput I want to use a Django custom template tag for checking whether the user id is in the database or not. We already created a custom template tag which works so far, but I can't get it to work with the form.
Goal is to not refresh the entire page but just show the result of this query. How is it possible to achieve this?
HTML Form:
<form role="form" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text">
    <button>Check Me</button>
</form>

{{ test|testid:123 }} <!-- Works, shows True or False -->

Filter:
@register.filter
def testid(value, test_id):
    if Test.objects.filter(id=test_id).exists():
        return True
    return False

I tried to look this up, but it seems that most of the people do this by implementing iQuery, just using forms or something similar and I'm trying to avoid this and wanted to use the template tag for this.

A: Django is a back-end system only. Its involvement ends at the html template layer, i.e. it does not provide anything real-time. By default, all interactions involve a round-trip to the server, i.e. a page refresh. That doesn't mean you can't do real-time Ajax interactions in a Django project, only that Django isn't going to help you there and you're not going to find anything to help in the Django docs.
It requires a lot more work to produce these results without a page refresh. In most cases, I think people are overly enamored of accomplishing that goal. You're going to need to set up a receiving view, write javascript or jquery to post to the receiving view, save the data in the receiving view, and also write js to update the page in real time assuming that the back-end save went well. All possible and we've all done it, but do consider whether it's worth it.
If it's an absolute requirement, dig in, because it's going to require a fair bit of custom code and tooling.


text:
Q: How can i get my loop to start from "Day 1"? So I'm trying to make a list starting from day one and moving onward, however every time i run the code it starts from the days the user inputs. It's probably an easy fix but I'm stumped. Any help would be appreciated!
orig = int(input("Enter the starting number of organisms: "))
days = int(input("Enter the number of days: "))
increase = float(input("Enter the daily population increase: "))
for i in range(days):
    orig = orig * (1 + increase)
    days = days + 1
    print(f'After {days} days there are {orig:.6f} organisms')

A: days = int(input("Enter the number of days: "))
increase = float(input("Enter the daily population increase: "))
for i in range(days):
    orig = orig * (1 + increase)
    days = days + 1
    print(f'After {i+1} days there are {orig:.6f} organisms')

A: then why not using i as the day counter:
orig = int(input("Enter the starting number of organisms: "))
days = int(input("Enter the number of days: "))
increase = float(input("Enter the daily population increase: "))
for i in range(days):
    orig = orig * (1 + increase)
    print(f'After {i+1} days there are {orig:.6f} organisms')

A: Changed code to track day number
orig = int(input("Enter the starting number of organisms: "))
days = int(input("Enter the number of days: "))
increase = float(input("Enter the daily population increase: "))
for i in range(days): # will take  on the values 0 to days -1
    orig = orig * (1 + increase)
    day_number = i + 1 # create a day number which will have the value 1 to days
    print(f'After {day_number} days there are {orig:.6f} organisms')

Trial run
Enter the starting number of organisms: 5
Enter the number of days: 5
Enter the daily population increase: .5
After 1 days there are 7.500000 organisms
After 2 days there are 11.250000 organisms
After 3 days there are 16.875000 organisms
After 4 days there are 25.312500 organisms
After 5 days there are 37.968750 organisms

A: You are forgetting to use i which is increasing in the way you would want days to increase:
orig = int(input("Enter the starting number of organisms: "))
days = int(input("Enter the number of days: "))
increase = float(input("Enter the daily population increase: "))

# Starting the range from 1 makes more sense
for i in range(1, days+1):
    orig *= (1 + increase)
    print(f'After {i} days there are {orig:.6f} organisms')

Enter the starting number of organisms: 1
Enter the number of days: 5
Enter the daily population increase: 1
After 1 days there are 2.000000 organisms
After 2 days there are 4.000000 organisms
After 3 days there are 8.000000 organisms
After 4 days there are 16.000000 organisms
After 5 days there are 32.000000 organisms


text:
Q: How to make operation atomic while inserting in mysql using perl script I have a perl script that places order for customer.
2 tables.
table_orders - orderic, customerid, orderdatetime
table_order_details - orderid, productname, Quantity, MRP. Sellprice

Steps to insert into table:
1. insert in table_orders.
2. for each product in shopping cart insert into table_order_details

Now problem is after insert in first table,
1. It is possible because of some error in input data insertion in second table is not possible and perl returns an error.
2. Few entries done in table 2 too, but now got the error so further entry not possible in table 2 and perl returns an error.

In both the cases transaction is not completed successfully, so how to revert back the entries in DB that was done before error occurred?
Is there any perl or MYSQl wat to do this or we need to handle it manually??

A: Use transactions.
Transactions allow you to isolate changes to the database until you're done making all the changes. Nobody else can see those changes and nobody else can change those rows while you're working in your transaction. Then you commit the transaction and everyone else can see your changes all at once. If there's an error, you can rollback all the changes you made in your transaction.
In Perl, using DBI, the default is to not use transactions. Every statement is automatically committed. It is a very good idea to always turn transactions on.  You typically do this when connecting to the database by setting AutoCommit off. You'll also want to turn on RaiseError so database errors will happen automatically, you don't have to write or die... everywhere. Then, since you don't want to see errors twice, turn PrintError off.
my $dbh = DBI->connect(
    'dbi:mysql:...', $user, $pass,
    { AutoCommit => 0, RaiseError => 1, PrintError => 0 }
);

Now everything you do will be in a transaction and nothing you do will be visible to anyone else until you run $dbh->commit.  Wrap all the work in an eval block to catch any errors thrown now that RaiseError is on.  If you get an error, $dbh->rollback will throw out any partial work.
eval {
    my $insert_table_orders_sth = $dbh->prepare(
        "INSERT INTO table_orders (...) VALUES (?, ?, ?)"
    );
    $insert_table_orders_sth->execute(@table_orders_values);

    my $insert_table_orders_details_sth = $dbh->prepare(
        "INSERT INTO table_orders_details (...) VALUES (?, ?, ?)"
    );
    for my $product ($cart->products) {
        $insert_table_orders_details_sth->execute($product->values);
    }

    # All done, make the changes visible to everyone else.
    $dbh->commit;
};
if($@) {
    warn "There was a database error: $@";

    # Wipe out anything you did above.
    eval { $dbh->rollback };

    # Do whatever else you might need to cleanup the error.
}