text:
Q: JPanel disappearing from window The SSCCE below is a class that extends JPanel. The JPanel is the basic outline of a calendar (I've stripped it way down for simplicity's sake), and it consists of JButton components, a JLabel, and a JTable. When I add this frame to a window (i.e. JDialog), it appears as normal. However, when I add another component with it, it disappears. Why is this happening, and how can I make this not happen?
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;

public class CalendarPanel extends JPanel {

    private static JDialog dialog = new JDialog();

    public static void main(String[] args) {

    setDialogProperties();
    addComponentsToDialog();
    dialog.setVisible(true);
    }

    private static void setDialogProperties() {
    dialog.setModal(true);
    dialog.setResizable(false);
    dialog.setSize(new Dimension(330, 400));
    dialog.setDefaultCloseOperation(2);
    dialog.setLocationRelativeTo(null);
    }

    private static void addComponentsToDialog() {
    CalendarPanel calendar = new CalendarPanel();
    JPanel panel = new JPanel();
    panel.add(calendar);

    dialog.add(panel);
    //dialog.add(new JLabel("Hello"));
    }

    private static final long serialVersionUID = 1L;
    private JLabel lblMonth;
    private JButton btnPrev, btnNext;
    private JTable tblCalendar;
    private DefaultTableModel mtblCalendar;
    private JScrollPane stblCalendar;
    private static GridBagLayout gridBag = new GridBagLayout();
    private GridBagConstraints constraints = new GridBagConstraints();

    public CalendarPanel() {

    super(gridBag);

    createControls();
    addControlsToPanel();
    addHeaders();
    setTableProperties();
    }

    private void createControls() {
    lblMonth = new JLabel("January");
    btnPrev = new JButton("<");
    btnNext = new JButton(">");
    mtblCalendar = new DefaultTableModel() {

        public boolean isCellEditable(int rowIndex, int mColIndex) {
        return false;
        }
    };
    tblCalendar = new JTable(mtblCalendar);
    stblCalendar = new JScrollPane(tblCalendar);
    stblCalendar.setPreferredSize(new Dimension(300, 247));
    }

    private void addControlsToPanel() {
    GridBagLayout topGridBag = new GridBagLayout();

    JPanel topPanel = new JPanel(topGridBag);

    JPanel labelPanel = new JPanel();
    labelPanel.add(lblMonth);
    labelPanel.setPreferredSize(new Dimension(180, 20));

    constraints.gridx = 1;
    topGridBag.setConstraints(labelPanel, constraints);

    constraints.gridx = 2;
    topGridBag.setConstraints(btnNext, constraints);

    topPanel.add(btnPrev);
    topPanel.add(labelPanel);
    topPanel.add(btnNext);

    gridBag.setConstraints(topPanel, constraints);

    constraints.gridy = 1;
    gridBag.setConstraints(stblCalendar, constraints);

    this.add(topPanel);
    this.add(stblCalendar);
    }

    private void addHeaders() {
    String[] headers = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
    for (int i = 0; i < 7; i++) {
        mtblCalendar.addColumn(headers[i]);
    }
    }

    private void setTableProperties() {
    tblCalendar.getTableHeader().setReorderingAllowed(false);

    tblCalendar.setRowHeight(38);
    mtblCalendar.setColumnCount(7);
    mtblCalendar.setRowCount(6);
    }
}

A: JDialogs and all top-level windows use BorderLayout by default. When you add a component to it (actually its contentPane) without specifying the position, you add it to the BorderLayout.CENTER position by default. You are covering up the previously added component whenever you add a new one. You will want to learn about the layouts available for your use and then use them to their best advantage.
e.g.,
  dialog.add(panel);
  dialog.add(new JLabel("Hello", SwingConstants.CENTER), BorderLayout.SOUTH);
}

Next you'll want to avoid setting the sizes of anything and to be sure to pack() your top level windows that allow this.


text:
Q: Android-Cant create order using woocommerce api Cant create order using WooCommerce API
The android code (okhttp) is
RequestBody formBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart(oauthConsumerKeyString, oauthConsumerKeyStringValue)
        .addFormDataPart(oauthNonceKeyString, oauthNonceKeyValue)
        .addFormDataPart(oauthSignatureMethodKey, oauthSignatureMethodKeyValue)
        .addFormDataPart(oauthTimestampKeyString, oauthTimeStampKeyStringValue)
        .addFormDataPart("oauth_signature", signature)
        .addFormDataPart("orders", postDataString)
        .build();
Request request = new Request.Builder()
        .url(urlOrders)
        .post(formBody)
        .build();

Notice the part of
addFormDataPart("orders", postDataString).

If this part is removed then the order is created without details like address, userinfo, price, product id and the like. So all the parameters are working all right.
Now when the above part is not omitted, the order does not get created and error is shown as:
Invalid signature - provided signature does not match.

The variable postDataString contains the following JSON data
{
    "payment_method": "bacs",
    "payment_method_title": "Direct Bank Transfer",
    "set_paid": true,
    "billing": {
        "first_name": "John",
        "last_name": "Doe",
        "address_1": "969 Market",
        "address_2": "",
        "city": "San Francisco",
        "state": "CA",
        "postcode": "94103",
        "country": "US",
        "email": "john.doe@example.com",
        "phone": "(555) 555-5555"
    },
    "shipping": {
        "first_name": "John",
        "last_name": "Doe",
        "address_1": "969 Market",
        "address_2": "",
        "city": "San Francisco",
        "state": "CA",
        "postcode": "94103",
        "country": "US"
    },
    "line_items": [
        {
            "product_id": "341",
            "quantity": "1"
        },
        {
            "product_id": "339",
            "quantity": "1"
        }
    ],
    "shipping_lines": {
        "method_id": "flat_rate",
        "method_title": "Flat Rate",
        "total": 10
    }
}

What is wrong with this code.
Thanks for your time.
If any doubt please comment.

A: Am writing this answer.
Note:- As of now,have seen many questions like this are on stackoverflow and no answer is provided.Many have earned tumbleweed.:)
Lets create a coupon resource.
The below method is the same whether it is for creating coupon or orders.Taking coupon as an example as it has a short json parameter.
The coupon json to be posted is
{"code":"asdfas"}

The minimum parameter for creating a coupon resource is the "code" parameter.Other parameters are optional.So am using the minimum json possible to create a coupon.
The url should be as
http://pro.....epo.net/scoop/wp-json/wc/v2/coupons?oauth_consumer_key=ck_2f53925cb6d2c8.....f118d01ed80e&oauth_timestamp=1492154063&oauth_nonce=JqYIfq&oauth_signature_method=HMAC-SHA1&oauth_signature=FC1lJ8Vzw.....B86UGlAoWA=
Many of you who can list resources can also presumbly create correct signatures.So not documenting the signature creation here.Can look to the many other resources out there.
Now getting json media type
MediaType JSON = MediaType.parse("application/json; charset=utf-8");

Now the final code (Am using okhttp3)
okhttp3.RequestBody body = RequestBody.create(JSON, dataCouponJsonObject.toString());
okhttp3.Request request = new okhttp3.Request.Builder().url(the url given above)
                .post(body)
                .build();
response = client.newCall(request).execute();

And then voila! resources are created :)
Note: 2 days gone and then arrived at this answer.
If any doubt please comment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: th:field parameter syntax using Thymeleaf in Spring I've always seen th:field used like this:
<form th:object="${bla}" method="POST">
   <div>
       <label for="bla"> </label>
       <input type="text" th:field="*{blabla}">
       <input type="submit" value="Search">
   </div>
</form>

but is it possible, in the case I had to search by 2 different fields, to do something like:
th:field="{blabla, thebla}"

A: Quick answer : No it doesn't permit such a behavior AFAIK.
Check the Official doc
A workaround: Your can always send one value with separators..


text:
Q: How can I listen for the drag/drop event in CKeditor? I'm building an application that requires the user to drag and drop html elements onto a CKeditor instance. I need to listen for the drop event so I can take action to remove the element that was dropped onto the editor. I see that there's a 'paste' event, but it's not triggered by the drop.
Here's my simple test, using the CKeditor jquery adapter:
// set up instance
$('#editor1').ckeditor();
var editor = $('#editor1').ckeditorGet();

// this gets a list of all events that you can listen for
console.log(editor._.events);

// here's how you listen for an event
editor.on("someEvent", function(e) {
  console.log(e);
});

I can't find anything in the documentation to shed light on this.
Any ideas?

A: See http://dev.ckeditor.com/ticket/5692

A: If possible, assign a unique attribute to the items you're dropping into the editor, then listen for selectionChange
editor.on('selectionChange', hookNewObjects);

Keep a register of all the objects you've already dropped and take action on new ones only.
You can access the recently dragged element using
ev.editor.getSelection().getStartElement().$


