text:
Q: syntax error: unexpected $end at token "" GLSL with any shader I've seen other similar questions, and I now that it's usually due to wrong shader loading code, but I've tried with lots of different ways to load them, and I always get this error. Here is the loading code I'm currently using (for the Vertex shader, i do the same for the fragment shader):
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
std::string VertexShaderCode;
std::ifstream VertexShaderStream(vertex_file_path, std::ios::in);
if(VertexShaderStream.is_open()){
    std::string Line = "";
    while(getline(VertexShaderStream, Line))
        VertexShaderCode += "\n" + Line;
    VertexShaderStream.close();
}
GLint Result = GL_FALSE;
int InfoLogLength;

// Compile Vertex Shader
printf("Compiling shader : %s\n", vertex_file_path);
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);

// Check Vertex Shader
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
std::vector<char> VertexShaderErrorMessage(InfoLogLength);
glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]);

I've also tried this:
    GLuint VertexShaderID = glCreateShader(GL_FRAGMENT_SHADER);
    std::ifstream shaderFile(vertex_file_path);
    //Error out here.
    stringstream shaderData;
    shaderData << shaderFile.rdbuf();  //Loads the entire string into a string stream.
    shaderFile.close();
    const std::string &VertexShaderCode = shaderData.str(); //Get the string stream as a std::string.
    GLint Result = GL_FALSE;
    int InfoLogLength;
    printf("Compiling shader : %s\n", vertex_file_path);
    char const * VertexSourcePointer = VertexShaderCode.c_str();
    glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
    glCompileShader(VertexShaderID);

    // Check Vertex Shader
    glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
    glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    std::vector<char> VertexShaderErrorMessage(InfoLogLength);
    glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
    fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]);

And this is the linking code:
// Link the program
fprintf(stdout, "Linking program\n");
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);

// Check the program
glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
std::vector<char> ProgramErrorMessage( max(InfoLogLength, int(1)) );
glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
fprintf(stdout, "%s\n", &ProgramErrorMessage[0]);

I have also tried passing (GLint *)VertexShaderCode.size() instead of NULL to the length parameter of glShaderSource(), but I get the same errors. I get those errors both when compiling and when linking
In case it helps, I'm using Opengl 3.3, GLEW, GLFW, Visual c++ 2010, and windows 7 64 bits

A: How did you pass the length parameter to glShaderSource. The typecast you performed should trigger you a thick fat warning. The proper way would have been to put the result of size() into a variable. And then you give the pointer to that variable to glShaderSource.


text:
Q: Disprove if $a_n$ converges then $a_{n+1}/a_n$ converges
Disprove: if $a_n$ converges then $a_{n+1}/a_n$ converges.

I want to disprove this statement but I couldn't find a sequence that disproves it.
Further more it will be really helpful to know what are the things to look for in those kind of questions.

A: Hint: We could try $ 1, , 1, -1, -1, 1, 1, -1, -1, \ldots$ but the sequence doesn't converge.
The ratio is $  1, -1, 1, -1, \ldots$ which doesn't converge.
Modify it so that the sequence converges, but the ratio doesn't.

Things to look for

*

*What could make the ratio not converge? Could we make it arbitrarily large?

*If $ a_n \rightarrow L \neq 0$, prove that $ \frac{ a_n } { a_{n-1}} \rightarrow 1$. (This should be obvious after playing around with it for a while.)

*Hence, if we want a counter example, what must be true of $ L$?

*So we know now that $ a_n \rightarrow 0$. Can the ratio of small terms be arbitraily large?

A: Let
$$a_n = \begin{cases}
\frac{1}{n} & \text{if }n\text{ is even} \\
\frac{1}{n^2} & \text{if }n\text{ is odd} \\
\end{cases}$$
Then $a_n \to 0$, but
$$\frac{a_{n+1}}{a_n} = \begin{cases}
\frac{n}{(n+1)^2} < \frac{1}{n} & \text{if }n\text{ is even} \\
\frac{n^2}{n+1} \geq \frac{n}{2} & \text{if }n\text{ is odd} \\
\end{cases}$$
Hence $\lim a_{n+1}/a_n$ does not exist.

A: If a sequence, $b_n$, is equidistributed in $[-1, 1]$ (or a smaller interval), then $a_n = \prod_{k=1}^n b_k$ would converge to $0$, while $\frac{a_{n+1}}{a_n} = b_{n+1}$ does not converge.
For example, take $b_n = \sin(n) \to a_n = \prod_{k=1}^n \sin(k)$. Then $a_n \to 0$, but $\lim_{n \to \infty}\frac{a_{n+1}}{a_n}$ does not exist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to install apache Jmeter on PKS (pivotal-container-service) I want to install Apache Jmeter on PKS (pivotal-container-service) for testing micro service on PCF.
I am not able to find any good resources ,did anyone tried and got success?

*

*https://hub.docker.com/r/justb4/jmeter/

*https://www.virtuallyghetto.com/2018/03/getting-started-with-vmware-pivotal-container-service-pks-part-1-overview.html

*https://network.pivotal.io/products/pcfdev

A: Looking into Pivotal Container Service main page

Production-ready Kubernetes for the enterprise

So Pivotal Container Service seems to be using Kubernetes under the hood.
The process of installation of JMeter into Kubernetes and/or Pivotal Container Service would be as easy as creating an Image with your own Docker JMeter installation (or use any existing one) and using this image in the PCS.


text:
Q: Reformatting HTML table - Align and Resizing cells
*

*Align the outer (formatting) table cells with content starting in the top left corner of the cells. Set the two columns to equal width.

*Align the cells (in ) in the nested table (use tag to identify only the inner table) to be centered in the middle.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Jake's Schedule</title>
        <link rel="stylesheet" type="text/css" href="Web4.css"/>

Jacob Martin

This table shows my Fall Semester of classes

                Hometown:

 Pulaski, WI
I have lived there for 19 years

                Education:

                 Soon to have Associates for CS
UW Fox Valley 2015 for Associates
BA at UW Stout

My Favorites

Musicians

Limp Bizkit

Kid Rock

Hobbies

Running

Video Games

Websites

IGN

N4G

WWE Network

                Monday
                Tuesday
                Wednesday
                Thursday
                Friday

                8:00-
8:59

Ethics
                Data Structors
                Ethics
                Data Structors
                Ethics

                9:00-
9:59

study
                study
                study

                10:00-
10:59

Calculas II

                11:00-
11:59

study

                12:00-
12:59

study

                1:00-
1:59

study

                2:00-
2:59

study

                3:00-
3:59

Linear Algebra
                study
                Linear Algebra
                study
                Linear Algebra

My goals goals for this Summer is to learn how to make webpages with HTML.
 I also want to learn more about Computer Programming in general.
 I have 4 classes and I want to be ready for my website job this fall.

a² + b² = c²

½ > ¼ & 0° C < 33° F

Can I get an explanation of 1 and 2. How can i solve it? I am assuming in 1 that it meant to make the width equal which i did in CSS. If that's the case can someone explain 2.


text:
Q: When exactly is the autoloader called? I have an autoloader that is registered using spl_autoload_register():
class MyAutoLoader{
   public function __construct(){
       spl_autoload_register(array($this, 'loader'));
   }

   public function loader($className){
       var_dump($className);
   }
}

$al = new MyAutoLoader(); //Register the autoloader

From the var_dump(), the autoloader seems to be called on lots of things, things that are data to be inserted into a database, parameterized SQL queries and what not:
string 'name' (length=4)

string 'a:2:{s:5:"label";s:4:"Name";s:8:"required";b:1;}' (length=48)

string 'en_US' (length=5)

string 'object' (length=6)

string 'name = ?' (length=8)

These things will never be classes so should never be loaded using new or class_exists(), etc.
Under what circumstances/function calls are autoloaders called? I would like to put a stop to autoloading "classNames" that are not classes from being called, because each $className is checked using file_exist(), and having these data strings checked is pretty inefficient.