text:
Q: Compilation of pure LaTeX (or beamer) with Pandoc lasts for over 30 min I am using WSL 2 (Ubuntu 20.04) and Windows Terminal setting to compile markdown file into the beamer presentation. Unfortunately if I am trying to use pandoc 2.5 to compile it, the time of compilation lasts over 30 min (doesn't matter if it is by pdfLaTeX, XeLaTeX or LuaLaTeX). During compilation large amounts of memory (over 7 Gb sometimes) and cpu are taken. I am now using full texlive installation, and if I compile minimal LaTeX file it takes about 7 s. on pdfLaTeX and 11 s. on XeLaTeX. I've tried to check if there is any difference between compilation on /mnt/c and in virtual partition, but I haven't seen any.
When I run --verbose it tends to stop for a long time there:
[makePDF] temp dir:
./tex2pdf.-e12d1f709f7253a6
[makePDF] Command line:
pdflatex "-halt-on-error" "-interaction" "nonstopmode" "-output-directory" "./tex2pdf.-e12d1f709f7253a6" "./tex2pdf.-e12d1f709f7253a6/input.tex"

[makePDF] Environment:
("TEXINPUTS","./tex2pdf.-e12d1f709f7253a6:")
("SHELL","/bin/bash")
("TBBROOT","/opt/intel/compilers_and_libraries_2020.4.304/linux/tbb")
("PSTLROOT","/opt/intel/compilers_and_libraries_2020.4.304/linux/pstl")
("LIBGL_ALWAYS_INDIRECT","1")
("WSL_DISTRO_NAME","Ubuntu")
("PKG_CONFIG_PATH","/opt/intel/compilers_and_libraries_2020.4.304/linux/mkl/bin/pkgconfig")
("WT_SESSION","a85cfba4-d3cd-4767-a4ea-eb71304ea2fa")
("I_MPI_ROOT","/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi")
("HOMEBREW_PREFIX","/home/linuxbrew/.linuxbrew")
("FI_PROVIDER_PATH","/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi/intel64/libfabric/lib/prov:/usr/lib64/libfabric")
("NAME","DESKTOP-D00B1T9")
("PWD","/mnt/c/Users/Acer/Desktop/Linux/Home/Notes/Studies/Seminars/Dirac_Physical_Interpretation_of_QM")
("LOGNAME","qsiek")
("MANPATH","/home/linuxbrew/.linuxbrew/share/man:/opt/intel/man/common:/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi/man:/opt/intel/documentation_2020/en/debugger/gdb-ia/man/:/usr/local/man:/usr/local/share/man:/usr/share/man::")
("CUDADIR","/usr/local/cuda")
("HOME","/mnt/c/Users/Acer/Desktop/Linux")
("LANG","C.UTF-8")
("WSL_INTEROP","/run/WSL/25516_interop")
("LS_COLORS","rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:")
("INFOPATH","/home/linuxbrew/.linuxbrew/share/info:/opt/intel/documentation_2020/en/debugger/gdb-ia/info/")
("IPPROOT","/opt/intel/compilers_and_libraries_2020.4.304/linux/ipp")
("LESSCLOSE","/usr/bin/lesspipe %s %s")
("TERM","xterm-256color")
("LESSOPEN","| /usr/bin/lesspipe %s")
("USER","qsiek")
("LIBRARY_PATH","/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi/intel64/libfabric/lib:/opt/intel/compilers_and_libraries_2020.4.304/linux/ipp/lib/intel64:/opt/intel/compilers_and_libraries_2020.4.304/linux/compiler/lib/intel64_lin:/opt/intel/compilers_and_libraries_2020.4.304/linux/mkl/lib/intel64_lin:/opt/intel/compilers_and_libraries_2020.4.304/linux/tbb/lib/intel64/gcc4.8:/opt/intel/compilers_and_libraries_2020.4.304/linux/tbb/lib/intel64/gcc4.8")
("HOMEBREW_CELLAR","/home/linuxbrew/.linuxbrew/Cellar")
("DISPLAY","172.29.96.1:0")
("SHLVL","1")
("HOMEBREW_REPOSITORY","/home/linuxbrew/.linuxbrew/Homebrew")
("CLASSPATH","/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi/intel64/lib/mpi.jar")
("LD_LIBRARY_PATH","/opt/intel/compilers_and_libraries_2020.4.304/linux/compiler/lib/intel64_lin:/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi/intel64/libfabric/lib:/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi/intel64/lib/release:/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi/intel64/lib:/opt/intel/compilers_and_libraries_2020.4.304/linux/ipp/lib/intel64:/opt/intel/compilers_and_libraries_2020.4.304/linux/mkl/lib/intel64_lin:/opt/intel/compilers_and_libraries_2020.4.304/linux/tbb/lib/intel64/gcc4.8:/opt/intel/debugger_2020/python/intel64/lib:/opt/intel/debugger_2020/libipt/intel64/lib:/usr/local/cuda/lib64:/usr/local/cuda/extras/CUPTI/lib64")
("XDG_RUNTIME_DIR","/tmp/runtime-qsiek")
("MKLROOT","/opt/intel/compilers_and_libraries_2020.4.304/linux/mkl")
("WSLENV","WT_SESSION::WT_PROFILE_ID")
("GCC_COLORS","error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01")
("XDG_DATA_DIRS","/usr/local/share:/usr/share:/var/lib/snapd/desktop")
("NLSPATH","/opt/intel/compilers_and_libraries_2020.4.304/linux/compiler/lib/intel64/locale/%l_%t/%N:/opt/intel/compilers_and_libraries_2020.4.304/linux/mkl/lib/intel64_lin/locale/%l_%t/%N:/opt/intel/debugger_2020/gdb/intel64/share/locale/%l_%t/%N")
("PATH","/home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin:/opt/intel/compilers_and_libraries_2020.4.304/linux/bin/intel64:/opt/intel/compilers_and_libraries_2020.4.304/linux/bin:/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi/intel64/libfabric/bin:/opt/intel/compilers_and_libraries_2020.4.304/linux/mpi/intel64/bin:/opt/intel/debugger_2020/gdb/intel64/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/cuda/bin")
("INTEL_PYTHONHOME","/opt/intel/debugger_2020/python/intel64/")
("HOSTTYPE","x86_64")
("INTEL_LICENSE_FILE","/opt/intel/compilers_and_libraries_2020.4.304/linux/licenses:/opt/intel/licenses:/mnt/c/Users/Acer/Desktop/Linux/intel/licenses")
("CPATH","/opt/intel/compilers_and_libraries_2020.4.304/linux/ipp/include:/opt/intel/compilers_and_libraries_2020.4.304/linux/mkl/include:/opt/intel/compilers_and_libraries_2020.4.304/linux/pstl/include:/opt/intel/compilers_and_libraries_2020.4.304/linux/pstl/stdlib:/opt/intel/compilers_and_libraries_2020.4.304/linux/tbb/include:/opt/intel/compilers_and_libraries_2020.4.304/linux/tbb/include")
("WT_PROFILE_ID","{2c4de342-38b7-51cf-b940-2309a097f518}")
("OLDPWD","/mnt/c/Users/Acer/Desktop/Linux/Home/Notes/Studies/Seminars")
("_","/usr/bin/pandoc")

[makePDF] Contents of ./tex2pdf.-e12d1f709f7253a6/input.tex:
\PassOptionsToPackage{unicode=true}{hyperref} % options for packages loaded elsewhere
\PassOptionsToPackage{hyphens}{url}
%
\documentclass[]{article}
\usepackage{lmodern}
\usepackage{amssymb,amsmath}
\usepackage{ifxetex,ifluatex}
\usepackage{fixltx2e} % provides \textsubscript
\ifnum 0\ifxetex 1\fi\ifluatex 1\fi=0 % if pdftex
  \usepackage[T1]{fontenc}
  \usepackage[utf8]{inputenc}
  \usepackage{textcomp} % provides euro and other symbols
\else % if luatex or xelatex
  \usepackage{unicode-math}
  \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase}
\fi
% use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
% use microtype if available
\IfFileExists{microtype.sty}{%
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
}
\usepackage{hyperref}
\hypersetup{
            pdfborder={0 0 0},
            breaklinks=true}