Problem resolved. I first did a back trace as suggested by Brad and dumped the traces to a file (just add a small snippet that opens a file and appends to it).
Obviously, the trace was very big, but I picked the simplest one I could find. Incidentally, that trace happened to be one that called a database (ORM) wrapper I have written to wrap around the awesome RedBean ORM library. The results from me dumping $className also validates that, because those strings are data are going into or coming out of the database.
Having said that, I have a __call() that intercepts methods to my database wrapper, does some processing, pass it to RedBean, process the result, and then sends it back to the caller.
Problem: During the processing, I am making calls to is_subclass_of() and instanceof, which will obviously ask the autoloader to try and load the class (since we don't have any class called name =? loaded, nor does it exist).
The solution was to actually make sure we have an object before calling is_subclass_of() and instanceof: if(is_object($someproperty) && is_subclass_of($someproperty)).
If $someproperty is not an object, the if immediately short-circuits and instanceof and is_subclass_of() is never called, which means the call to the autoloader is never made.
As mentioned by brad, having all sorts of things going to the autoloader to be included using require_once can be a huge security risk and at the same time, hitting the file system so many times using file_exists() is pretty inefficient too.
So, in conclusion, the autoloader is called every time you use instanceof, is_subclass_of, other class-type functions, class-exist functions and reflection methods, as Charles motioned in his answer.
So, the moral of the story is that if you plan to use a class-type function, or any of the functions mentioned above on a variable of mixed type, check it first before passing it to the class-type function.

A:
Under what circumstances/function calls are autoloaders called?

I realize that this has ended up basically being a secondary question given the problems noted in the comments, but it's still worth answering.
Autoload functions, that being a __autoload() function in your code or callbacks registered through spl_autoload_register, are called when -- and only when -- PHP needs to access a class that has not been defined.  This is done everywhere with few exceptions, such as class_exists, which have arguments that tell PHP not to call any autoloaders.
The PHP manual has a page dedicated to autoloading.  I recommend reviewing it if there's any confusion.

A: You can use debug_backtrace or debug_print_backtrace to find out where exactly the auto-loader function is being called.
Technically it should only be called by PHP when a script references a class name that does not exist.


text:
Q: How to create FunctionCall statement with arguments and add in function I need to create FunctionCall statement like Utiliy.initialize("value") and add this in first line of every function of js file.
Below is the code using which I am trying to create FunctionCall
private FunctionCall getFunctionCall() {
        FunctionCall functionCall = new FunctionCall();
        Name name =  new Name();
        name.setIdentifier("initialize");
        functionCall.setTarget(name);
}

below is the code I am using to add in every functionNode
class FunctionVisitor implements NodeVisitor {
        @Override
        public boolean visit(AstNode node) {
             if (node.getClass() == FunctionNode.class) {
                FunctionNode fun = (FunctionNode) node;
                fun.addChildrenToFront(getFunctionCall());
            }
            return true;
        }

    }

Please suggest how I can create FunctionCall with arguments and how I can print created FunctionCall statement to test.
Is there any tool available to view javascript nodes like java ASTVIEW viewer?

A: You have to create StringLiteral as a argument and add it to functionCall, in othere case it could be NumberLiteral, ArrrayLiteral etc. (see: http://javadox.com/org.mozilla/rhino/1.7R4/org/mozilla/javascript/ast/AstNode.html)
private FunctionCall getFunctionCall() {
        FunctionCall functionCall = new FunctionCall();
        Name name =  new Name();
        name.setIdentifier("initialize");
        functionCall.setTarget(name);
        StringLiteral arg = new StringLiteral();
        arg.setValue("value");
        arg.setQuoteCharacter('"');
        functionCall.addArgument(arg);
        return functionCall;
}

class FunctionVisitor implements NodeVisitor {
        @Override
        public boolean visit(AstNode node) {
             if (node.getClass() == FunctionNode.class) {
                FunctionNode fun = (FunctionNode) node;
                if(fun.getName().equals("initialize")) //prevents infinit loop
                {
                     return true;
                }
                fun.getBody().addChildrenToFront(new EmptyStatement()); // adds ';', I don't know if required
                fun.getBody().addChildrenToFront(getFunctionCall());//no fun.addChildrenToFront
            }
            return true;
        }

    }

You can print every corect AstNode by toSource() method. I hope this will help.


text:
Q: How to integrate programs written in different programming languages? I have two developers in my team. One will develop a Python application, the other will develop a Java application. The Java app generates a boolean value which is used by the Python app.
How can I integrate these applications? I have thought about using:

*

*Return codes: Python app calls the Java app, then the Java app uses
the return code to inform the boolean value.

*Sockets: Connect both
applications through sockets and exchange information. I think this
is overkill.

*Files: The Java app does its stuff, writes the output to
a file, then the Python app reads this file and retrieves the boolean
value it needs.

Any other suggestions? I'm not just looking for a solution, I'm also considering here aspects such as code organization and "beauty" of the overall solution.

Edit 1:
Thank you @user2387370 for the recommendation of using Jython, but I can't use it.

Edit 2: Thank you @RickyA, I'll have a look at messaging systems (such as zeromq, which you mentioned).

A: Use a messaging system like zeromq. That has libraries for both languages and allows you to integrate them seamlessly.
Your proposed options will get clunky interoperability. (filelocks, dead sockets, dead processes etc..)
Also this page lists some tools that can be used for pyton/java interop. I can't recommend one since I used none.


text:
Q: Adobe Reader: Links to third party protocol not working I have some PDF files with hyperlinks to a third-party protocol (ie. other than http://, https://, mailto:// and file://).
The links are on the form pw://xxxx.xxx.xxx
They open a document handling system on the client PC.
These worked fine in Reader version 9, but in versiosn X and XI I get a security block on them.
I have tried all security setting and trust manager settings, but nothing seems to address the problem.
Anybody got ideas or experience with this?
Regards
Leif


text:
Q: Cordova-Cloudinadinary plugin command I was try to add plugin for cordova-cloudinary through following command and not support.Kindly update the command for add cloudinary plugin in cordova web site.
cordova plugin add cordova.plugins.cloudinary
but it shows the error. 404not found.

A: I couldn't find the plugin you referred to.
If you refer to https://github.com/collectmeaustralia/cordova-cloudinary-upload, then they have specific instructions on how to install their plugin.


text:
Q: Beamer with multirow and multicolumn error I get the error "Package array Error: Empty preamble: `l' used.".  Any help would be appreciated.
\documentclass[12pt]{beamer}

\usetheme{metropolis}

\usepackage[T1]{fontenc}
\usepackage{tikz}
\usepackage[french]{babel}
\usepackage{pifont}
\usepackage{array}
\usepackage{multirow}
\usepackage{xfunctions}
\usepackage{algorithm2e}
\usepackage{booktabs}
\usepackage[backend=biber,style=authoryear]{biblatex}

\begin{document}
\begin{frame}{Maximization}
\begin{block}{Experiments}
\newcommand{\Cm}{$C_{\text{\tiny min}}$}
\newcommand{\Fm}{$F_{\text{\tiny max}}$}
\begin{table}
  \centering
    \setlength{\tabcolsep}{2.5pt}
  \begin{tabular}{l@{\ }c*{13}{c}}
        \toprule
        \multicolumn{2}{l}{Baseline}
        & \multicolumn{2}{c}{SM} && \multicolumn{4}{c}{SV} && \multicolumn{4}{c}{LR} \\
        \cmidrule(lr){3-4} \cmidrule(lr){6-9} \cmidrule(lr){11-14}
        \multicolumn{2}{l}{Options}
        & -- & \scshape t && -- & \scshape t & \scshape cs & \scshape cs{\scriptsize\&}t && -- & \scshape t & \scshape cs & \scshape cs{\scriptsize\&}t \\
        \midrule
        \multicolumn{1}{l}{\multirow{2}{*}{cv}} & \Cm & 48.2 & 49.6 && 47.6 & 49.7 & 49.9 & \textbf{50.2} && 46.3 & 49.8 & 49.9 & 49.9 \\
        \multicolumn{1}{}{} & \Fm & 42.8 & 44.7 && 47.6 & 44.1 & 49.2 & 44.2 && 46.4 & 44.3 & 49.3 & 44.5 \\
        \hline
        \multicolumn{1}{l}{\multirow{2}{*}{Sc}} & \Cm & 66.7 & 68.5 && 65.4 & 68.7 & 68.8 & 68.6 && 66.6 & 69.2 & 68.6 & \textbf{69.4} \\
        \multicolumn{1}{}{} & \Fm & 66.6 & 68.3 && 65.2 & 68.3 & 68.3 & 68.3 && 66.4 & 69.2 & 68.6 & 68.8 \\
        \hline
        \multicolumn{1}{l}{\multirow{2}{*}{Si}} & \Cm & 59.2 & 62.5 && 60.3 & 62.2 & \textbf{62.6} & 62.5 && 60.2 & 62.4 & 62.0 & 62.3 \\
        \multicolumn{1}{}{} & \Fm & 59.2 & 62.0 && 60.1 & 62.0 & 62.3 & 62.2 && 59.0 & 61.8 & 61.9 & 62.0 \\
        \hline
        \multicolumn{1}{l}{\multirow{2}{*}{Ye}} & \Cm & 61.8 & 65.1 && 64.1 & 64.8 & \textbf{65.6} & 65.2 && 63.3 & 64.9 & 65.3 & 64.9 \\
        \multicolumn{1}{}{} & \Fm & 60.2 & 60.2 && 60.6 & 59.3 & 60.7 & 61.2 && 63.2 & 59.8 & 61.0 & 60.9 \\
        \bottomrule
  \end{tabular}
\end{table}
\end{block}
\end{frame}
\end{document}

A: I don't have the package xfunctions, so I tried without. If I change all the \multicolumn{1}{}{} to \multicolumn{1}{l}{} your example compiles:
\documentclass[12pt]{beamer}

%\usetheme{metropolis}

%\usepackage[T1]{fontenc}
\usepackage{tikz}
\usepackage[french]{babel}
\usepackage{pifont}
\usepackage{array}
\usepackage{multirow}
%\usepackage{xfunctions}
\usepackage{algorithm2e}
\usepackage{booktabs}
\usepackage[backend=biber,style=authoryear]{biblatex}

\begin{document}
\begin{frame}{Maximization}
\begin{block}{Experiments}
\newcommand{\Cm}{$C_{\text{\tiny min}}$}
\newcommand{\Fm}{$F_{\text{\tiny max}}$}
\begin{table}
  \centering
    \setlength{\tabcolsep}{2.5pt}
  \begin{tabular}{l@{\ }c*{13}{c}}
        \toprule
        \multicolumn{2}{l}{Baseline}
        & \multicolumn{2}{c}{SM} && \multicolumn{4}{c}{SV} && \multicolumn{4}{c}{LR} \\
        \cmidrule(lr){3-4} \cmidrule(lr){6-9} \cmidrule(lr){11-14}
        \multicolumn{2}{l}{Options}
        & -- & \scshape t && -- & \scshape t & \scshape cs & \scshape cs{\scriptsize\&}t && -- & \scshape t & \scshape cs & \scshape cs{\scriptsize\&}t \\
        \midrule
        \multicolumn{1}{l}{\multirow{2}{*}{cv}} & \Cm & 48.2 & 49.6 && 47.6 & 49.7 & 49.9 & \textbf{50.2} && 46.3 & 49.8 & 49.9 & 49.9 \\
        \multicolumn{1}{l}{} & \Fm & 42.8 & 44.7 && 47.6 & 44.1 & 49.2 & 44.2 && 46.4 & 44.3 & 49.3 & 44.5 \\
        \hline
        \multicolumn{1}{l}{\multirow{2}{*}{Sc}} & \Cm & 66.7 & 68.5 && 65.4 & 68.7 & 68.8 & 68.6 && 66.6 & 69.2 & 68.6 & \textbf{69.4} \\
        \multicolumn{1}{l}{} & \Fm & 66.6 & 68.3 && 65.2 & 68.3 & 68.3 & 68.3 && 66.4 & 69.2 & 68.6 & 68.8 \\
        \hline
        \multicolumn{1}{l}{\multirow{2}{*}{Si}} & \Cm & 59.2 & 62.5 && 60.3 & 62.2 & \textbf{62.6} & 62.5 && 60.2 & 62.4 & 62.0 & 62.3 \\
        \multicolumn{1}{l}{} & \Fm & 59.2 & 62.0 && 60.1 & 62.0 & 62.3 & 62.2 && 59.0 & 61.8 & 61.9 & 62.0 \\
        \hline
        \multicolumn{1}{l}{\multirow{2}{*}{Ye}} & \Cm & 61.8 & 65.1 && 64.1 & 64.8 & \textbf{65.6} & 65.2 && 63.3 & 64.9 & 65.3 & 64.9 \\
        \multicolumn{1}{l}{} & \Fm & 60.2 & 60.2 && 60.6 & 59.3 & 60.7 & 61.2 && 63.2 & 59.8 & 61.0 & 60.9 \\
        \bottomrule
  \end{tabular}
\end{table}
\end{block}
\end{frame}
\end{document}


text:
Q: Collapsable List - Display all title using multiline I am having trouble modifying the following code to make it display correctly on mobile, I copied it from W3 Schools collapsable lists tutorial and modified it correctly for desktop.
However on mobile half the writing gets cut off by an ellipsis.
Desktop

Mobile

Any and all help would be greatly appreciated.
Ideally I would like to make the title section span across multiple lines.
See below code for more information.

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Do I need to buy now?

No. Sign up for a free 30-day trial now. With NO obligations.

Is the free trial fully functional?

Yes. The free trial comes with all of S2L features. You can give it a test run before you buy.

Do I need a credit card to sign up for the trial?

No. We do not collect payment information until you are ready to buy.

Do you provide a discount for yearly plans?

     Yes. You save 10% if you choose to pay yearly.

How do I activate my trial to a paid version?

Once you have entered your payment information, you will receive an activation code by mail.

Enter the code into the application and you are ready to go.

A: Well right now it is using an ellipsis with white-space: nowrap; on the overflow rather than breaking to a new line. Give your text a white-space: normal;.
CSS:
#pageone > div a {
  white-space: normal;
}

#pageone > div a {
  white-space: normal;
}
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

This title is super long and will overflow to a new line instead of using an ellipsis.

    No. Sign up for a free 30-day trial now. With NO obligations.

This title is super long and will overflow to a new line instead of using an ellipsis.

    Yes. The free trial comes with all of S2L features. You can give it a test run before you buy.

This title is super long and will overflow to a new line instead of using an ellipsis.

    No. We do not collect payment information until you are ready to buy.

This title is super long and will overflow to a new line instead of using an ellipsis.

         Yes. You save 10% if you choose to pay yearly.

This title is super long and will overflow to a new line instead of using an ellipsis.

    Once you have entered your payment information, you will receive an activation code by mail.

    Enter the code into the application and you are ready to go.


text:
Q: How to print output from both files matched on one column? I have two files
 >vi cc4
163489921       ENSG00000145416
163490721       ENSG00000145416
163493030       ENSG00000145416
163494582       ENSG00000145416
163498263       ENSG00000145416
163506833       ENSG00000145416
163510223       ENSG00000145416
...

>vi bed_chr_4.bed
chr4    171975321       171975322       rs230   0       -
chr4    10204223        10204224        rs231   0       +
chr4    184363210       184363211       rs232   0       -
chr4    39547490        39547491        rs529   0       +
chr4    109740780       163489921       rs551   0       -
chr4    25929702        25929703        rs554   0       +
chr4    17624034        17624035        rs555   0       +
...

I would like to mach 1st column of cc4 and 3rd column of bed_chr_4.bed and print matched lines from bed_chr_4.bed plus matched 2nd column from cc4. The output that I want to get for this sample would be:
chr4    109740780       163489921       rs551   0       -     ENSG00000145416

I tried this:
awk 'NR==FNR{a[$1]=$1;next}a[$3]{print $0}' cc4 bed_chr_4.bed >outfile

but I am getting only 6 column matches from bed_chr_4.bed and not the 2nd column from cc4, which is in this case: ENSG00000145416
I am getting only this:
chr4    109740780       163489921       rs551   0       -

A: You are almost there. The problem is that you are assigning $1 to a[$1].
Please try instead:
awk 'NR==FNR{a[$1]=$2;next} a[$3]{print $0 " " a[$3]}' cc4 bed_chr_4.bed > outfile

Precisely, it relies on the assumption that the 2nd field of cc4 holds a value
which is evaluated to be true. It may be safer to say:
awk 'NR==FNR{a[$1]++;b[$1]=$2;next} a[$3] {print $0 " " b[$3]}' cc4 bed_chr_4.bed > outfile


text:
Q: How to Build Request Header - TLM Authentication - Using Spring RestTemplate We have a web service client that is making requests against restful web services that require NTLM-based authentication. We are using:
org.springframework.web.client.RestTemplate

To execute a GET request, we call:
RestTemplate.execute(java.lang.String,
org.springframework.http.HttpMethod,
org.springframework.web.client.RequestCallback,
org.springframework.web.client.ResponseExtractor<T>)

In the RequestCallback, we provide the header parameters (Map < String, String >)  that, among other things, provide the authentication mechanism as one of params.
I need to be able to build a authorization parameter of type "NTLM", but I do not know how to create the string properly to accommodate NTLM-based authentication. I have found information for creating an NTLM-based service, but I believe my needs as a client calling NTLM service are simpler. For example, we had been using basic authentication client (before service switched to NTLM) like this:
..
String str = username:password
headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8")));
..

How would I do the same as above, only with NTLM rather than basic?


text:
Q: Запись данных в .csv pandas Всем привет, мне надо записать данные в csv файл, сейчас занимаюсь парсингом интернет магазина, там на каждом товаре разное количество характеристик например: вес, длина и т.д
Пытаюсь записать данные с помощью pandas, но не могу правильно записать все данные в словарь, подскажите как правильно сделать
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import requests
import time
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import pandas as pd

URLS = ['https://www.ikea.com/ru/ru/p/pahl-pol-pismennyy-stol-belyy-s29278422/','https://www.ikea.com/ru/ru/p/micke-mikke-pismennyy-stol-belyy-20373923/']
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'}
content = []
colum = []
driver = webdriver.Chrome(ChromeDriverManager().install())

def get_html(url, params=None):
    r = requests.get(url, headers=HEADERS, params=params)
    return r

def get_specifications_parameter():
    num = 0
    WebDriverWait(driver, 5).until(expected_conditions.visibility_of_element_located((By.XPATH, '//*[@id="content"]/div/div[1]/div/div[2]/div[2]/div[2]/div[2]/button')))

    driver.find_element_by_xpath('//*[@id="content"]/div/div[1]/div/div[2]/div[2]/div[2]/div[2]/button').click()
    time.sleep(3)
    table = driver.find_element_by_xpath('//*[@id="range-modal-mount-node"]/div/div[4]/div/div[2]/div/div/div').get_attribute('innerHTML')
    soup = BeautifulSoup(table,'html.parser')

    param = soup.find_all('dd',class_='range-revamp-product-dimensions__list-item-measure')
    titles = soup.find_all('dt',class_='range-revamp-product-dimensions__list-item-name')
    for item in titles:
        if item.text in colum:
            pass
        else:
            colum.append(item.text)
    for item in param:
        content.append({titles[num].text:item.text}) #Запись характеристик в content
        num+=1
    print(content)

def get_content(url):
    driver.get(url)
    get_specifications_parameter()

    # content.append[{
    #     'name':name,
    #     'price':price,
    #     'photo':photo,
    #     'description':description
    #     }]
    #  Дополнительные данные которые будут записыватся
    print(content)

def start():
    for URL in URLS:
        html = get_html(URL)
        if html.status_code == 200:
            get_content(URL)
        else:
            print('Network error')

def write():
    df = pd.DataFrame(colum)
    for p in content:
        df = pd.concat([df, pd.DataFrame(p,index=[0])],ignore_index=True)
    df.to_csv("output.csv", index=False)

start()
write()

На выходе я получаю вот это, что совсем не правильно

[{'Ширина:\xa0': '128 см'}, {'Глубина:\xa0': '58 см'}, {'Мин
высота:\xa0': '59 см'}, {'Макс высота:\xa0': '72 см'}, {'Макс
нагрузка:\xa0': '50 кг'}] [{'Ширина:\xa0': '128 см'}, {'Глубина:\xa0':
'58 см'}, {'Мин высота:\xa0': '59 см'}, {'Макс высота:\xa0': '72 см'},
{'Макс нагрузка:\xa0': '50 кг'}] [{'Ширина:\xa0': '128 см'},
{'Глубина:\xa0': '58 см'}, {'Мин высота:\xa0': '59 см'}, {'Макс
высота:\xa0': '72 см'}, {'Макс нагрузка:\xa0': '50 кг'},
{'Ширина:\xa0': '73 см'}, {'Глубина:\xa0': '50 см'}, {'Высота:\xa0':
'75 см'}, {'Макс нагрузка:\xa0': '50 кг'}] [{'Ширина:\xa0': '128 см'},
{'Глубина:\xa0': '58 см'}, {'Мин высота:\xa0': '59 см'}, {'Макс
высота:\xa0': '72 см'}, {'Макс нагрузка:\xa0': '50 кг'},
{'Ширина:\xa0': '73 см'}, {'Глубина:\xa0': '50 см'}, {'Высота:\xa0':
'75 см'}, {'Макс нагрузка:\xa0': '50 кг'}]

В идеале хочу получить такую структуру

products = [{'артикул': 12345, 'высота': 50, 'материал': 'дерево'},
{'артикул': 12346, 'ширина': 30, 'вес':1.5},
{'артикул': 12347, 'длина':14, 'высота': 6.2, 'материал': 'пластик'}]

А то с тем что я сейчас имею у меня получается вот такой файл


text:
Q: knitr: Knitting to HTML - add a prefix to figure and table numbers R Markdown with knitr can add a prefix (usually a letter) to figure and table numbers when knitting/compling to PDF. When knitting to PDF, the following code will do the job:
```{=tex}
\renewcommand{\thetable}{S\arabic{table}}
\renewcommand{\thefigure}{S\arabic{figure}}
```

The result will be

Figure S1.1.

rather than

Figure 1.1

Is there a way to achieve the same when knitting to HTML?


text:
Q: Bash: Remove # from the beginning of the line if the line contains specified substring I have a file with dependencies. Some of the dependencies are commented (#). I want to uncomment the line, if it contains a substring cassandra.
So If file looks like:
firstdependency>=2.0.7 # comment
otherdependency>=0.8.9 # another comment
#commenteddependency
#cassandra-driver>=2.1.4,!=3.6.0 # Apache-2.0
anotherdependency!=0.18.3,>=0.18.2

I want a script that will only change the fourth line into
cassandra-driver>=2.1.4,!=3.6.0 # Apache-2.0

So it should check if a line contains substring cassandra, and if yes, check if the first character of that line is equal to #, and if yes - remove first character of that specific line - DONE. I have no idea how to do that. Help!

A: Well, you know to start with sed, then it's just a matter of the right replacement command.
sed -e "s/^#\(.*cassandra.*\)$/\1/"

finds lines adhering to the following rules:

*

*starting with a #,

*containing "cassandra" somewhere (arbitrary sequences of characters are allowed both before and after),

stores all the rest of the line (except the #) in a temporary \1 (that's what the \( ... \) do) and is instructed to replace such a line only with the latter.
If needed, this can be further improved to e.g. not look for "cassandra" after a second occurrence of #, but I take it that the end-line comments in your example are added by you and won't be a problem.
Example output:
firstdependency>=2.0.7 # comment
otherdependency>=0.8.9 # another comment
#commenteddependency
cassandra-driver>=2.1.4,!=3.6.0 # Apache-2.0
anotherdependency!=0.18.3,>=0.18.2

A: Simple with ed, the standard editor:
printf '%s\n' 'g/^#.*cassandra/s/^#/' w | ed -s file >/dev/null

The command g/^#.*cassandra/ marks all lines that start with # and contain the string cassandra, and s/^#/ removes the leading # in these marked lines.

A: In awk. If the record starts with a # and has cassandra on it, remove the leading # printing all the records:
$ awk '/^#/ && /cassandra/ { sub(/^#/,"") } 1' file
firstdependency>=2.0.7 # comment
otherdependency>=0.8.9 # another comment
#commenteddependency
cassandra-driver>=2.1.4,!=3.6.0 # Apache-2.0
anotherdependency!=0.18.3,>=0.18.2

A: Your script should contain this only line :
sed -e 's/#cassandra/cassandra/' your_file

The regex s/// replaces one pattern by another, in this case '#cassandra" by "cassandra".


text:
Q: Layering derived objects in Papyrus by OCL Being new to UML/OCL/Papyrus the lack of exchange about this gives me a feeling I might be on the wrong path:
Working on a class diagramm I would like to layer a) all objects that are members of a composition and b) all interfaces that inherit from another interface. That is, I would say, layering by direct and indirect association.
In papyrus I could do this by simply adding elements to a layer. More convenient would be the use of Reg Exp Layers, which select all elements returning TRUE on an OCL boolean expression. As an example, it is easy to put a single element on its own layer via self.element.oclAsType(uml::NamedElement).name='myclass'
But I would also like to put all (downwards) associated elements of 'myclass' on that layer. Any suggestions?

A: Answer from: https://www.eclipse.org/forums/index.php/mv/msg/1087968/1769850/#msg_1769850
While layers may allow you to fold multiple logical diagrams into a single diagram, it seems very misguided.
I find that once diagrams get non-trivial, it is helpful to draw one diagram showing the inheritance architecture, another the containment architecture and perhaps further diagrams for the construction/destruction, communication architectures. Forcing a positional sharing with layers seems to create an undesirable limitation. Remember a UML Diagram is a view of the underlying Model. You may have many Diagrams for different views.


text:
Q: Could not resolve 'spring-boot-security-test' when testing service with mockk I'm currently getting the following error when I try to test my service:
Execution failed for task ':compileTestKotlin'.
> Error while evaluating property 'filteredArgumentsMap' of task ':compileTestKotlin'.
   > Could not resolve all files for configuration ':testCompileClasspath'.
      > Could not find org.springframework.boot:spring-boot-security-test:.
        Required by:
            project :

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

Currently, my test file looks like this:
class UserServiceTest {
    val userRepository: HireOutUserRepository = mockk()
    val passwordEncoder: BCryptPasswordEncoder = BCryptPasswordEncoder()
    val userService: UserService = UserServiceImpl(userRepository, passwordEncoder)

    @Test
    fun whenGetAllUsers_thenReturnSize() {
        verify(exactly = 0) { userService.getUsers() }
    }
}

and my build.gradle.kts looks like this:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "3.0.1"
    id("io.spring.dependency-management") version "1.1.0"
    kotlin("jvm") version "1.7.22"
    kotlin("plugin.spring") version "1.7.22"
}

group = "com.jre"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_17

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    //implementation("org.springframework.boot:spring-boot-starter-data-jdbc")
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-security")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    runtimeOnly("com.h2database:h2")
    //testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("org.springframework.boot:spring-boot-security-test")
    testImplementation("org.springframework.boot:spring-boot-starter-test") {
        exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
        exclude(group = "org.mockito", module = "mockito-core")
    }
    testImplementation("org.junit.jupiter:junit-jupiter-engine")
    testImplementation("io.mockk:mockk:1.13.2")
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "17"
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

I'm not sure what is going on to cause the error to trigger as this should be a simple test scenario in my code.
Thanks

A: Dependency is incorrect. The correct dependency is this.

testImplementation 'org.springframework.security:spring-security-test'

Please add this in build.gradle file and try again


text:
Q: How to speed up svm.predict? I'm writing a sliding window to extract features and feed it into CvSVM's predict function.
However, what I've stumbled upon is that the svm.predict function is relatively slow.
Basically the window slides thru the image with fixed stride length, on number of image scales.

*

*The speed traversing the image plus extracting features for each
window takes around 1000 ms (1 sec).

*Inclusion of weak classifiers trained by adaboost resulted in around
1200 ms (1.2 secs)

*However when I pass the features (which has been marked as positive
by the weak classifiers) to svm.predict function, the overall speed
slowed down to around 16000 ms ( 16 secs )

*Trying to collect all 'positive' features first, before passing to
svm.predict utilizing TBB's threads resulted in 19000 ms ( 19 secs ), probably due to the overhead needed to create the threads, etc.

My OpenCV build was compiled to include both TBB (threading) and OpenCL (GPU) functions.
Has anyone managed to speed up OpenCV's SVM.predict function ?
I've been stuck in this issue for quite sometime, since it's frustrating to run this detection algorithm thru my test data for statistics and threshold adjustment.
Thanks a lot for reading thru this !

A: (Answer posted to formalize my comments, above:)
The prediction algorithm for an SVM takes O(nSV * f) time, where nSV is the number of support vectors and f is the number of features. The number of support vectors can be reduced by training with stronger regularization, i.e. by increasing the hyperparameter C (possibly at a cost in predictive accuracy).

A: I'm not sure what features you are extracting but from the size of your feature (3780) I would say you are extracting HOG. There is a very robust, optimized, and fast way of HOG "prediction" in cv::HOGDescriptor class. All you need to do is to

*

*extract your HOGs for training

*put them in the svmLight format

*use svmLight linear kernel to train a model

*calculate the 3780 + 1 dimensional vector necessary for prediction

*feed the vector to setSvmDetector() method of cv::HOGDescriptor object

*use detect() or detectMultiScale() methods for detection

The following document has very good information about how to achieve what you are trying to do: http://opencv.willowgarage.com/wiki/trainHOG although I must warn you that there is a small problem in the original program, but it teaches you how to approach this problem properly.

A: As Fred Foo has already mentioned, you have to reduce the number of support vectors. From my experience, 5-10% of the training base is enough to have a good level of prediction.
The other means to make it work faster:

*

*reduce the size of the feature. 3780 is way too much. I'm not sure what this size of feature can describe in your case but from my experience, for example, a description of an image like the automobile logo can effectively be packed into size 150-200:

*

*PCA can be used to reduce the size of the feature as well as reduce its "noise". There are examples of how it can be used with SVM;

*if not helping - try other principles of image description, for example, LBP and/or LBP histograms

*LDA (alone or with SVM) can also be used.

*Try linear SVM first. It is much faster and your feature size 3780 (3780 dimensions) is more than enough of "space" to have good separation in higher dimensions if your sets are linearly separatable in principle. If not good enough - try RBF kernel with some pretty standard setup like C = 1 and gamma = 0.1. And only after that - POLY - the slowest one.


text:
Q: Search box broken on Firefox I'm trying to make some beauty search box with css.
On chrome, this works fine, but on FF the search button is broken..
    <form class="form-wrapper cf" action="" method="post">
        <input type="search" placeholder="O que voce procura?" required>
        <button type="submit">BUSCAR</button>
    </form>

my input field css:
    /* Form text input */
    .form-wrapper input {
        width: 230px;
        height: 30px;
        padding: 0px 10px 0px 30px;
        padding-top:5px\9;
        float: left;
        font: 16px 'Maven Pro', Arial, Tahoma, serif;
        color:#959595;
        border: 0;
        background: #eee url(imagens/lupa.png) no-repeat;
        background-position:5px center;
        border-radius: 3px 0 0 3px;
    }
    .form-wrapper input:focus {
        outline: 0;
        background: #fff url(imagens/lupa.png) no-repeat;
        background-position:5px center;
        /*box-shadow: 0 0 2px rgba(0,0,0,.8) inset;*/
    }

here is my fiddle: http://jsfiddle.net/NeRFC/
Open on Chrome and on Firefox to see the problem
How to fix it?

A: Just removed the width from .form-wrapper and it seems to work.

A: Try to add the mozilla rule to .form-wrapper input :
-moz-border-radius: 3px 0 0 3px;

Also, try to comment properly those lines:
In .form-wrapper input :
background: #eee url(imagens/lupa.png) no-repeat;

To
#background: eee url(imagens/lupa.png) no-repeat;

In .form-wrapper input:focus :
background: #fff url(imagens/lupa.png) no-repeat;

To
#background: fff url(imagens/lupa.png) no-repeat;

Maxime


text:
Q: Installing tizen in windows 7 I am trying to install tizen wearable sdk in windows 7 64bit. I have donwload the .exe however when I am trying to isntall it I am getting the following error:
error - Cannot execute Java even if it was installed. Check environment variable or Java version(over 1.6) please.

I have installed in my computer java 1.7.0_80. I have put to the path of the system C:\Program Files\Java\jre7\bin and in JAVA_HOME C:\Program Files\Java\jdk1.7.0_80
I have tried to follow the instructions from here here  however I didn't mange to solve my issues.

EDIT: I followed the instructions from that link I went to cd\Users\AppData\Local\Temp and I run from there the command in console java -jar installmanager.jar. THe installation began normally. However, during the installation I got several errors.

A: Try to check if this directory is in the path too:
C:\ProgramData\Oracle\Java\javapath

and if there is links to missing java executables.
If this is the case, you can remove that folder to the path, replacing with the current java version you want, or fix the link from there.

A: I've had a few problems with the Tizen Wearable install too.

*

*You can either make sure that you have Java in your path by going to a command prompt and typing java -version for example. If it works then Java is in your path. If it doesn't you have to fix it:

*

*Win+Pause/SysRq then click on Advanced System Settings

*Click on environment variables

*Look for PATH and edit it

*Add the path to your Java install (eg: C:\Program Files (x86)\Java\jre1.8.0_31)

*Or run from the command line:

*

*Go to a command line

*cd to %TEMP%

*Run Java by first entering the path to your java version (eg C:\Program Files (x86)\Java\jre1.8.0_31) then bin\java, so C:\Program Files (x86)\Java\jre1.8.0_31\bin\java.exe

If you are still having problems then edit the question to add more specific information so any other issues can be fixed.

A: It seems like the VBS script tried to delete a file that doesn't exist, you can go to the VBS file and go to the problem line, and check out which file was missing. Then decide what to do.
Maybe you should install the latest JDK, try the latest JDK and see if the problem can be solved.


text:
Q: Howto Wordpress + Ajax + Custom Post Type + Custom Metabox + Contact Form 7 here's the situation:
I have a page generated from a custom post type in Wordpress.
This page has a custom metabox with a "thank you" message.
In this page there is a contact form generated with Contact Form 7.
What I would like to archive is that when someone submits the post, a ajax function replaces the form with the content in the metabox.
Now the content in the metabox has also some script (tracking codes) that I don't want to load before the the form is submitted.
Any suggestions?
Thanks in advance!

A: It is possible to do what you want but since you are using CF7 it requires quite a lot of customisation.
It would be way easier to achieve the desired result if you could hardcode the php form into the page.
Let me know if that's an option for you and maybe I can give you an hand.


text:
Q: How to disable GPUImageGrayscaleFilter I have attached GPUImageGrayscaleFilter in a chain with some other filters like so:
[self.image addTarget:self.sepiaFilter];
[self.sepiaFilter addTarget:self.brightnessFilter];
[self.brightnessFilter addTarget:self.grayscaleFilter];
[self.grayscaleFilter addTarget:self.imageView];
[self.image processImage];

I'm wondering, is it possible to do something like:
grayscaleFilter.shutoff = YES;

I'd like for my users to be able to turn on grayscale or turn it off. I'm wondering if I can accomplish this without having to remove it from the chain?

A: You can't accomplish what I want to above, have to remove GPUImageGrayscaleFilter from the filter chain in order to remove it.

A: This is what I did to chain the filters:
- (void) chainFilters
{
    [self.gpuImage removeAllTargets];

    Filter *previousFilter = nil, *firstFilter = nil;

    for (int i = 0; i < [self.filters count]; i++)
    {
        Filter *currentFilter = [[self.filters objectAtIndex:i] retain];
        [currentFilter.filter removeAllTargets];

        if ([currentFilter applied])
        {
            if (!firstFilter)
            {
                firstFilter = [currentFilter retain];
            }

            if (previousFilter)
            {
                [previousFilter.filter addTarget:currentFilter.filter];
                [previousFilter release];
            }

            previousFilter = [currentFilter retain];
        }

        [currentFilter release];
    }

    if (firstFilter != nil)
    {
        [self.gpuImage addTarget:firstFilter.filter];
        [previousFilter.filter addTarget:self.gpuImageView];
    }
    else
    {
        [self.gpuImage addTarget:self.gpuImageView];
    }

    [previousFilter release];
    [firstFilter release];
}

Where Filter is a wrapper class for GPUImageFilter. I apply this each time a filter changes. Don't know if it's the most efficient but it gets the job done. I think there are some other classes within GPUImage like FilterGroup and FilterPipeline that make this easier though I haven't messed with them yet.


text:
Q: Export Magento 1.8 category list with product name and sku I'm looking at the post here:
Create CSV list of all products & their categories
and the instructions to "put the script in a file on the same level as index.php and run it in the browser or command line."
I'm new to Magento. Does this mean to create a .bat file and place it in same file level as index.php?  Where is index.php located?

A: The first line of the script tells you what kind of file it is: a .php file. So you'll need to use a text-editor to create that file, give it any name you like, and make sure you save it with a .php extension.
As to the location of your index.php file, it is located at your document root for your website, typically a folder called public_html or www or something similar.
After you create the file you will need to upload it to your server and call it from your browser:
www.yourdomain.com/yourscript.php
This will cause the server to execute that file and perform whatever actions you have included in it.
This is really basic stuff. If any of it is making you nervous or perhaps ask more questions than you have, please consider hiring a developer to assist you.


text:
Q: Is there a naming convention for a navigation controller? When I try to push a view controller to my UINavigationController I get a NSInvalidArgumentException thrown with the error message "unrecognized selector sent to instance".  But this only happens when I name my UINavigationController ivar anything other than "navigationController".  Is there a reason for this?

A: Not sure how your code is structured, but every UIViewController has a navigationController property.  (See http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html)
So, [self navigationController] is returning the property from the current view controller (whatever self is), not what you've named in your AppDelegate.


text:
Q: NoReverseMatch in django production server The project is working fine in the dev server but when I try to use it in the production sv(Gunicorn + Nginx), NoReverseMatch error appears. I checked the code several times and I can't find the error.
urls.py:
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings

urlpatterns = patterns('',
    (r'^obras/', include('obras.urls')),
)

obras urls.py:
from django.conf.urls.defaults import *
from obras import views

urlpatterns = patterns('',
    url(r'^presobra/$', views.pres_obra, name='pres_obra'),
)

Error message:
Request URL:   http://127.0.0.1:8888/admin/
Python Path:
     ['/srv/www/antingprojects.com.ar/gobras',
     ...
     ']
Exception Value:
 Caught NoReverseMatch while rendering: Reverse for 'pres_obra' with arguments '()' and  keyword arguments '{}' not found.
Template error
In template /srv/www/antingprojects.com.ar/gobras/templates/admin/index.html, error at line  75
 Caught NoReverseMatch while rendering: Reverse for 'pres_obra' with arguments '()' and keyword arguments '{}' not found.
75
Presupuestos-Obras

settings.py:
import os.path
PROJECT_DIR = os.path.dirname(__file__)
ROOT_URLCONF = 'gobras.urls'

Project structure:
-gobras
--obras
--media

A: Try adding: from obras.urls import urlpatterns as obras_urlpatterns to the urls.py.  I'll bet that it fails, and that the issue is the PYTHONPATH in production isn't finding the obras app.  Make sure you have it set correctly.


text:
Q: How to sort list by first element I have a list of vectors looking like:
[[1]]
[1] 2 1.0 3.0

[[2]]
[1] 3 3 3

[[3]]
[1] 1 3.0 1.0

and I want it to be sorted by first element of every vector, in decreasing order, like that:
[[1]]
[1] 3 3 3

[[2]]
[1] 2 1.0 3.0

[[3]]
[1] 1 3.0 1.0

I am looking for a solution that would look like (of course it is not working):
list.sortby(function (x) x[1])

A: I assumed that your example should not have resulted in putting the second element of your list in the first element of the result? If this is right, you can use lapplyto do what you want:
L <- list(c(2,1,3), c(3,3,3), c(1,3,1))
L
lapply(L, sort)

If you are ordering by the first value in each vector of you list, then this can be done in the following way:
L[order(sapply(L, function(x) x[1], simplify=TRUE), decreasing=TRUE)]

L
[[1]]
[1] 3 3 3

[[2]]
[1] 2 1 3

[[3]]
[1] 1 3 1

From your example, it looks like you want the decreasing order.

A: Similar to @MarkintheBox.
L <- list(c(2,1,3), c(3,3,3), c(1,3,1))

L[order(sapply(L,head,1),decreasing=T)]
# [[1]]
# [1] 3 3 3
#
# [[2]]
# [1] 2 1 3
#
# [[3]]
# [1] 1 3 1

A: Same as the others but using Map to extract the first element of each vector.
L <- list(c(2,1,3), c(3,3,3), c(1,3,1))
idx <- as.numeric(Map(function(vec){vec[1]},L))
L[order(idx, decreasing=TRUE)]


text:
Q: PositionalDataSource : how to jump to specific position in recycler view? I'm using PositionalDataSource and LiveData/PagedListAdapter
I want to make my recyclerview scroll to specific position when given a corresponding key value.
How to do this?

added my trial code : what i hope is when button clicked recyclerview method scrolltoposition works well.. but I know it's an incorrect way. I believe i need to use key instead of this direct access.
itemViewModel.getAllItems().observe(this, new Observer<List<Item>>() {
        @Override
        public void onChanged(@Nullable List<Item> itemList) {
            itemViewModel.getPagedListLiveData(itemList).observe(MainActivity.this, new Observer<PagedList<Item>>() {
                @Override
                public void onChanged(@Nullable PagedList<Item> items) {
                    adapter.submitList(items);
                }
            });
        }
    });
    binding.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ItemDataSource dataSource = itemViewModel.getDataSource();
            dataSource.invalidate();
            binding.rv.getLayoutManager().scrollToPosition(20000);
        }
    });

datasource class
public class ItemDataSource extends PositionalDataSource<Item> {
private List<Item> list;

public ItemDataSource(List<Item> list) {
    this.list = list;
}

private int computeCount() {
    return list.size();
}

private List<Item> loadRangeInternal(int startPosition, int loadCount) {
    List<Item> modelList = new ArrayList<>();
    int endPosition = Math.min(computeCount(), startPosition + loadCount);
    for (int i = startPosition; i < endPosition; i++) {
        modelList.add(list.get(i));
    }
    return modelList;
}

@Override
public void loadInitial(@NonNull LoadInitialParams params, @NonNull LoadInitialCallback<Item> callback) {
    int totalCount = computeCount();
    int position = computeInitialLoadPosition(params, totalCount);
    int loadSize = computeInitialLoadSize(params, position, totalCount);
    callback.onResult(loadRangeInternal(position, loadSize), position, totalCount);
}

@Override
public void loadRange(@NonNull LoadRangeParams params, @NonNull LoadRangeCallback<Item> callback) {
    callback.onResult(loadRangeInternal(params.startPosition, params.loadSize));
}

repository class
public class ItemRepository {
private ItemDao itemDao;
private LiveData<List<Item>> allItems;
private MutableLiveData<PagedList<Item>> pagedListLiveData = new MutableLiveData<>();

private ItemDataSource dataSource;

public ItemRepository(Application application) {
    ItemDatabase database = ItemDatabase.getInstance(application.getApplicationContext());
    itemDao = database.itemDao();
    allItems = itemDao.getAllItems();
}

public LiveData<PagedList<Item>> getPagedListLiveData(List<Item> itemList) {
    dataSource = new ItemDataSource(itemList);
    PagedList.Config config = new PagedList.Config.Builder()
            .setPageSize(200)
            .setEnablePlaceholders(false)
            .build();
    PagedList<Item> itemPagedList = new PagedList.Builder<>(dataSource, config)
            .setInitialKey(10000)
            .setNotifyExecutor(new MainThreadExecutor())
            .setFetchExecutor(Executors.newSingleThreadExecutor())
            .build();
    pagedListLiveData.setValue(itemPagedList);
    return pagedListLiveData;
}

public ItemDataSource getDataSource() {...}

public LiveData<List<Item>> getAllItems() {...}

A: If you have a recyclerView object then you can use method scrollToPosition(position: Int)


text:
Q: How to convert Observable to InputStream? I have an Observable which emits Buffer items which contain byte arrays.
I would need to process this data via an InputStream. I'm aware that InputStreams are essentially blocking but I can use an Scheduler to work around this. My current issue is how to convert the formats.
Single<String> transform(Observable<Buffer> obs) {
  try (InputStream ins = ???) {
    String data = processData(ins);
    return Single.just(data);
  }
}


text:
Q: CalendarView getDate method returns current date, not selected date... What am I doing wrong? My calendarView fails to return the selected date, instead returning some default that always points to today.
I am of course changing the date selected in my calendar, and it indeed displays as having changed. I tried inspecting the view in debug mode, but didn't find anything.
I am running this in a simulator, not on a real phone... Should I modify some settings? Am I missing something important? Because it really is confusing that I'm not getting the selected date, but the current one.
<CalendarView
                            android:id="@+id/view_calendar_create_event_date"
                            android:layout_width="wrap_content"
                            android:layout_height="0dp"
                            android:layout_weight="1" />

This is called from the event listener
protected void createEvent(View view){
        TextView eventNameView = (TextView) this.findViewById(R.id.createEventNameInput);
        String eventName = eventNameView.getEditableText().toString();

        CalendarView eventOccursOnView = (CalendarView) this.findViewById(R.id.view_calendar_create_event_date);
        long eventOccursOn = eventOccursOnView.getDate();
        Date temporary = new Date(eventOccursOn);

        Event newEvent = new Event(eventName, "", 0, 0, eventOccursOn);
        newEvent.save(view.getContext());
    }

and this is how I'm setting my event listener
saveButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                // Create the event
                EventDetailsActivity.this.createEvent(view);