\urlstyle{same}  % don't use monospace font for urls
\setlength{\emergencystretch}{3em}  % prevent overfull lines
\providecommand{\tightlist}{%
  \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
\setcounter{secnumdepth}{0}
% Redefines (sub)paragraphs to behave more like sections
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi

% set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother

\date{}

\begin{document}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.

\end{document}

The markdown file is just:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.

and I use this command for minimal example (this particular example goes for under 4 min but I think it shouldn't take so long, slightly bigger with YAML header can take over 30 min):
pandoc -t latex test.md -o test.pdf


text:
Q: Try/Catch is breaking Firebase Cloud Functions I'm using Firebase Functions and have a try / catch within a get().then( ... ) function.
ESLint is calling the catch an error with:

Parsing error: Unexpected token { eslint

If I get rid of the try/catch completely, the error rolls up to another issue which is:
Each then() should return a value or throw eslint(promise/always-return)

That error resolves when adding
return null

I tried adding return null to the code when the try/catch was there to see if the issue may have just been that it was missing it, but it doesn't fix it.
An example of what this actually looks like in the code is this, I have tried what seems like everything:

A: I think you just need to change
try {...}
catch {...}

to
try {...}
catch(e) {...}


text:
Q: How to do JavaScript object introspection? What to do when after all probing, a reportedly valid object return 'undefined' for any attribute probed? I use jQuery, $('selector').mouseover(function() { }); Everything returns 'undefined' for $(this) inside the function scope. The selector is a 'area' for a map tag and I'm looking for its parent attributes.

A: Your question is a bit vague, so maybe you can provide more details?
As for finding out about an object and the values of its properties, there are many ways to do it, including using Firebug or some other debug tools, etc. Here is a quick and dirty function that might help get you started until you can provide more details:
function listProperties(obj) {
   var propList = "";
   for(var propName in obj) {
      if(typeof(obj[propName]) != "undefined") {
         propList += (propName + ", ");
      }
   }
   alert(propList);
}

That will display a list of the properties of the object that you pass it that are not undefined.
Hope that helps...

A: Is selector the name of the element?  If so then you should reference it as:
$('area#selector')

or
$('#selector')

otherwise it will attempt to look for the (non-existent) "selector" HTML tag and, obviously, not find it.

A: Though this answer is a bit late, I'd still recommend checking out these links:
http://www.webweavertech.com/ovidiu/weblog/archives/000317.html
http://www.syger.it/Tutorials/JavaScriptIntrospector.html


text:
Q: ClassNotFoundException : ValidateLogin after user enters username and password on java web application I have created a Java web app which is just a few simple jsp pages & java classes that retrieves data from a database and displays it to one of the jsp's. The app has functionality to add, edit and remove records from the mySQL database and then update the jsp with the new input/delete. This is all working fine so I moved on to creating a login screen which would check the username & password entered in to the textfield against database records. After implementing my code and testing my app, I keep receiving an error which is "Error instantiating servlet class ValidateLogin" because of the root cause "java.lang.ClassNotFoundException: ValidateLogin". I have researched alot in to this and a lot of people seem to think that I need to add some sort of jar to my class path. After reviewing other peoples stack traces with similar errors, they all seem to have at least one line which is something to do with their own written code. I do not have this and is all pointing to apache classes.
The stack trace is as follows:

javax.servlet.ServletException: Error instantiating servlet class ValidateLogin
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
      java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      java.lang.Thread.run(Thread.java:745)

root cause

java.lang.ClassNotFoundException: ValidateLogin
      org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
      org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
      java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
      org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      java.lang.Thread.run(Thread.java:745)

Is this error appearing because of something to do with my class path? Or am I missing some obvious point that will be an easy fix?
My java classes that check the database connection and records are as follows:
ValidateLogin.java (Servlet)
 package com.dunn.helpers;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author joshuadunn
 *
 */
 public class ValidateLogin extends HttpServlet {

/**
 *
 */
private static final long serialVersionUID = 1L;
public Connection connection;
public ResultSet results;
public String username, password, query;
public DatabaseConnection dbConnection;

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {
        username = request.getParameter("username");
        password = request.getParameter("password");

        query = "select * from users where username = '"+username+"' and password ='"+password+"'";
        dbConnection = new DatabaseConnection();
        connection = dbConnection.setConnection();
        results = dbConnection.getResult(query,connection);

        if (results.next( ) ) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("databaseEntry.jsp");
            dispatcher.forward(request, response);
            out.write(username);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    processRequest(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    processRequest(request,response);
}

}

DatabaseConnection.java
package com.dunn.helpers;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author joshuadunn
 *
 */
public class DatabaseConnection {

public Statement statement;
public ResultSet resultSet;
public Connection connection;

public DatabaseConnection() {

}

public Connection setConnection() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/pizzaApplication", "joshd", "joshd");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return connection;
}

public ResultSet getResult(String query, Connection conn) {
    connection = conn;
    try {
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultSet;
}
}

index.jsp is the login form page which calls on ValidateLogin
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import ="com.dunn.helpers.ValidateLogin"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>

<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">

Login

<form action ="ValidateLogin" method="POST" name="login">
<input type="text" id =username class="login-input" onblur="validateUsername();" />
<input type="text" id = password class="login-input" onblur="validatePassword();" />
<input type="submit" class="login-submit" />

Forgot password?

</form>

If anyone has any ideas on what I need to do to fix this problem it would be greatly appreciated. Im fairly new to java and have never updated my classpath before. Do i need something like sbt or maven to build my project and get the jars? Or does eclipse do this automatically?
Thanks.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<display-name>HelloWebApp</display-name>

<servlet>
<servlet-name>ValidateLogin</servlet-name>
<servlet-class>ValidateLogin</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ValidateLogin</servlet-name>
<url-pattern>/ValidateLogin</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
    30
</session-timeout>
</session-config>
</web-app>

A: You need to specify your class along with Package Hierarchy
<servlet>
  <servlet-name>ValidateLogin</servlet-name>
   <servlet-class>ValidateLogin</servlet-class>
</servlet>

Instead of above code Please specify as below along with Package
<servlet>
  <servlet-name>ValidateLogin</servlet-name>
    <servlet-class>com.xxx.yyy.ValidateLogin</servlet-class>
</servlet>

Here com.xxx.yyy is your Package hirerachy. I believe you had created your class in a package

A: The problem is here:
<servlet>
    <servlet-name>ValidateLogin</servlet-name>

    <servlet-class>ValidateLogin</servlet-class>
</servlet>

There's no class called ValidateLogin. In <servlet-class> you should specify the complete name of the class, this is the name of the package and the name of the class. Update this configuration into:
<servlet>
    <servlet-name>ValidateLogin</servlet-name>

    <servlet-class>com.dunn.helpers.ValidateLogin</servlet-class>
</servlet>

A better option will be to create a web application that uses Servlet 3.0 or superior, noticed by this part of your configuration:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

If you see, there's version="2.5" and there are references to 2.5 (or 2_5) in it. Change it to:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

And you can forget about defining the servlets in web.xml, instead use annotations:
//this annotation works like <servlet> and <servlet-mapping> together
@WebServlet("/ValidateLogin")
public class ValidateLogin extends HttpServlet {
    //class definition
}


text:
Q: Random write freezes I have a MySQL 5.5.23 DB that performs about 3k qps, 5% of which are writes. Lately, I've been having a big problem with random write freezes. Everything is going great, and then all of a sudden any write that comes in stops in the "update" or "Updating" state. They stay in this state for about a minute or two and then finally finish. The problem is that with such high amount of connections, when they freeze randomly like this, the connection stays open and then I inevitably get too many connection errors.
It's happening on all tables during both INSERT and UPDATE queries.
Has anyone seen this before? Is there anything that can be done about it?
I'm using Amazon RDS with the biggest instance they offer. I'd be more than happy to provide any information you guys need, just let me know what that is.
UPDATE: The main table I'm inserting into is:
CREATE TABLE `mytable` (
 `hash` varchar(5) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
 `name` varchar(256) DEFAULT NULL,
 `ip` varchar(64) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
 `deletehash` char(15) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
 `datetime` datetime NOT NULL,
 `api_key` varchar(64) CHARACTER SET latin1 COLLATE latin1_general_cs DEFAULT NULL,
 `account_id` int(10) unsigned DEFAULT NULL,
 `type` varchar(15) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
 `width` int(10) unsigned NOT NULL DEFAULT '0',
 `height` int(10) unsigned NOT NULL DEFAULT '0',
 `size` int(10) unsigned NOT NULL DEFAULT '0',
 `animated` tinyint(1) NOT NULL DEFAULT '0',
 `views` int(10) unsigned NOT NULL DEFAULT '0',
 `lastviewed` datetime NOT NULL,
 PRIMARY KEY (`hash`),
 UNIQUE KEY `deletehash` (`deletehash`),
 KEY `datetime` (`datetime`),
 KEY `account_id` (`account_id`),
 KEY `ip` (`ip`),
 KEY `api_key` (`api_key`),
 KEY `views` (`views`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Sample insert:
insert into mytable (hash, name, ip, deletehashe, datetime, api_key, account_id, type, width, height, size, animated, views, lastviewed) values('abcde', 'file name', '127.0.0.1', 'abcdefghijklmn', '2012-05-31 00:00:00', NULL, NULL, 'mime/type', 0, 0, 0, 0, 0, '0000-00-00 00:00:00');

Sample update:
update mytable set views = views+1, lastviewed = NOW() where hash = 'abcde';

A: I think the issue is due to the choice of the clustered index. From MySQL docs, Clustered and Secondary Indexes:

Every InnoDB table has a special index called the clustered index where the data for the rows is stored. Typically, the clustered index is synonymous with the primary key. To get the best performance from queries, inserts, and other database operations, you must understand how InnoDB uses the clustered index to optimize the most common lookup and DML operations for each table.

Also check the answer by @marc_s in this SO question: How to choose the clustered index in SQL Server?, where he mentions:

According to The Queen Of Indexing - Kimberly Tripp - what she looks for in a clustered index is primarily:

*

*Unique

*Narrow

*Static

  And if you can also guarantee:

*

*Ever-increasing pattern

  then you're pretty close to having your ideal clustering key!

Now, your clustered index is the (Primary Key):
hash varchar(5) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,

which (lets go through the check-list) is:

*

*Unique  (yes, OK)

*Narrow  (yes, OK)

*Static  (perhaps, you know that)

but is probably not:

*

*Ever-increasing pattern (No, it probably isn't)

So, what happens when you use a non-ever-increasing clustered index?
I can't answer better than Kimberly L. Trip: Ever-increasing clustering key - the Clustered Index Debate..........again!

If the clustering key is ever-increasing then new rows have a specific location where they can be placed. If that location is at the end of the table then the new row needs space allocated to it but it doesn't have to make space in the middle of the table. If a row is inserted to a location that doesn't have any room then room needs to be made (e.g. you insert based on last name then as rows come in space will need to be made where that name should be placed). If room needs to be made, it's made by SQL Server doing something called a split. Splits in SQL Server are 50/50 splits - simply put - 50% of the data stays and 50% of the data is moved. This keeps the index logically intact (the lowest level of an index - called the leaf level - is a douly-linked list) but not physically intact. When an index has a lot of splits then the index is said to be fragmented. Good examples of an index that is ever-increasing are IDENTITY columns (and they're also naturally unique, natural static and naturally narrow) or something that follows as many of these things as possible - like a datetime column (or since that's NOT very likely to be unique by itself datetime, identity).

Note that despite the mention of SQL-Server, the same concept applies to InnoDB clustered indexes as well. I suppose that the clustered index has 2 issues:

*

*When you are inserting a new row (the "random" hash guarantees that) it gets inserted in a random location of the index. This means that it sometimes will find no space there available to be inserted (note that InnoDB always leaves some space free in the index but when that free-available space is filled) there has to be some rearrangement of the index - and that takes time.

*What the rearrangement is also causing over time is fragmentation of the index. Which will eventually make other queries and statements slower.


text:
Q: "Show Annotation..." Shortcut no longer working in Eclipse 2020-12 (4.18.0) The shortcut Ctrl + Alt + A is no longer working. I already set in Window -> Preferences -> General -> Keys the value "Show Annotation..." to Ctrl + Alt + A. But it's still not working.
It's still possible to use Right Click in file -> Team -> Show Annotation...

A: *

*make sure you have no conflicts in the bindings
Example: Show Annotation + Show in (SVN Annotate). You do not want this

*make sure the action set "SVN" is available in your view:
window -> perspective -> customize perspective. Tab: Action Set Availability. Check SVN
Checkbox svn in action set availability


text:
Q: Calling another different view from the controller using ASP.NET MVC 4 I have a view (Index.cshtml) with a submit button. When the submit button is clicked, it calls an action (Action01) within the controller (TestController.cs) so at the end of the action I want to return to the caller (Index.cshtml) view with a custom view model as a parameter. How do I do this?
Results after first attempt using View("ViewName",model):
An error is raised, as the action is within the controller Test, so returning, it is searching for \Views\Tests\Index, and my Index page is in \Views\Home\Index.
The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Test/Index.aspx
~/Views/Test/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Test/Index.cshtml
~/Views/Test/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml

Final solution:
I have used return View("ViewName", model), and I have changed my directories structure as it was the problem.

A: To return a different view, you can specify the name of the view you want to return and model as follows:
return View("ViewName", yourModel);

if the view is in different folder under Views folder then use below absolute path:
return View("~/Views/FolderName/ViewName.aspx");

A:             public ActionResult Index()
            {
                return View();
            }

            public ActionResult Test(string Name)
            {
                return RedirectToAction("Index");
            }

Return View Directly displays your view but
Redirect ToAction Action is performed

A: You have to specify the name of the custom view and its related model in Controller Action method.
public ActionResult About()
{
   return View("NameOfViewYouWantToReturn",Model);
}

A: You can directly return a different view like:
return View("NameOfView", Model);

Or you can make a partial view and can return like:
return PartialView("PartialViewName", Model);

A: Also, you can just set the ViewName:
return View("ViewName");

Full controller example:
public ActionResult SomeAction() {
    if (condition)
    {
        return View("CustomView");
    }else{
        return View();
    }
}

This works on MVC 5.


text:
Q: Capybara + Selenium - Element is not clickable at point (388.3833312988281, 8.333328247070312). Other element would receive the click Im having a problem with a button.
Every time i tried to click, i receive this message
" Element is not clickable at point (388.3833312988281, 8.333328247070312). Other element would receive the click. "
Im using Firefox, and Capybara + ruby, and selenium ( not webdriver )
Heres the code of the button
I want to click on the Add button
What can i do ?

                  Add

A: This issue usually appear when the DOM either is not ready or is changing.
So you should wait until the page become stable, all async scripts are finished, images loaded and so on. Ads also could be an issue, as they could change the page.
Please have a look here for waiting (by the way, I'd recommend to use watir webdriver on top of Selenium):
http://watir.github.io/docs/waiting/
Here are steps for reducing probability of this issue:

*

*wrap this code in rescue block and retry when it happens

*disable images loading

*install AdBlock or similar extension

*use wait_ helpers in Watir

*try to avoid using complicated css selectors. Use something like button(text: 'Add') instead

*if you use it, try to select an element as close to click action in your code as it possible

A: I'm not sure I understand your "not webdriver" comment, since the only way to use selenium with Capybara is via the selenium-webdriver gem.
Judging by the y position of the error you're getting (8.333328247070312) it's likely that the button you're trying to click is behind a fixed header.  This is either because you haven't clicked an element necessary to make the button slide out from behind the header or because the page was longer than the screen and selenium-webdriver scrolled the page until the element was at the top (which ends up behind your header).  If you don't have a fixed footer on the page then you can change selenium-webdriver, via the elementScrollBehavior property, to scroll elements to the bottom instead of the top - see Selenium WebDriver : How do I set capabilities elementScrollBehavior to 1 for a FireFox configuration in rails?
. If that doesn't work for you then you can use execute_script and JS to scroll the page so the element moves out from under the header


text:
Q: PhoneGap: InAppBrowser I have installed the plugin:
https://github.com/apache/cordova-plugin-inappbrowser
I have followed their installation directions:
Installation

cordova plugin add cordova-plugin-inappbrowser
If you want all page loads in your app to go through the InAppBrowser,
you can simply hook window.open during initialization. For example:

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    window.open = cordova.InAppBrowser.open;
}

I have added this to my config.xml:
<gap:plugin name="cordova-plugin-inappbrowser" source="npm" version="1.0.1" />
<feature name="InAppBrowser">
<param name="ios-package" value="CDVInAppBrowser" />
</feature>

This is my code to use the above:
    Test 1

    Test 2

To no avail, when I click these links (on Android), nothing happens. Why?

A: Have you tried
window.open('http://example.com', '_blank');
without the document ready listener you have added.


text:
Q: why layered navigation shopping option BRAND not working?
I added custom attribute brand and i want that brand to be in layered navigation to filter the products by brand. But as in the attached picture its not create links for brand section and not showing the total number of products for each brand.

A: First of all you need to goto "Frontend properties" of attributes and set
Use In Layered Navigation to YES.
Also you have to set is Anchor YES for that category.
And also the category should have some products with brand value.


text:
Q: WooCommerce Sort-by SKU - Get numeric order correct I have a website running WooCommerce and on the Product Category page we have the option "Sort by SKU in Ascending order". The products have SKUs in the format of 4 Alpha and 2 Numeric, e.g. BLHS-20.
The issue we have is when the list of products in the Product Category page is sorted the SKUs aren't in true numeric order.
Example:
BLHS-1
BLHS-10
BLHS-11
BLHS-2
What code would we need to get the SKUs to sort as follows?
BLHS-1
BLHS-2
BLHS-10
BLHS-11
Thanks for any help given.

A: Ok, we have a workaround. Because the SKU field is a text field the simple fix is to find the largest numeric part of the SKU and for all smaller numbers add leading zeros.
Example:
BLHS-01
BLHS-02
BLHS-10
BLHS-11
This sorts correctly.


text:
Q: How do I get an average for each column for each gene in R? I am working with a data frame in R, beginning as follows:
   > head(renamed.Mc.Cd.Ni[2:6])
   s_MC13_B2_Cd.Ni s_MC13_B3_Cd.Ni s_MC13_B4_Cd.Ni     GENE_ID
   9.854759       10.216916        9.722329     GENE:JGI_V11_100009
   7.863938        8.075640        7.894878     GENE:JGI_V11_100009
   9.448034        9.177245        9.053654     GENE:JGI_V11_100036
   9.333245        9.208673        9.159947     GENE:JGI_V11_100036
   9.360540        9.374757        9.273236     GENE:JGI_V11_100036
   8.983222        9.023339        9.112987     GENE:JGI_V11_100044

As you can see, I have three columns which give a gene expression value for 3 different daphnia when under a treatment. The final column represents the gene expressed. However, there are more than one row for each gene due to multiple probes being used. How do i get an average for each gene for each daphnia (columns 1-3)?
For example, for each of the three daphnia (columns 1 to 3), I want an overall average gene expression for each gene shown in column 4. I cant do it manually as I have over 60,000 gene probe expression values.
Thank you in advance!

A: Your question appears to be a straight forward mean by group problem, there are several examples already on SO... so this is a duplicate, however, this a a tidy approach to solving your problem.
library(dplyr)

df <- read.table(text = "
s_MC13_B2_Cd.Ni s_MC13_B3_Cd.Ni s_MC13_B4_Cd.Ni     GENE_ID
9.854759       10.216916        9.722329     GENE:JGI_V11_100009
7.863938        8.075640        7.894878     GENE:JGI_V11_100009
9.448034        9.177245        9.053654     GENE:JGI_V11_100036
9.333245        9.208673        9.159947     GENE:JGI_V11_100036
9.360540        9.374757        9.273236     GENE:JGI_V11_100036
8.983222        9.023339        9.112987     GENE:JGI_V11_100044
", header = TRUE, stringsAsFactors = FALSE)

df %>%
  group_by(GENE_ID) %>%
  summarise_if(is.numeric, mean)

# # A tibble: 3 x 4
#   GENE_ID             s_MC13_B2_Cd.Ni s_MC13_B3_Cd.Ni s_MC13_B4_Cd.Ni
#   <chr>                         <dbl>           <dbl>           <dbl>
# 1 GENE:JGI_V11_100009            8.86            9.15            8.81
# 2 GENE:JGI_V11_100036            9.38            9.25            9.16
# 3 GENE:JGI_V11_100044            8.98            9.02            9.11


text:
Q: `pip install -e .` does not work in windows conda environment I want to install a local package. Usually, I would go to the package directory and type
pip install -e .

And then be able to use the package from anywhere, if the respective conda environment is activated. Though under Windows I get the message

Successfully installed {package}

But if I try to import it, I get

Module not found

How can I properly install a local package in a conda environment under Windows?

A: Did you
conda install pip

?  A conda environment needs it's own pip, then
pip install -e path/to/a/python/package

works.


text:
Q: Does anyone know what this file could be? The server I'm on is using Plesk and in the httpdocs directory there is a folder called test which has a structure similiar to the following:
httpdocs/test/cgi/
httpdocs/test/coldfusion/
httpdocs/test/fcgi/
httpodcs/test/php/
Specifically within the fcgi directory, there are 4 files
fcgi.py
fcgi.pyc
test.fcgi
test.html
I am a programmer, not a server administrator. All of the files in this seem like they are created by default via the Plesk control panel as they all have the same timestamp ( Last modified ). There is one file however that was added to the directory at about 2 am with a 'last modified' date about 1 month after the others, which is fcgi.pyc. I've downloaded it and opened in VI and it is full of characters such as:
Mc@^@^@^

although there is some html thrown into the file as well.
We've had issues before with finding variants of c99shell and other websites on the same server being allowed to run functions like exec() and get lists of files on the domain. I am just wondering if anyone familiar with Plesk/Servers would know why a seemingly corrupt file names fcgi.py appears in this directory.
I've searched google for the filename and all I find is open directories that are containing the same file.
If anyone can provide any insight whatsoever I would be quite grateful.

A: By default, when you set up a site, Plesk will install some test files for CGI, FCGI (Fast CGI), ColdFusion (CFML) and PHP. These are so you can check all the correct software is working when you set up a site, not very useful I know but they're there all the same.
Files with the .pyc extension are the compiled version of .py (Python) files that get automatically generated when the .py file is run.
You can test this out if you want, on a UNIX/Linux system create a file with the code
print "Hello World"

and save it with a .py extension somewhere, then from the command line run python ./path/to/that/file.py and it will echo out 'Hello World', then if you check the directory with the .py file in there should be a .pyc file next to it that was created when the Python script was compiled and run.
As for how the script got there, my guess would be someone like GoogleBot came along and hit that file on the website, this caused the file to get run with Python which created that .pyc file. The next time someone hits that URL, instead of having to re-compile the Python script again it can just use the .pyc file so it'll be faster.
You can just delete those files if you don't need/want them, anything in the /test directory in httpdocs is just test scripts.

A: .py is python code which is usually readable and pyc is the compiled python code which would not be readable and is probably created on demand which might explain why it has a different timestamp. Are you sure this isn't just some test website that happens to be configured to use python?
What is in test.html?

A: I believe it's a file associated with Fast CGI which is likely turned on in Plesk. It's a complied version of the Python script.


text:
Q: Android add a view at the beginning of a listview I have a listview with a base adapter. I have an inflater which gives the style for each item of my list, but the thing I want to do is to add a view at the beginning of the listview with a different inflated layout.
Is this possible?

A: Yes.  There's two ways of doing it.  The first is to add a listview header. The second is to add an item to your adapter that holds the first place in the list, and map it as if it was an item.

A: Possible duplicate of
Android ListView headers
This might also help.
http://stacktips.com/tutorials/android/listview-with-section-header-in-android


text:
Q: Разработка командной строки (CLI) Программе на вход подается argv argc, мне нужно обрабатывать команды вида:
cmd cmd1 [cmd2 arg] [cmd3] [cmd4 arg]...
Текущая реализация работает только если опции в нужном порядке и заданы все опции, каким образом можно реализовать подобно утилитам в линуксе чтобы опции были опциональны и была возможность вызывать в разном порядке? Буду рад любым ссылкам, статьям, идеям. То что пока что пришло в голову это построить конечный автомат, но мне кажется есть какие то решения фреймворки для такой типовой задачи.

A:
пришло в голову построить конечный автомат

Этот конечный автомат уже сделан. Называется он getopt. Делаем man 3 getopt и читаем:
Функция getopt() разбирает аргументы командной строки. Ее аргументы argc и argv являются счетчиком и массивом аргументов, которые передаются функции main() при запуске программы. Элемент argv, начинающийся с "-" (и не являющийся "-" или "--"), считается опцией. Символы этого элемента (не считая начального "-") являются символами опций. При каждом повторном вызове getopt() возвращаются символы следующей опции.
Есть более продвинутый вариант этого автомата. Называется getopt_long()


text:
Q: using filter and generator to generator endless prime number in python Below is a python program I found to find prime numbers using Sieve of Eratosthenes. It uses filter and generator. I'm not able to understand it.
def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n

def _not_divisible(n):
    return lambda x: x % n > 0

def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(_not_divisible(n), it)

for n in primes():
    if n < 1000:
        print(n)
    else:
        break

What I don't understand is it = filter(_not_divisible(n), it). For example for number 105, how is it excluded by this single line of code?

A: It's not just that single line of code, it's that line being run repeatedly, with different values of n.
Basically, it is an iterator that yields candidate prime numbers which have not yet been ruled out by the sieve. You start by making all odd numbers candidates.
it = _odd_iter()

Then you repeatedly take the first remaining candidate,
while True:
    n = next(it)

remove all numbers that are multiples of that candidate,
    filter(_not_divisible(n), it)

and replace your candidate primes with everything that is left after removing multiples.
    it = ...

If you pretend filter returns a list of numbers, rather than an iterable, and also pretend _odd_iter() returns a list of odd numbers instead of an iterable, you can trace through the loop and determine what's in the list at each point. For example, after running
it = _odd_iter()

you start with
it = 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, ...

Then run
    n = next(it) # 3

which pulls the first item off the front, leaving you with
it = 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, ...

and run
    it = filter(_not_divisible(3), it)

filter out all the multiples of 3,
it = 5, 7, 11, 13, 17, 19, 23, 25, ...

Then go back to the top of the loop and pull the new first number off the front
    n = next(it) # 5

leaving
it = 7, 11, 13, 17, 19, 23, 25, ...

and then filter out all the multiples of 5,
    it = filter(_not_divisible(5), it)

which gives
it = 7, 11, 13, 17, 19, 23, ...

and so on.
In practice, because filter() returns an iterator, not a list, you wind up getting a nested sequence of iterators. In particular, you start with
it = _odd_iter()

then after the first iteration of the loop, you have basically
it = filter(_non_divisible(3), _odd_iter())

except that 3 has been taken from the iterator, and then after the second iteration of the loop you have
it = filter(_non_divisible(5), filter(_non_divisible(3), _odd_iter()))

except that 5 has also been taken from the iterator, and then
it = filter(_non_divisible(7), filter(_non_divisible(5), filter(_non_divisible(3), _odd_iter())))

and so on.

A: For each prime number found a filter is applied to the iterable, the filter used is a function that excludes all multiples of the prime number.
So your iterable is wrapped in as many filters as you found prime numbers, for example the number 105 is excluded because it's divisible by 3 and the filter for all multiples of 3 was added when you found the prime number 3.
If you add some print statements it will be a bit clearer (I hope):
def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n

def _not_divisible(n):
    print('add filter for all multiples of', n)
    return lambda x: print('check if', x, 'is divisible by', n, 'result: ', not (x % n > 0)) or x % n > 0

def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(_not_divisible(n), it)

for n in primes():
    if n < 20:
        print(n)
    else:
        break

which prints:
2
3
add filter for all multiples of 3
check if 5 is divisible by 3 result:  False
5
add filter for all multiples of 5
check if 7 is divisible by 3 result:  False
check if 7 is divisible by 5 result:  False
7
add filter for all multiples of 7
check if 9 is divisible by 3 result:  True
check if 11 is divisible by 3 result:  False
check if 11 is divisible by 5 result:  False
check if 11 is divisible by 7 result:  False
11
add filter for all multiples of 11
check if 13 is divisible by 3 result:  False
check if 13 is divisible by 5 result:  False
check if 13 is divisible by 7 result:  False
check if 13 is divisible by 11 result:  False
13
add filter for all multiples of 13
check if 15 is divisible by 3 result:  True
check if 17 is divisible by 3 result:  False
check if 17 is divisible by 5 result:  False
check if 17 is divisible by 7 result:  False
check if 17 is divisible by 11 result:  False
check if 17 is divisible by 13 result:  False
17
add filter for all multiples of 17
check if 19 is divisible by 3 result:  False
check if 19 is divisible by 5 result:  False
check if 19 is divisible by 7 result:  False
check if 19 is divisible by 11 result:  False
check if 19 is divisible by 13 result:  False
check if 19 is divisible by 17 result:  False
19
add filter for all multiples of 19
check if 21 is divisible by 3 result:  True
check if 23 is divisible by 3 result:  False
check if 23 is divisible by 5 result:  False
check if 23 is divisible by 7 result:  False
check if 23 is divisible by 11 result:  False
check if 23 is divisible by 13 result:  False
check if 23 is divisible by 17 result:  False
check if 23 is divisible by 19 result:  False

A: First, filter over iterator returns another iterator. I.e. when we do something like:
it = filter(_not_divisible(3), it)
it = filter(_not_divisible(5), it)

We get a chained iterator "odd number AND not divisible by 3 AND not divisible by 5". It is somewhat similar to chained decorators, where we get an equivalent of:
# assuming we have decorator @not divisible
@not_divisible(2)
def iter():
    return xrange(inf)

# then, at every subsequent prime we do something like:
iter = not_divisible(3)(iter)
# next prime is 5:
iter = not_divisible(5)(iter)

... and so on


text:
Q: Postgres- group each n days Can i group each n days in postgres
If we have:
date       |  price
2018-01-01 |  10
2018-01-02 |  11
2018-01-03 |  10.5
.....

something like grouping each 10 days and get the avg of price column

A: How about this? It buckets consecutive 10 day periods regardless of gaps.
CREATE TABLE date (
  date  DATE             NOT NULL,
  price DOUBLE PRECISION NOT NULL
);

INSERT INTO date (date, price)
SELECT (now()::DATE) + s.i,
  s.i :: DOUBLE PRECISION
FROM generate_series(0, 1000) AS s(i);

SELECT ((extract(EPOCH FROM date) / (60 * 60 * 24)) :: BIGINT) / 10
    , avg(price) AS average_price
FROM date
GROUP BY 1
ORDER BY 1;

A: example data:
ugautil=> select id,date, price from sales order by 1 limit 30;
id  |    date    | price
-----+------------+--------
569 | 2018-01-01 | 296.01
570 | 2018-01-02 | 409.50
571 | 2018-01-03 |  46.73
572 | 2018-01-04 | 302.13
573 | 2018-01-05 | 313.83
574 | 2018-01-06 | 302.68
575 | 2018-01-07 | 359.53
576 | 2018-01-08 | 348.60
577 | 2018-01-09 | 376.09
578 | 2018-01-10 |  23.71
579 | 2018-01-11 | 470.93
580 | 2018-01-12 | 409.37
581 | 2018-01-13 | 160.95
582 | 2018-01-14 |  22.04
583 | 2018-01-15 | 295.15
584 | 2018-01-16 | 475.42
585 | 2018-01-17 | 399.37
586 | 2018-01-18 | 394.43
587 | 2018-01-19 |  91.97
588 | 2018-01-20 |  27.38
589 | 2018-01-21 | 286.23
590 | 2018-01-22 |  57.81
591 | 2018-01-23 | 486.14
592 | 2018-01-24 |  10.30
593 | 2018-01-25 | 423.67
594 | 2018-01-26 | 169.94
595 | 2018-01-27 | 152.08
596 | 2018-01-28 | 344.42
597 | 2018-01-29 | 448.63
598 | 2018-01-30 | 360.33
(30 rows)

Picking Jan 1, 2018 as start date. Every 10 days gives us an index number.
only looking at first 3 groups in Jan
ugautil=> select floor((extract(epoch from date) - extract(epoch from date('2018-01-01')))/86400/10) as "ten_day_index", round(avg(price),2) from sales group by 1 order by 1 limit 3;
ten_day_index | round
---------------+--------
           0 | 277.88
           1 | 274.70
           2 | 273.96
(3 rows)

ugautil=> delete from sales where id >= 569 and id <= 576;
DELETE 8
ugautil=> select id,date, price from sales order by 1 limit 30;
id  |    date    | price
-----+------------+--------
577 | 2018-01-09 | 376.09
578 | 2018-01-10 |  23.71
579 | 2018-01-11 | 470.93
580 | 2018-01-12 | 409.37
581 | 2018-01-13 | 160.95
582 | 2018-01-14 |  22.04
583 | 2018-01-15 | 295.15
584 | 2018-01-16 | 475.42
585 | 2018-01-17 | 399.37
586 | 2018-01-18 | 394.43
587 | 2018-01-19 |  91.97
588 | 2018-01-20 |  27.38
589 | 2018-01-21 | 286.23
590 | 2018-01-22 |  57.81
591 | 2018-01-23 | 486.14
592 | 2018-01-24 |  10.30
593 | 2018-01-25 | 423.67
594 | 2018-01-26 | 169.94
595 | 2018-01-27 | 152.08
596 | 2018-01-28 | 344.42
597 | 2018-01-29 | 448.63
598 | 2018-01-30 | 360.33
599 | 2018-01-31 | 120.00
600 | 2018-02-01 | 328.08
601 | 2018-02-02 | 393.58
602 | 2018-02-03 |  52.04
603 | 2018-02-04 | 206.91
604 | 2018-02-05 | 194.20
605 | 2018-02-06 | 102.89
606 | 2018-02-07 | 146.78
(30 rows)

ugautil=> select floor((extract(epoch from date) - extract(epoch from date('2018-01-01')))/86400/10) as "ten_day_index", round(avg(price),2) from sales group by 1 order by 1 limit 3;
ten_day_index | round
---------------+--------
           0 | 199.90
           1 | 274.70
           2 | 273.96
(3 rows)

only the Jan 9 and 10 entries are in the first average in group 0

A: This is pretty brute force, and I'll bet a dollar it's wickedly inefficient due to the > and < in the join, but it notionally sounds like what you want to do:
with intervals as (
  select start_date, start_date + interval '10 days' as end_date
  from generate_series (
    (select min (date) from price_data),
    (select max (date) from price_data),
    interval '10 days') gs (start_date)
)
select
  i.start_date, sum (p.price) / 10 as average
from
  price_data p
  join intervals i on
    p.date >= i.start_date and
    p.date <  i.end_date
group by
  i.start_date

This looks a whole lot uglier, but I suspect on large datasets it would run a lot faster:
with intervals as (
  select
    start_date::date as start_date,
   (start_date + interval '10 days')::date as end_date
  from generate_series (
    (select min (date) from price_data),
    (select max (date) from price_data),
    interval '10 days') gs (start_date)
),
exploded_intervals as (
  select
    start_date + i as snapshot_date, start_date, end_date
  from
    intervals i
    cross join generate_series (0, 9) gs (i)
)
select
  i.start_date, sum (p.price) / 10 as average
from
  price_data p
  join exploded_intervals i on
    p.date = i.snapshot_date
group by
  i.start_date

I don't promise these are the best way to do it, but they are ways to do it.
In a nutshell, I am taking the minimum and maximum dates in your dataset and chunking them into 10-day intervals.  This does presuppose that the clock on "every 10 days" starts on your first date.
From there, I am grouping the actual data into each of these date buckets, summing the prices and dividing by 10.  If you have missing dates, it should account for that.  If you have duplicates on the same day...  well, then it's going to artifically inflate your "average."  If you define a rule on how to deal with dupes, that is easy enough to manage.


text:
Q: The argument type 'Object' can't be assigned to the parameter type 'Map? i have encountered this error :
The argument type 'Object' can't be assigned to the parameter type 'Map<String, dynamic>?

in this line of code :
 listMakans = query.docs.map((m) => Makan.fromSnapshot(m.data()!)).toList();

and here is the code for (Makan.fromSnapshot):
Makan.fromSnapshot(Map<String, dynamic>? snapshot)
      : id = snapshot!['id'],
        owner = snapshot['owner'],
        category = snapshot['category'],
        hobby = snapshot['hobby'],
        business = snapshot['business'],
        title = snapshot['title'],
        details = snapshot['details'],
        latlng = snapshot['latlng'],
        from = snapshot['from'].toDate(),
        to = snapshot['to'].toDate(),
        created = snapshot['created'].toDate(),
        updated = snapshot['updated'].toDate();

i didn't understand where the Object here?

A: Remove ? from
Makan.fromSnapshot(Map<String, dynamic>

This (m.data()!)) is the Object in the error.

A: listMakans = query.docs.map((m) => Makan.fromSnapshot(m.data() as Map<String, dynamic>?)).toList();


text:
Q: build a dynamic link in devexpress ASP MVC I try to build a dynamic link in devexpress batch diting.
Well, i need to build link like:
Ir para ...

Where @item.IdFornecedor and @item.IdFilial are dynamic values by line.
Now, how i can build a column with this values?
settings.Columns.Add(c =>
    {
        c.SetDataItemTemplateContent(a =>
        {
            ViewContext.Writer.Write(
                   "asd");
        });
    });

A: It possible using DataBinder.Eval(a.DataItem, "IdForn")
    settings.Columns.Add(c =>
    {
        c.SetDataItemTemplateContent(a =>
        {
            ViewContext.Writer.Write(
                   "Ir para ...");
        });
        c.Width = System.Web.UI.WebControls.Unit.Percentage(7);
    });


text:
Q: Why buttons are outside of JQM popup's footer Using Jquery-mobile, the following (abbreviated here) footer

    Open
    Close

that exist in a popup, when popped-up, its buttons
are displayed outside the popup-frame, aligned under it.
Why? What am I doing wrong?
The full example is in http://jsfiddle.net/yotam/d0aqmx6m/

A: I'm beginning to wonder if button footers are not supported in popups.  Or at least, not fully supported.  From the docs, you need to throw a "ui-title" in there too - it's what will give the footer height (The docs show a span after the button definitions).
I've done that here:

  Open
  Close

See: http://jsfiddle.net/had4or71/
Of course, it only partially solves your problem, as though they are now in the footer, they don't yet look good.  I tried with a navbar in the footer with similarly disappointing results (the navbar was well positioned top, bottom, and left, but ran over the right border pretty badly.
Finally, I did this version real quick as well:
http://jsfiddle.net/ph0e54ee/2/
Which shows pushing the close button into the header like the demos site does, and just presenting your open button inline as a standard button - alas, it's a compromise, and not what you asked for.
On further investigation, it would appear the "ui-btn-left" and "ui-btn-right" classes are not supported in the footer, see:

*

*gh:6331

*gh:6872

*gh:6137 (comment)
Again, I messed about with the CSS a bit, and managed to get something sort of nice, at least on my test browser of chrome.  I suspect your mileage will vary greatly outside of chrome.: http://jsfiddle.net/9crnjakr/


text:
Q: use external functions in the componentDidMount() and pass an element of the state to them as parameter I have a big application in React-Native and I have a lot of duplicate functions in the code.
So I created a file called function.js which could contain all my duplicate functions. Like queries on the local database, remote data base...
So I pretty much got the job done. However I have a problem.
This two functions must be used one after the other.
The first one does an update of the state to get a user id from local database.
The second one, asks information from the remote database with the user id retrieved by the first function in parameters.
When both calls are in the componentdidmount element, unfortunately it doesn't work !!
The update time of the state by the first function is too slow compared to the execution of the second function.
The second function gets an "undefined" parameter when it is executed. because the state is not updated by the first function for the moment.

*

*If I put the second function in componentDidUpdate() it works but it runs in a loop so it's not a solution either.

*I also don't want to trigger the execution of the second function at the end of the first one in the external file. It would make the functions not autonomous from each other.

*And I think that the solution of a timeout() is not very good either, even if we could work with it.

Example code :
It's the content of my App.js file that imports the Function.js file containing all my functions
import React, { Component } from 'react';
import { fetchUser, prepareUserData } from 'bitcoin/Functions/Function'

export default class Profile extends Component {

  state = {
    user_id: "",
  }

  componentDidMount() {
    fetchUser.call(this);
    prepareUserData.call(this, this.state.user_id)
  }

render{
 return (<View></View>)
}

This is the content of my Function.js file which contains functions that are duplicated in my application.
import * as SQLite from "expo-sqlite";
import axios from "axios";

const db = SQLite.openDatabase("db.db");

/* #############################################################################
User data retrieval function in the local database
##############################################################################*/
export function fetchUser () {
  let query = "select * from ?";
  let params = [];
  db.transaction(tx => {
    tx.executeSql(
      query,
      params,
      (_, { rows: { _array } }) => {
        this.setState({user_id: _array[0].user_id})
      },
      function(tx, err) {
        console.log("Erreur" + err);
      }
    );
  });
}

/* #############################################################################
User data retrieval function in the remote database
##############################################################################*/
export function prepareUserData(userID) {
    let userConnect = new FormData();
    userConnect.append("id", userID);

    console.log(userConnect)
    const url =
      "https://*************/rest_api/React_native_api/appmobile_profile";

    axios
      .post(url, userConnect)
      .then(res => {
        console.log(res.data)
        if(res.status === 200){
        this.setState(
          {
            user_pseudo: res.data.pseudo,
            [ ... ]
            user_lastName: res.data.last_name,
           },);
       }
      })
      .catch(err => {
        console.log("Erreuur", err);
      });
  }

I've tried a lot of things with async componentDidMount(), await myfunc(), creating asynchronous functions in my function file ...
But I can't find solutions. I could do otherwise but I find the problem really interesting.
I think there is a way to optimize my use of react native.
Thank you for your various feedbacks. Have a nice day.

A: Okay, so I've come up with a effective solution to this problem.
I don't know much about promise and yet it seems to be a key for a lot element in react-native and javascript in general.
I'll share my code. Hopefully it can be useful to someone in the future! thank you for your prompt return and see you soon!
To make it work I used:

*

*The Promise Object new Promise(function(resolve,reject)

*Creation of a dynamic SQL query by adding parameters when calling the function.

File App.js
import React, { Component } from 'react';
import { selectFromTable, prepareUserData } from 'bitcoin/Functions/Function'

export default class Profile extends Component {

  state = {
    user_data: "",
  }

  componentDidMount() {
    selectFromTable('user', ['*']).then((result) => {
      this.setState({ user_data: result.rows._array[0] },() =>
       {prepareUserData.call(this, this.state.user_data.user_id)})
    })
  }

render{
 return (<View></View>)
}

File Function.js
export function selectFromTable(table_name, selected_columns, conditions, callback) {
        return new Promise(function(resolve,reject) {
            let db_cmd = `SELECT ${selected_columns} FROM ${table_name}`;
            db.transaction((tx, err) => {
                tx.executeSql(db_cmd, [], (tx, res) => {
                    resolve(res);
                },
                function(tx, err) {
                  console.log("Error" + err);
                }
                );
            });
        });
    }

export function prepareUserData(userID) {
   let userConnect = new FormData();
    userConnect.append("id", userID);
    const url =
          "https://**********/**********/appmobile_profile";

        axios
          .post(url, userConnect)
          .then(res => {
            console.log(res.data)
            if(res.status === 200){
            this.setState(
              {
                user_pseudo: res.data.pseudo,
                user_cellphone: res.data.cellphone,
                user_callingCode: res.data.calling_code,
               });
            };
          })
          .catch(err => {
            console.log("Error", err);
          });
      }


text:
Q: Letting Pin select one Category I have problem letting my pin select 1 category, below is what I had attempted.
$ rails g model category name:string

$ rails g migration add_category_id_to_event

in /db/migrate/XXXX_add_category_id_to_pin

I modified
class AddCategoryIdToPin < ActiveRecord::Migration
def self.up
  add_column :pins, :category_id, :integer
 end

def self.down
 remove_column :pin, :category_id
  end
 end

 Rake db:migrate

in app/models/pin.rb
 class Event < ActiveRecord::Base
  belongs_to :category
 end

in app/models/category.rb
class Category < ActiveRecord::Base
 has_many :pins
 end

in rails console
Category.create( :name => "Course" )
Category.create( :name => "Meeting" )
Category.create( :name => "Conference" )

In app/views/pins/_form.html.erb
<%= f.select :category_id, category_options %>

In pp/views/pins/show.html.erb

Category: <%= @pin.category.name %>

in app/helpers/pins_helper.rb
module PinsHelper
 def category_options
    Category.all.map{ |c| [c.name, c.id] }
 end
end

But now nothing shows up on my app and I get the below, before all this was working fine. So I don't understand where went wrong? Can Some one help?
NameError in Pins#index
Showing /Users/mattbook/code/dine/app/views/layouts/_header.html.erb where line #17 raised:
undefined local variable or method `new_pin_path' for #<#:0x007f92565413d0>
Extracted source (around line #17):
14:
15:
16:
17:                             <% if user_signed_in? %>
*<%= link_to "拚 +", new_pin_path %>
18:
*
19:                               個人
20:


text:
Q: UIDocumentInteractionController for remote pdf files Does anybody know how to use UIDocumentInteractionController to "Open in iBooks" remote pdf files, i can't seem to be able to get around this one. I have managed to open my pdf in QLPreviewController and get the OptionsMenu to give me the option to open in iBooks but i won't open the file if it is remote...when i use local file it works fine.
If this is not possible what is the alternative?
Thanks in advance

A: Although UIDocumentInteractionController has a convenience method interactionControllerForURL:, it requires the argument to be a file URL. So you either download the PDF within your app and open it with the UIDocumentInteractionController object or you can use a UIWebView object to open remote PDFs. Pass the URL to the web view and they open just fine.

A: Ad mentioned you must use a file url for UIDOcumentInteractionController. First download the document. A really easy way to do this is with AFNetworking. Here is how I am using AFNetworking to download a file:
- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)req navigationType:(UIWebViewNavigationType)navigationType {
self.title = req.URL.description;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = req.URL;
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
    self.fileURLPath = [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];
    return self.fileURLPath;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];

return YES;

}
Now that you have the fileURLPath you can create the UIDocumentInteractionController like so:
documentController = [UIDocumentInteractionController interactionControllerWithURL:self.fileURLPath];


text:
Q: Cutting a video with FFmpeg produces audio-only output I have to extract some small clips with FFmpeg but the movie produced has no video but only audio even if it is correctly an mp4 file.
Command:
ffmpeg -i ORIGINAL.mp4 -ss 5.263 -t 2.085 -y -avoid_negative_ts 1 -c copy OUTPUT.mp4

There was no output error from the console.
Here is the image of the files:

The generated mp4 file has only audio and no video.
What is the problem?

A: Video can only be spliced at keyframes. If there is no keyframe at -t 2.085, this operation can not be completed. You must transcode the video to covert the frame at -t 2.085 into a keyframe. e.g.
ffmpeg -i ORIGINAL.mp4 -ss 5.263 -t 2.085 -y -avoid_negative_ts 1 -acodec copy OUTPUT.mp4


text:
Q: where is the client-side EaselJS file? Here is (more or less) the text in a sample script tag for EaselJS:
'script src="https://code.createjs.com/easeljs-0.8.2.min.js">

Note the file name: easeljs-0.8.2.min.js
But...when I download EaselJS from GitHub I can't find the equivalent file. The closest I can come is this: easeljs-NEXT.min.js.
I want to point to a client-side script, so that I can work off-line. Like this:
"script src='easeljs-0.8.2.min.js'' /script"
In the downloaded files from GitHub, which file is the correct one to point to in the src attribute for local use?

A: Have you gone to https://code.createjs.com? There are links to download all the versions of EaselJS libs.
You can also get the latest compiled libs in the lib/ folder on GitHub, or download any of the releases here: https://github.com/CreateJS/EaselJS/releases


text:
Q: In react.js how can you asynchronously assign source attribute for video.js object My knowledge gap is understanding how to use async properly to have the correct value for attribute 'src' of object 'const videoJsOptions'.
import React, { useEffect, useState } from 'react';
import VideoPlayer from "./VideoPlayer";
import Amplify, { Storage } from 'aws-amplify';

function VideoPlayerPage () {
    const [state, setState] = React.useState({ vidSrc: "" })

    useEffect(() => {
        async function getURI() {
        try {
            const value = await Storage.get("andy_2020_something_description.mp4");
                    console.log(value);
            setState({ vidSrc: value });
        } catch (error) {
      console.log(error);
          }
        }
        getURI();
    }, [] );

    const videoJsOptions = {
        autoplay: true,
        controls: true,
        sources: [{
// If I replace the reference to state on the line below with a string of the URL then the video.js player will work fine.
            src: state.vidSrc,
            type: 'video/mp4'
        }]
    }

    return (
        <div>
            <h1> value of state: { state.vidSrc } </h1>
            <VideoPlayer {...videoJsOptions} />
        </div>
    )
}

export default VideoPlayerPage

So what is rendered/displayed on the page by the line:

 value of state: { state.vidSrc }

is a perfectly valid URL. If I hardcode this URL as a string to replace the variable on line:

src: state.vidSrc,
then the video.js player works fine.

I'm thinking that 'const videoJsOptions' may be passed to the VideoPlayer Component too early, but I cannot figure out how to fix this, that is, have it wait until later such as when the line:

 value of state: { state.vidSrc }

is displayed.
Ideas to debug further are greatly appreciated.

A: why dont you do a conditional rendering,
 { state.vidSrc && <VideoPlayer {...videoJsOptions} /> }

this would ensure that the player is only rendered after the correct value is available


text:
Q: The integral expression for stretch/similarity theorem of Fourier transform The integral expression for stretch/similarity theorem of Fourier transform, which is
$\displaystyle \mathcal{F}_x[f(ax)](y)=\int^\infty_{-\infty}f(ax)\exp\left(-2\pi iyx\right) \,dx$
But the definition of Fourier transform is
$\displaystyle \mathcal{F}_x[f(x)](y)=\int^\infty_{-\infty}f(x)\exp\left(-2\pi iyx\right) \,dx$
My question is why the expression is not in the form
$\displaystyle \mathcal{F}_x[f(ax)](y)=\int^\infty_{-\infty}f(ax)\exp\left(-2\pi iy(ax)\right) \,d(ax)$

A: It's somewhat ambiguous notation. Think of it like this: define the stretch operator $S_a$ by $$(S_af)(x) = f(ax).$$
The stretch similarity theorem is a statement about the Fourier transform of $S_af$:
$$
\mathcal{F}_x[(S_af)(x)](y) = \int_{-\infty}^\infty (S_af)(x)e^{-2\pi iyx}~dx,
$$
which your author has chosen to express in the equivalent form
$$
\mathcal{F}_x[f(ax)](y) = \int_{-\infty}^\infty f(ax)e^{-2\pi iyx}~dx.
$$


text:
Q: Computer Vision: Simple Question - what are 'side lobes'? This is a very trivial question!!
In some computer vision literature, side-lobes are mentioned.. what are they?.... Can't seem to find anywhere that actually says what they are :S.
Thanks :).

A: This is a term from antenna theory. Antennas broadcast radiation (radio, microwave, light, infrared) in a certain pattern. Generally, there will be a preferred direction and most of the energy will be in that 'main lobe'. However, there generally exists secondary directions ('side lobes') of energy transmission. Some times, side lobes are a not ideal and are engineered to a minimum. Other times, side lobes can be an advantage and are enhanced.
Bob

A: Did a quick google search
Byt it seams like the wiki page mentioned i also relevant along with
http://en.wikipedia.org/wiki/Spectral_leakage
I assume its a way of finding noice.


text:
Q: mPDF (PHP) does not recognize html check mark I am showing a table in HTML on my web page where a check mark is shown properly (I am using ✔ for the bold check mark).
I am using classic-asp to display the HTML. The html buildup (tableOutput) is then posted to a PHP script ($output = $_POST["output"]) that uses mPDF.php (version 6.0) to print to PDF the same HTML table and somehow the check mark wont print correctly (%u2714 in printed on my PDF). All the rest of the table is printed correctly, only the check mark has a problem.
I tried adding the Symbola.ttf and Symbola_hint.ttf fonts in the mpdf\ttfonts folder but it didnt do the trick.
HTML (classic-asp):
tableOutput = tableOutput & "✔	"

PHP (create_report_pdf.php):
$output = $_POST["output"];  //This is the html buildup tableOutput discussed previously
$header = Irrelevant;
$footer= Irrelevant;

$mpdf = new mPDF( 'utf-8', 'A4-L', 0, '', 5, 5, 20, 20);
$mpdf->allow_charset_conversion = true;
$mpdf->WriteHTML($style,1);
$mpdf->SetHTMLHeader( $header );
$mpdf->SetHTMLFooter( $footer );
$mpdf->WriteHTML( $output );
$mpdf->Output($temp ,'F' );

config_fonts.php (I addded symbola.ttf and Symbola_hint.ttf in the mpdf\ttfonts folder):
$this->fontdata = array (
        "symbola"  => array (
                'R' => "Symbola.ttf",
                'I' => "Symbola_hint.ttf",
        ),

CSS (PHP $style variable points to create_report_pdf.css):
.report-table{
    border: 1px solid black;
    border-collapse: collapse;
    font-size: 7pt;
    width: 100%;
}

th,td{
    font-size: 7pt;
    border: 1px solid black !important;
    vertical-align : middle;
}

.center{ text-align: center; vertical-align: middle; }

INPUT{
    border-color:#ffffff !important;
}

.pf{ width: 45px; }
.fix-cell{ width: 90px; }
.dr-column, .dr-input{ width: 100px; }
.comments, .comments-input{ width: 130px; }

Thank you very much for your help

A: There are two possible solutions:

*

*Replacing manually the %u2714 with the respective html entity ✔ by doing the following:

$output = str_replace('%u2714', '✔', $output);

*

*Implement more generic approach that will handle all such special chars. The approach is based on the fact that %uXXXX is a non-standard notation scheme for URL-encoding Unicode characters. So you need to convert %uXXXX notation to HTML entity notation &#xXXXX; and then this can be decoded to actual UTF-8 by html_entity_decode.

$output = preg_replace('/%u([0-9A-F]+)/', '&#x$1;', $output);
$output = html_entity_decode($output, ENT_COMPAT, 'UTF-8');


text:
Q: How to sort by key in Java? I have date in this format:
Key        Value
13:00:08 : 3
13:00:08 : 2
13:00:08 : 2
13:00:06 : 2
13:00:08 : 2
13:00:09 : 1
13:00:07 : 2
13:00:09 : 3

I convert the timestamp to seconds. Then based on the timestamp, I have to sort the data.
I tried using TreeMap but it removes duplicates. I tried HashMap but it removes the duplicates. MultiMap will not work here.
Code which I tried was :
Map<Integer, Integer> map = new TreeMap<Integer, Integer>(tmap);
        System.out.println("After Sorting:");
        Set set2 = map.entrySet();
        Iterator iterator2 = set2.iterator();
        while(iterator2.hasNext()) {
            Map.Entry me2 = (Map.Entry)iterator2.next();
            System.out.print(me2.getKey() + ": ");
            System.out.println(me2.getValue());
        }

How can I proceed with the sorting?

A: Sounds like you just want a list.
Encapsulate the time and the value in an object, and process a list of these objects. You can then sort the list by time.
public class TimeValue {
    LocalTime time;
    int value;

    public TimeValue(LocalTime time, int value) {
        this.time = time;
        this.value = value;
    }

    public LocalTime getTime() {
        return time;
    }

    public static void main(String[] args) {
        List<TimeValue> timeValues = new ArrayList<>();
        timeValues.add(new TimeValue(LocalTime.of(13, 0, 8), 3));
        timeValues.add(new TimeValue(LocalTime.of(13, 0, 8), 2));
        timeValues.add(new TimeValue(LocalTime.of(13, 0, 8), 2));
        timeValues.add(new TimeValue(LocalTime.of(13, 0, 6), 2));
        timeValues.add(new TimeValue(LocalTime.of(13, 0, 8), 2));
        timeValues.add(new TimeValue(LocalTime.of(13, 0, 9), 1));
        timeValues.add(new TimeValue(LocalTime.of(13, 0, 7), 2));
        timeValues.add(new TimeValue(LocalTime.of(13, 0, 9), 3));

        timeValues.sort(Comparator.comparing(TimeValue::getTime));

        System.out.println(timeValues);
    }

    @Override
    public String toString() {
        return this.time + ": " + this.value;
    }
}

The reason why a List is preferable to a Map is that in your case the time is not unique; it can therefore not be used as a key.

A: So for the sample you posted, the actual problem is creating the tmap in your code sample. That's pretty much just parsing the data.
Map<LocalTime, List<Integer>> result = new TreeMap<>();
try (Scanner fileScanner = new Scanner(yourFile)) {
    while (fileScanner.hasNext()) {
        try (Scanner lineScanner = new lineScanner(fileScanner.nextLine())) {
            LocalTime time = DateTimeFormatter.ISO_LOCAL_TIME.parse(lineScanner.next());
            // skip the ":"
            lineScanner.next();
            int value = lineScanner.nextInt();
            // use the list for this time or create a new one if none is present
            List<Integer> valueList = result.computeIfAbsent(time, d -> new ArrayList<>());
            valueList.add(value);
        }
    }
}


text:
Q: How do I solve Raspberry Pi 2 / Tensorflow Allocation of 5031936 exceeds 10% of system memory error? I am trying to detect humans in a video frame using tensorflow object detection api and raspberry pi 2.The video input is from an ip camera.
I get the following error when I run my code.
2019-04-07 13:57:17.996374: W
tensorflow/core/framework/allocator.cc:124] Allocation of 5660928
exceeds 10% of system memory.
2019-04-07 13:57:18.096145: W
tensorflow/core/framework/allocator.cc:124] Allocation of 25159680
exceeds 10% of system memory.
2019-04-07 13:57:18.208663: W
tensorflow/core/framework/allocator.cc:124] Allocation of 10063872
exceeds 10% of system memory.
2019-04-07 13:57:18.260229: W
tensorflow/core/framework/allocator.cc:124] Allocation of 5031936
exceeds 10% of system memory.
2019-04-07 13:57:18.293027: W
tensorflow/core/framework/allocator.cc:124] Allocation of 5031936
exceeds 10% of system memory.
Killed

I followed this tutorial to install tensorflow and opencv on my pi
https://www.youtube.com/watch?v=npZ-8Nj1YwY
This is the code that I am using
import numpy as np
import tensorflow as tf
import cv2
import time

class DetectorAPI:
def __init__(self, path_to_ckpt):
    self.path_to_ckpt = path_to_ckpt

    self.detection_graph = tf.Graph()
    with self.detection_graph.as_default():
        od_graph_def = tf.GraphDef()
        with tf.gfile.GFile(self.path_to_ckpt, 'rb') as fid:
            serialized_graph = fid.read()
            od_graph_def.ParseFromString(serialized_graph)
            tf.import_graph_def(od_graph_def, name='')

    self.default_graph = self.detection_graph.as_default()
    self.sess = tf.Session(graph=self.detection_graph)

    # Definite input and output Tensors for detection_graph
    self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
    # Each box represents a part of the image where a particular object was detected.
    self.detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
    # Each score represent how level of confidence for each of the objects.
    # Score is shown on the result image, together with the class label.
    self.detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
    self.detection_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
    self.num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')

def processFrame(self, image):
    # Expand dimensions since the trained_model expects images to have shape: [1, None, None, 3]
    image_np_expanded = np.expand_dims(image, axis=0)
    # Actual detection.
    start_time = time.time()
    (boxes, scores, classes, num) = self.sess.run(
        [self.detection_boxes, self.detection_scores, self.detection_classes, self.num_detections],
        feed_dict={self.image_tensor: image_np_expanded})
    end_time = time.time()

    print("Elapsed Time:", end_time-start_time)

    im_height, im_width,_ = image.shape
    boxes_list = [None for i in range(boxes.shape[1])]
    for i in range(boxes.shape[1]):
        boxes_list[i] = (int(boxes[0,i,0] * im_height),
                    int(boxes[0,i,1]*im_width),
                    int(boxes[0,i,2] * im_height),
                    int(boxes[0,i,3]*im_width))

    return boxes_list, scores[0].tolist(), [int(x) for x in classes[0].tolist()], int(num[0])
def close(self):
    self.sess.close()
    self.default_graph.close()

if __name__ == "__main__":
model_path ='/home/pi/tensorflow1/models/research/object_detection/ssd_mobilenet_v2_coco_2018_03_29/frozen_inference_graph.pb'
odapi = DetectorAPI(path_to_ckpt=model_path)
threshold = 0.7
cap = cv2.VideoCapture('rtsp://vamshi@123:vikas123@192.168.0.5:88/videoMain')

while True:
    r, img = cap.read()
    img = cv2.resize(img, (500, 400))
    cv2.line(img,(0,400 // 2),(500 ,400 // 2),(0,255,255),2)
    cv2.line(img,(500 // 2,0),(500 // 2,400),(0,255,255),2)
    boxes, scores, classes, num = odapi.processFrame(img)

    # Visualization of the results of a detection.

    for i in range(len(boxes)):
        # Class 1 represents human
        if classes[i] == 1 and scores[i] > threshold:
            box = boxes[i]
            cv2.rectangle(img,(box[1],box[0]),(box[3],box[2]),(255,255,0),2)
            cX=int((box[1] + box[3]) / 2.0)
            cY=int((box[0] + box[2]) / 2.0)
            cv2.circle(img,(cX,cY),4,(0,255,0),-1)
            if cX < 500 // 2 and cY < 400 //2:
                print ('Quadrant 1')
            elif cX < 500 // 2 and cY > 400 //2:
                print ('Quadrant 3')
            elif cX > 500 // 2 and cY < 400 //2:
                print ('Quadrant 2')
            else:
                print ('Quadrant 4')

    cv2.imshow("Human Detection", img)
    key = cv2.waitKey(1)
    if key & 0xFF == ord('q'):
        break

Tensorflow version:1.13.1
OpenCV version:3.4.4


text:
Q: How to change the wrapped action call during action composition in play framework 2.0 From what I understand of Action composition, we can wrap multiple action classes around an action class so that the wrapped classes are called first before the action action class
so, for eg:
@With(a.class, b.class)
public static Result index() {
  return ok("It works!");
}

public static Result logout(){
  session().clear();
}

Any call to index will first go through the call() methods of a & b. The key thing here is that at some point of time, the control needs to be delegated to the index() method.
My question is; is it possible to change the call from index to logout in either a or b.
I tried calling controller.Application.logout() instead of delegate.call but the logout method doesnt get a handle on the context. Any ideas?

A: I don't believe you can change the method the call gets delegate back to, but you can just do a redirect to your logout route.
if (...)
   return delegate.call(ctx);
else
   return redirect(routes.Controller.logout()); //reverse-route to your logout() method

Alternatively, I think you could do something like this where you pass the Context to your logout method.
// -- Action.class
return Controller.doLogout(ctx);

// -- Controller.java
public static Result logout()
{
  // defined in your routes file but it just calls doLogout
  return doLogout(ctx());
}

public static Result doLogout(Context ctx)
{
  // this method does your actual "logout" process
  ctx.session().clear();
  return ...;
}


text:
Q: How to get started in The Castle Doctrine? I'm a bit at a loss. Sure, the basic concept is booby-trapping one's own house sufficiently such that no one can harm your family or steal from your vault, while trying to save some money so one can afford the tools to bypass other homes' defences. But what is a simple setup for starters?

A: Your $2000 starting cash is enough to buy a small combination of home defense structures. I like to buy a pair of pit bulls and put them in hallways such that a successful route to the vault has one or both chasing you the entire way. I put in a bunch of doors with dead ends behind them, and some battery-switch-grate combos that form a commitment trap in front of one or two sets of dead ends, and finally I buy a shotgun for the wife.
If your traps are clever enough, you'll quickly start earning some cash from dead invaders, but this starting layout is not remotely sufficient for anyone who sank their entire 2k into tools, so the sooner you can earn enough to buy a pit trap or two, the better.
I strongly recommend finding videos like this one from YouTube user Aavak to give you a better idea for home defense basics:


text:
Q: Faraday Gem Update locked because of Oauth2 I was trying to update Faraday Gem to 0.12.0.
However, I ended up being as same since oauth2 gem has a dependency on Faraday
(<0.10, >=0.8) [It says bundler has locked Faraday at 0.9.0]
The "gem A" I wanted to install requires Faraday with version 0.12.
How am I going to install 0.12.0 Faraday so that I can install "gem A" and also leave Oauth2 working?
How does the decision normally get made when it comes to the gem dependency issue?
(If it had not been limited by inequality, then things would have been straight forward though, but nothing I can help on the gem creation )

A: You can use FaradayMiddleware::OAuth2Refresh and install the gem:
gem 'faraday_middleware-oauth2_refresh'