                // Notify the user
                Snackbar.make(view, "Successfully created a new event!", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

                // Return to the previous activity
                finish();
            }
        });

A: You need to implement setOnDateChangeListener
long eventOccursOn;

eventOccursOnView.setOnDateChangeListener(new OnDateChangeListener() {
    //show the selected date as a toast
    @Override
    public void onSelectedDayChange(CalendarView view, int year, int month, int day) {
        Toast.makeText(getApplicationContext(), day + "/" + month + "/" + year, Toast.LENGTH_LONG).show();
        Calendar c = Calendar.getInstance();
        c.set(year, month, day);
        eventOccursOn = c.getTimeInMillis(); //this is what you want to use later
    }
 });

A: This is my understanding and solution:
by default CalendarView's selected date is today. When you select new day in calendar, it's just highlighted in view, but not actually selected (I know, doesn't make sense, but this is how this view works).
So you need to implement date change listener and inside it select new date in calendar view.
import java.util.Calendar
import java.util.Date

// assuming your CalendarView has id 'calendarView'
fun initCalendarView() {
   // prints today's date by default
   printCurrentlySelectedDate()

   binding.calendarView.setOnDateChangeListener { _, year, month, dayOfMonth ->
      binding.calendarView.date = Calendar.getInstance()
         .apply { set(year, month, dayOfMonth) }
         .timeInMillis
   }
}

fun consumeSelectedDate() {
   // now date is whatever you selected in view
   printCurrentlySelectedDate()
}

fun printCurrentlySelectedDate() {
   val date = Date(binding.calendarView.date)
   println(date)
}


text:
Q: How to add exe as reference in my web application I have created an exe with some methods in it (ref example exe below).
using System;
using System.Collections.Generic;
using System.Text;

namespace SampleRef
{
  public class Program
  {
  static void Main(string[] args)
    {
    }
  }
  public class Sample
  {
   public Sample(int count)
    {

    }

    public string SampleString(int InputValue)
    {
      //Do something
       return "<the result>";
    }
  }
}

I want to add reference this exe into my web application to call (SampleString) methods in side the exe. Is it possible in .net and how can I achieve this?

A: Yes - just add it as if it were a class library. Visual Studio has supported this since 2005.
EDIT: Okay, it sounds like ASP.NET may not like .exe assemblies :(
In that case I suggest you extract the code from your current executable and put it into a class library. You may find it easier to change the whole of your normal application into a DLL - and just add another executable project which does nothing but call into the DLL to start the "application". That shouldn't be the end-point of your code, but it's an easy way to get up and running.

A: You definitely can add and use a reference to an exe in exactly the same way that you would a dll (.net 4 at least).
I think the missing assembly message is probably a red herring, if you've added a reference successfully and get this message when you try to use it, I've always found this is due to targeting different versions of framework (usually the Client Profile version being defaulted).

A: Final compiled output in .Net is called Assemblies and EXEs are no different in this case. It's just that they carry a special header that identify them as executables with program entry points and normal compiled dll assemblies don't have this, but both are assemblies and you can add assemblies as reference in any .net project you're working on.

A: Yes.
Just go to the Project menu, select Add Reference change to the Browse tab and find and select the executable.


text:
Q: Proofs of identity for product of binomial coefficients While verifying my answer to another question, I came across a problem of binomial coefficients:  Does $\hspace{.2cm}\displaystyle \prod_{k=1}^{n-1}\binom{n-1}{k}=\prod_{k=1}^{n-1}k^{2k-n}$ for all $n\in\mathbb{N}^+?$
I offer a proof by induction below, but I would appreciate references or alternative approaches.

A: Well, in each term of your product, the numerator is $(n-1)!$. Thus, the "total" numerator is $$\left((n-1)!\right)^{n-1}=\prod_{1}^{n-1}k^{n-1}$$
As for the denominator, each individual denominator is a product of 2 factorials, the argument of first factorial "grows" from  $0$ to $(n-1)$, the argument of the second one "grows smaller" from $n-1$ to $0$. Thus, each argument appears exactly two times, and we have $\left(\prod_1^{n-1}k!\right)^2$. Note that in $\left(\prod_1^{n-1}k!\right)$ we come across number $k$ $n-k$ times, thus our denominator is $$\left(\prod_1^{n-1}k!\right)^2 = \prod_1^{n-1}k^{2(n-k)}$$
Trivial division allows to conclude. I favour this kind of proofs because you make virtually no formula manipulation, almost impossible to get it wrong.

A: The identity can be proved by induction on $n$. For $n=1$, each side is an empty product and so both equal $1$, so we assume it is true for some $n\geq 1$. Then for $n+1$ we have
$$\prod_{k=1}^{n}\binom{n}{k}=\prod_{k=1}^{n-1}\binom{n}{k}=\prod_{k=1}^{n-1}\frac{n}{n-k}\binom{n-1}{k}=\frac{n^{n-1}}{(n-1)!}\prod_{k=1}^{n-1}\binom{n-1}{k},\\
\prod_{k=1}^{n}k^{2k-n-1}=n^{n-1}\prod_{k=1}^{n-1}k^{2k-n-1}=\frac{n^{n-1}}{\prod_{k=1}^{n-1}k}\left(\prod_{k=1}^{n-1}k^{2k-n}\right)=\frac{n^{n-1}}{(n-1)!}\prod_{k=1}^{n-1}k^{2k-n}.$$
Then the inductive hypothesis implies that these expressions are equal, and we conclude that the identity is true for all $n\in \mathbb{N}^+$.


text:
Q: What is PyObjC? I understand the concept of PyObjC, but can nowhere find any information on what exactly it is or how to get started with it.
Is it like a converter, where youinput python files and get an objective c one?
Or is it a library you can import to your objective c files which let's you write python in them?
Or is it something else entirely?
If anyone can give tips on how to approach it, an outline of how it works, or just some instructions on a hello world with it, I would be very grateful.

A: It's a language binding, meaning it allows you to call ObjC code from Python and vice versa. You write wrapper modules in ObjC that can be linked into the Python interpreter (which is written in C) to give it access to ObjC functions (tutorial for this use case). Apparently, the entire Cocoa framework is already wrapped, so you can use that from Python with ease.
Vice versa, it enables you to link the Python interpreter into your ObjC app and use it to execute Python code in your app (tutorial).


text:
Q: Why .net shows version conflict for same nuget package which is internal dependency for 3rd party library/package? Conflicting versions of Newtonsoft.json library.
Steps to Reproduce issue:

*

*Create 2 .net c# project

*Project 1 include IdentityModel with some method

*Project 2 include Microsoft.AspNet.WebApi.OwinSelfHost with some method

*Pack them and create nuget package and publish it locally (2 package will get created)

*Now create a test project and install both nuget package in it.

*Call the method from those installed packages. You will get conflict error regarding Newtonsoft.json

I have two custom plugin developed on top of Kafka and REST. To fullfill the plugin I am using 3rd party libraries as part of dependency. Dependency internally uses Newtonsoft.Json package with their specific version.
package use for developing kafka plugin

package use for developing REST plugin

.net should not show the error

System.Reflection.TargetInvocationException : Exception has been
  thrown by the target of an invocation.   ---->
  System.IO.FileLoadException : Could not load file or assembly
  'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral,
  PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The
  located assembly's manifest definition does not match the assembly
  reference. (Exception from HRESULT: 0x80131040)

as 3rd party library should refer their package according to their version. For me if I navigate to

%USERPROFILE%.nuget\packages

location I can see version graph  for newtonsoft.json and 3rd party lib should use them at runtime. Version 6.0.4 and 11.0.2 should load at it's runtime.

A: please use Update-Package command to update all the packages in all projects


text:
Q: Code in my wp-config file I do not understand and need help deciphering I was updating my wp-config file today, and I found a lot of random stuff added to the end which was from a previous host. I deleted it, as it was not necessary, but I also noticed this code which I'm not sure about. I think the first part is for SSL reasons, but I thought that was taken care of elsewhere, not in my config file? Or am I mistaken? I have noticed when doing research in ahrefs that my site suffers from redirect chains related to http > https, so I'm not sure if this is something to do with that?
The rest of this I do not understand at all. Any help would be really appreciated.
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
$_SERVER['HTTPS'] = 'on';
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
/**
 * Include tweaks requested by hosting providers.  You can safely
 * remove either the file or comment out the lines below to get
 * to a vanilla state.
 */
if (file_exists(ABSPATH . 'hosting_provider_filters.php')) {
include('hosting_provider_filters.php');
}

Thanks for help.

A: When in doubt its always a good idea to reference - https://github.com/WordPress/WordPress/blob/master/wp-config-sample.php
That aside, the first part you are correct it deals with redirecting to SSL. It is better to use https vs http to avoid the redirect.
Incoming traffic
Request - http > server > redirect to https and returns request
https > server > returns request
The next section is part of a normal wp-config.php file.
The last section is specific to a hosting provider. It mentions it is safe to comment out or remove. If unsure I would contact your current host to see if it is theirs and what it does if so. If not, you are safe to remove.

A: I will break your code into three parts
1.
    if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
    $_SERVER['HTTPS'] = 'on';

To get information about which protocol used between client and load balancer, we can use the X-Forwarded-Proto request header. Using this header, the client can make an HTTP request to an HTTPS-only resource.
The purpose of HTTP_X_FORWARDED_PROTO is to make sure the connection is secure with ssl
Notice:Not in the original file https://github.com/WordPress/WordPress/blob/master/wp-config-sample.php
2.
    if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');
    /** Sets up WordPress vars and included files. */
    require_once(ABSPATH . 'wp-settings.php');

ABSPATH is defined and used for two main purposes
contain Absolute path to the WordPress directory
To deny direct access to files
3.
     if (file_exists(ABSPATH . 'hosting_provider_filters.php')) {
        include('hosting_provider_filters.php');
        }

Added by hosting provider
It can be deleted


text:
Q: How to read Bytes of an Image in Java? I am currently working with Image processing in Java. Initially I used ImageIO class to write images
ImageIO.write(image,"jpg",os);

the problem with this method is am lossing the actual image size and quality. Then I preferred ByteStream
Files.readAllBytes(fi.toPath());

to read and
fos.write(fileContent);

to write Images. This works perfectly. The issue I am facing here is I can read only files but not Images(ie, BuffreredImage image). Is it possible to read a Image rather than files here or should I move to someother IO?
Code Snippet is here,
try {

File fnew=new File("d:\\3\\IMG1.jpg");
java.io.FileOutputStream fos = new java.io.FileOutputStream(new             File("d:\\3\\Test1\\4.jpg"));
File fi = new File("d:\\3\\7.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath());
fos.write(fileContent);

} catch (Exception e) {

System.out.println("Exception");
}

Any Kind of suggestions or help will be appreciated. Thanks in Advance.

A:
the problem with this method is am lossing the actual image size and quality. Then I preferred ByteStream

When you read a JPEG with with ImageIO, it is converting the JPEG to a Bitmap automatically. Then when you write it, it is encoding to a JPEG again (which loses quality).
Just replace ImageIO.write(image,"jpg",os) with ImageIO.write(image,"png",os) and you are done. A lossless format such as PNG will not lose any data when you write the image.

A: BufferedImage getRGB() will get you all the actual pixel data for the image.  There will be no compression or anything like JPEG.  It will be the raw image.
Edited to add an example based on my comments...
    BufferedImage image = ImageIO.read(new File("google.jpg"));
    ImageWriter w = ImageIO.getImageWritersBySuffix("jpg").next();
    ImageOutputStream out = ImageIO.createImageOutputStream(new File("output.jpg"));
    w.setOutput(out);
    ImageWriteParam param = new JPEGImageWriteParam(Locale.getDefault());
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(1);
    w.write(null, new IIOImage(image, null, null), param);
    out.close();


text:
Q: jquery: most efficient way to get and store the ids of 100+ td items? Ok so I have about six of these calendars on page, so thats around 180 td items (1 for each date):

each td has an id that is equal to that day's timestamp.
the dates I want are the red ones (class of .booked).
So i need the fastest way to 'serialize' the ids for td.booked items, any ideas?

A: You can get an array of the IDs using .map(), like this:
var ids = $("td.booked").map(function() { return this.id; }).get();

This would result in an array like this:
["id1", "id2", "id3", ... ]

A: What exactly do you mean by "serialize"?
If they are being marked on the client, then the fastest way to collect references to them would be to collect them as they are marked.  Then, you already an index to them when you need it, and no retroactive query is needed.

A: How about this:
var str = '';

$(function(){
  $('td.booked').each(function(index){
     str += '&td' + index + "=" + encodeURIComponent($(this).text());
  });
});

alert(str);


text:
Q: Adjusting the X zoom for the Shield UI Inversed Bar Chart I am using an Inversed Shield UI Chart  that I need to be able to zoom. I am using local data binding:
  var MyData = [
[0.75, 0.79],
[0.95, 1.03],
…
  ];

…
    dataSeries: [{
      seriesType: "rangebar",
      collectionAlias: "Series A",
      data: MyData
    }

and the chart actually works and displays data as expected.
Since some of the data values are much smaller than others, I need these bars to be zoomed in to and to stretch along the X axis. For that purpose I set the property:
zoomMode:'x',

but there is some strange result. It looks like bars zoom on the Y axis. What can be wrong to be getting this behaviour?

A: The issue s quite simple. Since the chart is inversed this means that X and Y axes are switched. And so does the zoomMode scope.
You need to set
zoomMode:'y'

in order to zoom the bars horizontally.


text:
Q: How to move object's hitbox/content size with Cocos2d I would like to make a button with large hover picture on top of if with Cocos2D MenuItems. I tried to make it with 2 sprites which are larger than the are I want user to be able to touch - a bit like the iPhone keyboard.
I figured I could make the hitbox of the button smaller with [button setContentSize:CGSizeMake(22, 22)];, but couldn't find a way to move it. I want the touchable area to be in the middle bottom area.
Other way would be to add an object aboce the button when selected, but I don't know how to do that with Cocos2D's MenuItems.

A: try doing this....
CCMenuItem *MenuItem = [CCMenuItemImage itemFromNormalImage:@"Button.png" selectedImage:@"ButtonSel.png"  target:self selector:@selector(ButtonTapped:)];
  CCMenu *myMenu = [CCMenu menuWithItems:MenuItem, nil];
[self addChild:myMenu];

but the ButtonSel is the image when you hover over it
it should work but if it doesn't play around with anchorPoints
i mean there's no reason why the selected button shouldn't be bigger than the non-selected one
i didn't actually try this..so let me know if it works


text:
Q: Firefox 4: How does File.url work? Did it as stated at this page, but got undefined in my Firefox 4 Beta 7.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function read(files) {
 var myFile = files[0];
 document.write(myFile.url);
}
</script>
</head>
<body>

 <input type="file" onchange="read(this.files);" />

</body>
</html>

A: I think this page will be more useful ;)

A: I don't know why it isn't working in the current beta. I don't think the standard is very stable yet, so file.url might have been removed since the article was written. I can't find anything about it in the current API draft.
It seems you get the same type of url in FF 4 beta 7 if you use createBlobURL(myFile) instead of myFile.url


text:
Q: How can I convert a JavaScript variable to a Java variable? I need to convert a variable from JavaScript into a Java variable. I'm asking users for their e-mail ids with a Block-UI popup through Test Box. If the field is neither null nor empty, the e-mail id should be sent to a session variable so that it can be accessed anywhere in the project.
Here's my code:
function sbtEmail(){
    var email = document.getElementById("EmailId").value;
    if (email == null || email == ""){
        alert("Enter your contact Email address to continue...!");
        document.getElementById("EmailId").focus();
    } else {
        <%session.setAttribute("quoteEmail",email);%>
        window.location.href = "demo2.jsp";
    }
}

It doesn't work. What am I doing wrong?

A: You can not set a variable in the session (which resides on the server alone!) directly from JavaScript. You have to pass them to your server in some kind of request, and then the server can set it in the session.

A: Solved : using Ajax will solve the Problem.
  <script type="text/javascript" src="../ajax.js"></script>

     <script type="text/javascript">
    function sbtEmail(){
        var email = document.getElementById("anonymousEmailId").value;
        if (email==null||email==""){
            alert("Enter your contact Email address to continue...!");
            document.getElementById("anonymousEmailId").focus();
        }else{
            enqueue("demo1.jsp?Id="+email,ajaxReplay);
        }
    }
    function ajaxReplay(){
        window.location.href="demo.jsp";
    }
    </script>

In demo1.jsp : set value for session variable
String Email = request.getParameter("Id");
session.setAttribute("sessEmail",Email);

A: Use this Ajax file:----> eval(function(p, a, c, k, e, r) { e = function(c) { return (c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) r[e(c)] = k[c] || e(c); k = [function(e) { return r[e] } ]; e = function() { return '\\w+' }; c = 1 }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p } ('d 7;f n(a,b,c){6(!7)7=j s;6(!7.n(a,b,c))g l;6(!7.k)7.o();g h}f s(){3.5=j t();3.8=9;3.k;3.m=h;3.n=f(a,b,c){u(d i=0;i<3.5.p;i++)6(3.5[i][0]==a&&3.5[i][1]==b&&3.5[i][2]==c)g l;6(3.8==9){3.k=l;3.m=h;3.8=0}v{++3.8}3.5[3.8]=j t();3.5[3.8][0]=a;3.5[3.8][1]=b;3.5[3.8][2]=c;6(3.k&&c)w(c);g h};3.o=f(){6(3.8==9||3.5.p==0)g;3.k=h;6(3.m){d r=q();d a;6(r){u(d i=0;i<3.5.p;i++){6(3.5[i][2])w(3.5[i][2])}}3.m=l}3.x(3.5[0][0],3.5[0][1])};3.x=f(a,b){d r=q();6(r){r.E("F",a,h);r.G=f(){6(r.H==4){6(b)b(r.I);7.5.J(0,1);7.8>0?--7.8:7.8=9;6(7.8==9){7.k=l;7.m=h;g}v{7.o()}}};r.K(9)}}}f q(){d A=9;y{A=j z("L.B")}C(e){y{A=j z("M.B")}C(N){A=9}}6(!A&&O D!="P"){A=j D()}g A}', 52, 52, '|||this||queue|if|g_q|position|null||||var||function|return|true||new|isProcessing|false|callPreFunctions|enqueue|process|length|getXMLHTTP||ajaxQueue|Array|for|else|eval|getAjaxQueueResult|try|ActiveXObject||XMLHTTP|catch|XMLHttpRequest|open|GET|onreadystatechange|readyState|responseText|splice|send|Msxml2|Microsoft|oc|typeof|undefined'.split('|'), 0, {}))


text:
Q: search a string in file and insert content above I try to search a string inside a txt-file and insert some specific content above it.
Sadly the output looks quite different from what I expect.
Can somebody give me a hint?

This is how far I got!

    String description= "filename.txt";
    String comparison="    return model;";
    RandomAccessFile output = null;
        try
        {
          output = new RandomAccessFile(description, "rw" );
          String line = null;
          while ((line = output.readLine()) != null) {
                  if (line.equals(comparison)){
                      //System.out.println("alt: "+line);
                      output.seek(output.getFilePointer()-line.getBytes().length);
                      output.writeChars("new stuff; \n");
                      //System.out.println("new: "+output.readLine());
                      }
          }
        }
        catch ( IOException e ) {
          e.printStackTrace();
        }
        finally {
          if ( output != null ){ try { output.close(); } catch ( IOException e ) { e.printStackTrace(); }}
        }

This is the file I try to read:
/*filename.txt*/
    some longer content ~ 100kB

    return model;

    further content

and this is what I hope to get
/*filename.txt*/
    some longer content ~ 100kB

    new stuff;

    return model;

    further content

A: Files don't support insertion or deletion of content except at the end of the file. (It's not a limitation of Java but the OS)
To insert text, you must re-write the file (at the least from the point you want to alter) The simplest solution is to copy content to a temporary file, altering/inserting or deleting as required and replacing the original if this is sucessful.

A: Use two files. Copy until which line you want into a new file. Add your new line. Then again copy the rest of the lines into the file. Finally, copy the whole content of the new file into the old file

A: First of all: there is white space in the string you're testing for:
String comparison="    return model;";

It would be a better idea to compare the lines like this:
if (line.trim().equals(comparison.trim())){ ...

The call to trim() will remove all whitespaces/tabs in the line and the comparison string, so it would match also if some file uses tabs instead of whitespaces, or a different number of whitespaces...


text:
Q: Unable to send email inside my console application. error "No connection could be made because the target machine actively refused it" I have the following console application, which connect to our SharePoint online site collection and send emails:-
using (ClientContext context = new ClientContext(scurl))
            {
                SecureString passWord = new SecureString();
                foreach (var cc in s)
                passWord.AppendChar(cc);
                context.Credentials = new SharePointOnlineCredentials("admin@****.onmicrosoft.com", passWord);

                List oList = context.Web.Lists.GetByTitle(listname);
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = "<View><Query><Where><And><Eq><FieldRef Name='Contract_x0020_Review_x0020_Date'/>" +
                    "<Value Type='DateTime'><Today /></Value></Eq><Eq><FieldRef Name='Contract_x0020_Status'/><Value Type='String'>Active</Value></Eq></AND></Where></Query><RowLimit>5000</RowLimit></View>";
                ListItemCollection collListItem = oList.GetItems(camlQuery);

                context.Load(collListItem,
items => items.Include(
item => item["Contract_x0020_Status"],
item => item["Person_x0020_Responsible"],
item => item["Title"],
item => item["Id"]

));

                context.ExecuteQuery();
                foreach (ListItem oListItem in collListItem)
                {

                    oListItem["Contract_x0020_Status"] = "Needs Review";
                    oListItem.Update();
                    context.ExecuteQuery();
                    var userValue = (FieldUserValue)oListItem["Person_x0020_Responsible"];
                    var user = context.Web.GetUserById(userValue.LookupId);
                    context.Load(user, x => x.Email);
                    context.Load(user, x => x.Title);
                    context.ExecuteQuery();

                    //item.RoleAssignments.RemoveById(spgroup.ID);

                    MailMessage mail = new MailMessage("no-reply@sharepointonline.com", user.Email);
                    SmtpClient client = new SmtpClient();
                    client.Port = 587;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.UseDefaultCredentials = false;
                    client.EnableSsl = true;
                    client.Host = "smtp.office365.com";
                    mail.Subject = "The Contract has revowed";
                    //mail.To = user.Email[0];
                    mail.Bcc.Add(ConfigurationManager.AppSettings["bccemail"].ToString());
                    mail.Body = "Hi " + user.Title + "
The Review Date for the following Contract has been reached " + oListItem["Title"]+ "
TDM Group Operations";
                    client.Send(mail);

                }

                // Now update the list.
            }

but the client.Send(mail); will raise this exception:-
System.Net.Mail.SmtpException was unhandled
  HResult=-2146233088
  Message=Failure sending mail.
  Source=System
  StackTrace:
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at ConsoleApplication1.Program.Main(String[] args) in c:\Users\***Program.cs:line 94
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.Net.WebException
       HResult=-2146233079
       Message=Unable to connect to the remote server
       Source=System
       StackTrace:
            at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
            at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
            at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
            at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
            at System.Net.Mail.SmtpClient.GetConnection()
            at System.Net.Mail.SmtpClient.Send(MailMessage message)
       InnerException: System.Net.Sockets.SocketException
            HResult=-2147467259
            Message=No connection could be made because the target machine actively refused it 52.97.133.226:587
            Source=System
            ErrorCode=10061
            NativeErrorCode=10061
            StackTrace:
                 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
                 at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
            InnerException:

so can anyone advice on this?

A: This isn't a SharePoint Online question (and I suspect your message will be rejected if you're also attempting to use a domain other than your own) but rather an Exchange Online question.
However, you can review the documentation for using Office 365 SMTP relay.
How to set up a multifunction device or application to send email using Office 365


text:
Q: After instaling ARM eclipse plugin in eclipse indigo clicking when clicking on new C/C++ project dothing happens
*

*I installed ARM Code Sourcery G++ Lite

*Installed Eclipse IDE for C/C++ Developers indigo

*Installed ARM eclipse plugin
And few things happen now:

*

*After clicking on new C/C++ plugin nothing happens.

*The Code Sourcery toolchain seems not to be supported.
When I try to select it I always get:

Internal Error:
  org.eclipse.cdt.cross.arm.gnu.sourcery.windows.IsToolChainSupported.isSupported(Lorg/eclipse/cdt/managedbuilder/core/IToolChain;Lorg/osgi/framework/Version;Ljava/lang/String;)Z

Any idea what how to fix those issues?

A: It works for Indgo already. See bug in ARM eclipse plugin.
Using version 0.5.4 fixes the problem.

A: Known Bug in ARM eclipse plugin, it does not work with CDT indigo yet.


text:
Q: Unable to track why string permutations are not being appended in a global variable for array permutations I am trying to code the String permutation problem. Instead of string I have a list of integers like [1,2,3]. I have to print out all possible permutations of the list. However, there's some issue with my code that I'm not able to figure out. Somehow, the line if not in words in the base case hits only once. I'm trying to figure this out from the past one hour. Any help would be appreciated!. TIA
Here's the code
words = list()
def permute(nums):
    if len(nums) == 0:
        return None

    l = 0
    r = len(nums)

    permute_helper(nums,0,r)

def permute_helper(nums,start,end):
    current = 0
    if start == end-1:
        if not nums in words:
            print 'appended'
            words.append(nums)
    else:
        for current in range(start,end):
            temp = nums[start]
            nums[start] = nums[current]
            nums[current] = temp
            #Recursive call
            permute_helper(nums,start+1,end)
            temp = nums[start]
            nums[start] = nums[current]
            nums[current] = temp

permute([1,2,3])
print words

A: The bug is that you keep modifying the same list nums so you end up with only one copy that was modified but the modifications were not recorded.
Change:
words.append(nums)

to:
words.append(nums[:])

which will create a copy of nums and "freeze" it current state.
Comment:
You can do the swap in a more pythonic way, instead of:
temp = nums[start]
nums[start] = nums[current]
nums[current] = temp

do:
nums[start], nums[current] = nums[current], nums[start]

A: You're appending the same list each time. No wonder it's already there (in words).
In other words, you are not collecting each different permutation, but a reference to nums. So, subsequent permutations are reflected in words. That's the plague of mutability.
One solution is to make a copy of the current permutation:
words.append(nums[:])

By the way, a pythonic swap is:
a, b = b, a   # no need for tmp

Also, there is no need to reset current.


text:
Q: Does operator overloading still cause performance hit for SIMD wrappers? I was reading: http://jmabille.github.io/blog/2014/11/20/performance-considerations-about-simd-wrappers/
That blog says that operator overloading for simd wrapper introduces overhead when the code is compiled with gcc 4.7.3.
Is this still true for new gcc (like gcc 5 or 6) or intel c compilers (2016 version)?
In Agner Fog's vector class library, it seems the operations (such as >) is defined by the stateless function as described in the blog.


text:
Q: How do you change Advanced Matching Personal info after init FB Pixel with other info? After initializing the Facebook Pixel with personal information for Advanced Matching, are you allowed to change the personal information for Advanced Matching? This is for a Single Page Application. I tried to initialize the Facebook Pixel again with new personal information, and the pixel still was reporting the original Advanced Matching info that I initialized with.
For example, we would run:
window.fbq('init', <FACEBOOK_ID>, { em: <email> });
On a later page we get more information about them, so we would run:
window.fbq('init', <FACEBOOK_ID>, { em: <email>, st: <state> })
The new infomation, in this example state info, is not being reported.

A: As you are using single page application so you have to do init again, This is not possible to append the advance parameter.
window.fbq('init', <FACEBOOK_ID>, { em: <email>, st: <state> })

Facebook always fire the event after initializing the pixel so in your first line code call was already sent to faecbook and that's fire. Now if you want to send another parameter then you have to send the call to facebook again with init.

A: I solved this while also working with a Single Page Application (SPA) by just sending the information using a pixel based on an image after the Javascript's one was initialized with the init event.
I used the following code:
var fbtag = document.createElement('img');
var user_email = 'USER_HASHED_EMAIL_IN_SHA256';
var pixel_id = 'XXXXXXXXX';
fbtag.src = 'https://www.facebook.com/tr/?id=' + pixel_id + '&ev=PageView&ud[em]=' + user_email;
document.body.appendChild(fbtag);

You can also do the same for a Lead standard event:
var fbtag = document.createElement('img');
var user_email = 'USER_HASHED_EMAIL_IN_SHA256';
var pixel_id = 'XXXXXXXXX';
fbtag.src = 'https://www.facebook.com/tr/?id=' + pixel_id + '&ev=Lead&ud[em]=' + user_email;
document.body.appendChild(fbtag);

Or, of course, for a Purchase vent where extra data is added to the URL:
var fbtag = document.createElement('img');
var user_email = 'USER_HASHED_EMAIL_IN_SHA256';
var pixel_id = 'XXXXXXXXX';
var purchase_value = '999';
var purchase_currency = 'EUR';
var content_ids = '123,456,789'; // content identifiers separated by commas

fbtag.src = 'https://www.facebook.com/tr/?id=' + pixel_id + '&ev=Purchase&ud[em]=' + user_email + '&cd[value]=' + purchase_value + '&cd[content_ids]=' + content_ids + '&cd[currency]=' + purchase_currency;
document.body.appendChild(fbtag);

I know this is not perfect, but I've started to see advanced matching information in Facebook, so I guess it works properly :).
Just please remember that you should use SHA256 over the user's email address before sending it to Facebook to avoid issues with the GDPR laws :).


text:
Q: Vue-Resource gives TokenMismatchException in Ajax POST call Please note, I'm using the Laravel framework.
Also please note, there are similar questions on SO, I've checked them, but wasn't able to solve my problem based on those solutions...
Even though I set my CSRF token right to my knowledge, I'm not sure why it won't work.
When checking the console, it seems I have 3 cookies: two Request cookies of which one is called XSRF-TOKEN and one is called laravel_session. And one respone laravel_session cookie. All have a different value!!!
My Vue:
new Vue({
    el:'body',
    http: {
        root: '/root',
        headers: {
            'X-CSRF-Token': $('meta[name=_token]').attr('content')
        }
    },
});

My head:
<meta name="_token" content="{!! csrf_token() !!}"/>

My Vue component addNew method:
Vue.component('things',{
    template:'#things-panel-template',
    data(){
        return {
            list: [],
            newThing: {
                body: '',
                // _token: $('meta[name=_token]').attr('content'),
                // tried removing token from head meta and adding up here.
            },
        }
    },
    methods:{
        addNew(){
            var thing = this.newThing; // get input
            this.newThing = {body:''}; // clear input
            this.$http.post('/api/things/add',thing) // send
        },
    },
});

My route:
Route::post('/api/things/add',function(){
    return App\Thing::create(Request::get());
});

And finally, the form in my Vue Template:
<form action="/things/add"
        method="POST"
        @submit.prevent="addNew"
    >

            {{ csrf_field() }}
            Add
            <input type="text"
                name="body"
                id="task-body"
                class="form-control"
                v-model="newThing.body"
            >
            <button :disabled="!isValid"
                class="btn btn-primary"
                type="submit"
            >Add</button>

    </form>

A: Try this:
this.$parent.$http.post('/api/things/add', thing)

instead of
this.$http.post('/api/things/add', thing)

Or set default values using the global configuration:
Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');

A: I found the answer myself:
If you're gonna work with a vue-component, you should just add the token to that component instead. Otherwise it won't go with your ajax request.
So put this part underneath the template in the component:
    http: {
        root: '/root',
        headers: {
            'X-CSRF-Token': $('meta[name=_token]').attr('content')
        }
    },

Do this to check if your token was properly sent inside the headers:

*

*Go to google chrome, open dev-tools, go to the network tab and Reload.

*Make the ajax call and look at the file added in the network tab, open it and go to the 'Headers' tab.

*Look at the bottom where it says: 'Request Headers' and check if the token was properly added in the request.


text:
Q: Converting SQL query to Spark Dataframe structured data processing I want to convert the below query in spark dataframe:
sqlContext.sql("SELECT d.dep_name,count(*) FROM employees e,department d WHERE e.dep_id = d.dep_id GROUP BY d.dep_name HAVING count(*) >= 2").show

Output:
+---------+---+
| dep_name|_c1|
+---------+---+
|  FINANCE|  3|
|    AUDIT|  5|
|MARKETING|  6|

I tried it using below query:
scala> finalEmployeesDf.as("df1").join(depDf.as("df2"), $"df1.dep_id" === $"df2.dep_id").select($"dep_name").groupBy($"dep_name").count.show()
+---------+-----+
| dep_name|count|
+---------+-----+
|  FINANCE|    3|
|    AUDIT|    5|
|MARKETING|    6|
+---------+-----+

I know that this isn't correct coz suppose we have a case where we have only single entry for department then it will be also listed in these results but I want results to be displayed only if counts are greater than 2. So how can I achieve this ??? I tried googling but of no help in this case.

A: You have the group and aggregate parts wrong. You need to select all the relevant columns, group by and aggregate by the relevant once. Here is untested code which will represent the correct approach:
finalEmployeesDf.as("df1")
 .join(depDf.as("df2"), $"df1.dep_id" === $"df2.dep_id")
 .select($"dep_name")
 .groupBy($"dep_name")
 .agg(count($"dep_name").as("cnt"))
 .filter($"cnt" > 2)
 .show()

A general suggestion is to try and break the API calls into several lines, this makes reading and understanding much easier.

A: Try something like this:
DF.groupBy("x").agg(count("*").alias("cnt")).where($"cnt" > 2)