text:
Q: opengl: unable to draw left wall I am trying to start building a very basic room using opengl.  For some reason in the function drawWalls() the left wall doesn't get drawn or i'm misunderstanding the camera positioning.  Does anyone have any idea why I can't see the left wall when running this code?
my code:
#include <gl/gl.h>
#include <gl/glut.h>

/*defining colors used in the room*/
GLfloat black[] = {0.0, 0.0, 0.0, 1.0};
GLfloat white[] = {1.0, 1.0, 1.0, 1.0};
GLfloat brown[] = {165.0/255.0, 42.0/255.0, 42.0/255.0, 1.0};

void drawFloor()
{
    glBegin(GL_QUAD_STRIP);
    glColor4fv(black);
    glVertex3f(0.0, 0.0, -3.0);
    glVertex3f(1.0, 0.0, -3.0);
    glVertex3f(2.0, 0.0, -3.0);
    glEnd();
}

void drawWalls()
{
    glBegin(GL_QUAD_STRIP);
    glColor4fv(white);

    glPolygonMode(GL_FRONT, GL_FILL);

//draw left wall
glVertex3f(0.0, 0.0, 2.0);
glVertex3f(0.0, 1.0, 2.0);
glVertex3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 1.0, 1.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);

//draw front wall
            glVertex3f(0.0, 0.0, 3.0);
            glVertex3f(0.0, 1.0, 3.0);
            glVertex3f(1.0, 0.0, 3.0);
            glVertex3f(1.0, 1.0, 3.0);
            glVertex3f(2.0, 0.0, 3.0);
            glVertex3f(2.0, 1.0, 3.0);
    glEnd();
}
void display()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, 0.0, 0.8, 0.0, 1.0, 0.0,  1.0, 0.0);
drawFloor();
    drawWalls();
    glFlush();
    glutSwapBuffers();
}

void reshape(int w, int h)
{
    glViewport(0, 0, (GLsizei) w, (GLsizei) h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
gluPerspective(60, (GLfloat) w / (GLfloat) h, 1, 500);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

void idleFunc()
{
    glutPostRedisplay();
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(0, 0);
    glutCreateWindow("My room");
    glEnable(GL_DEPTH_TEST);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutIdleFunc(idleFunc);
    glutMainLoop();
}

A: Why do you expect to see the left wall? It is off-screen (for any reasonable aspect ratios of your window). If we imagine some "world space", you'll have the folliwing situation: Your camera is placed at the origin and looking at almost diagonal vector. The lfet wall is placed at x=0 too, so you have almost 45 degrees between the view direction and the wall. Your frustum starts at distance 1 in front of the camera, and has a vertical FOV of 60 degrees, and the horizontal FOV is defined by the aspect ratio of the window. So if you make the window much wider than tall, you have a chance of seeing that wall.


text:
Q: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted - NodeJS, Express & Webpack I am developing a web application using Node.js, Express & Webpack. Everything was going well until Webpack was upgraded to Webpack 5 and lots of bugs appeared. I have managed to solve all the errors but there is a warning I can't solve. I have seen this post but it's related to Angular so I don't think it helps me much: Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
WARNING in ./node_modules/terser-webpack-plugin/dist/minify.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

This is my webpack.config.js; resolve fields and node-polyfill-webpack-plugin are used to solve Webpack 5 bugs and errors.
    const path = require("path")
    const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
    const webpack = require('webpack')
    const HtmlWebPackPlugin = require("html-webpack-plugin")
    module.exports = {
      resolve:{
        fallback: {
        "fs": false,
        "path": false,
        "worker_threads":false,
        "child_process":false,
        "http": false,
        "https": false,
        "stream": false,
        "crypto": false,
        }
      },
      entry: {
        main: './src/js/main.js',
        index:'./src/js/'
      },
      output: {
        path: path.join(__dirname, 'dist'),
        //publicPath: '/',
        filename: '[name].js'
      },
      mode:"development",
      target: 'web',
      devtool: 'source-map',
      module: {
        rules: [
          {
            test: /\.(png|jp(e*)g|svg)$/,
            use: [{
                loader: 'url-loader',
                options: {
                    limit: 8000, // Convert images < 8kb to base64 strings
                    name: 'images/[hash]-[name].[ext]'
                }
            }]
          },
          {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: "babel-loader",
          },
          {
            test: /\.bpmn$/,
            use: 'raw-loader'
          },
          {
            // Loads the javacript into html template provided.
            // Entry point is set below in HtmlWebPackPlugin in Plugins
            test: /\.html$/,
            use: [
              {
                loader: "html-loader",
                //options: { minimize: true }
              }
            ]
          },
          {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
          }
        ]
      },
      plugins: [
        new HtmlWebPackPlugin({
          template: '!!raw-loader!./src/views/pages/index.ejs',
          filename: "./index.ejs",
          excludeChunks: [ 'server', 'main' ]
        }),
        new HtmlWebPackPlugin({
          template: '!!raw-loader!./src/views/pages/bmv.ejs',
          filename: "./bmv.ejs",
          excludeChunks: [ 'server', 'index' ]
        }),
        new webpack.NoEmitOnErrorsPlugin(),
        new NodePolyfillPlugin()
      ]
    }

A: configure the webpack:
const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      'terser-webpack-plugin': path.resolve(__dirname, 'node_modules/terser-webpack-plugin/dist/minify.js'),
    },
  },
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show that $g$ is not topologically conjugate to the tent function Question: Define the function $g : [0, 1]\mapsto [0, 1]$ by
$g(x)=\begin{cases}3x&\text{if}\;\;0\le x\le \frac{1}{3}\;\;\\{}\\
2-3x&\text{if}\;\;\frac{1}{3}\le x\le \frac{2}{3}\;\;\\{}\\
3x-2&\text{if}\;\;\frac{2}{3}\le x\le 1\;\;\\{}\\\end{cases}$
Show that $g$ is not topologically conjugate to the tent function.
Def.: The functions $f : X\mapsto X$ and $g : Y\mapsto Y$ (and the
dynamical systems defined by them) are said to be topologically conjugate if
there exists a homeomorphism $h : X\mapsto Y$ such that $g\circ h = h\circ f$. The
function h is called a topological conjugacy between $f$ and $g$.
If I must show that there is no $h(x)$ such that $g\circ h = h\circ f$, I don't have any clue how to guess some $h(x)$ at all; even though, it's not a proof it's 'many examples'.
Also, I don't know which of tent functions writer is mentioning; i.e., for what $n$ in $T^n$. The pictures for $T^1$ and $T^2$ follows:

Thank you.

A: Consider the solutions of $g\circ h=\frac{1}{2}$ and $h\circ T=\frac{1}{2}$ (or $h\circ T^n=\frac{1}{2}$ if you want or need to prove it for any number of tents).
Solving $g\circ h=\frac{1}{2}$:
$g=\frac{1}{2}$ at $3$ points in the interior of $[0,1]$. These points are mapped by $h^{-1}$ to three interior points of $[0,1]$.
Solving $h\circ T=\frac{1}{2}$:
$h^{-1}$ maps $\frac{1}{2}$ to an interior point $a\in[0,1]$. Then $T=a$ (or $T^n$) at an even number of points.


text:
Q: Analytic Continuation proof questions

Q1. How does $F(\zeta) = F(z) = 0 \implies F'(z) = 0$? What about the denominator? Don't we have a $0/0$ situation?
Q2. How does continuity imply $F$ and its derivatives vanish at $w$?

A: 1) Because the function $G(\zeta):=\dfrac{F(\zeta)-F(z)}{\zeta-z}$ on $\mathcal N\backslash\{z\}$ is the zero function, i.e, $G(\zeta)=0$ for all $\zeta\in\mathcal N\backslash\{z\}$, therefore its limit for $\zeta\to z$ is $0$.
We're not in the $0/0$ situation. It's as asking if $$\lim_{x\to 0}\dfrac{0}{x}=0$$ is wrong because it's the $0/0$ situation.
2) Let $F^{(n)}$ be the $n$-th derivative of $F$ for some $n\in\mathbb N$ (with $F^{(0)}=F$ by convention). Since $F$ is analytical on $D$, $F^{(n)}$ is continuous on $D$. In particular, for any parametric curve $\gamma(t)$ in $D$ so that $\gamma(1)=w$, we have $\lim_{t\to 1^-}F^{(n)}(\gamma(t))=F^{(n)}(w)$. In particular for the curve used in the proof, we have $F^{(n)}(\gamma(t))=0$ for $t\in (0,1)$ (so that $\gamma(t)$ is inside $\mathcal N$ for $t\in (0,1)$. Thus $F^{(n)}(w)=0$.


text:
Q: Inconsistent number of samples K Nearest Neighbor sklearn I'm doing some self training on stuff from guidetodatamining.com and am working on some K Nearest Neightbor stuff using sklearn. I am getting the error: ValueError: Found input variables with inconsistent numbers of samples: [2, 20]
When I run this code:
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
cols= ['Name', 'Sport', 'Height', 'Weight']
df = pd.read_table("https://raw.githubusercontent.com/zacharski/pg2dm-python/master/data/ch4/athletesTrainingSet.txt",  names = cols, index_col='Name')
df = df[1:]
df = df[ ['Height', 'Weight','Sport'] ]
knn = KNeighborsClassifier(n_neighbors=2)
X= df.Height, df.Weight
y = df.Sport
knn.fit(X, y)
knn.predict(X)

In the dataset there are 20 in each of the three rows so I have no idea whats happening.
I am trying to use the Height and Weight friends to help train the Sport field, so that if you put some data in it "recommends" what sport a person would play. I know theres several similar topic about the LinearRegression tool but I can't get any of the solutions on those to work for me. I have tried reshaping my data, and I have tried doing just height or weight but that gives me an error on a 1D instead of 2D array.
Even just a helpful nudge in the right direction would be incredibly helpful as I have been staring at this for 2 days now with no solution. Thank you.

A: Your problem is in your x,y creation. x is two pandas data series and y is just one serie. Creating two new dataframes can solve your problem. You can run your code line by line to locate it.
x= df[["Height","Weight"]]
y = df[["Sport"]]

You can try splitting your dataset into to sets. Your model can be train on one set and be validated in the other.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x,y,test_size=0.2)
knn.fit(X_train, y_train)
knn.predict(X_test)

You can save your target value and prediction into a dataframe and check them.
comp_results=pd.concat([y_test,pd.DataFrame(data=knn.predict(X_test),index=y_test.index.values.tolist())],axis =1).rename(columns={"Sport":"Target",0:"Prediction"})


text:
Q: Trying to find time difference in Joda Time between 2 DateTime objects I'm trying to find the difference between 2 times using Joda Time.  I've tried using some of the examples on here and can not get a value to return.  Here is what I've tried:  Where time is in a format like 17:23 and the to and from variables are time zones like America/Los_Angeles or Europe/London
    DateTime dtFrom = DateTime.now()
    DateTime dtTo = new DateTime(dtFrom.withZone(DateTimeZone.forID(to)));
    //calculate time difference
    Period period = new Period(dtTo, dtFrom) ;
    Minutes minutes = Minutes.minutesBetween(dtFrom, dtTo);
    long diffInMillis = dtFrom.getMillis() - dtTo.getMillis();

I've tried using different methods to compare these two and always get no value returned...period returns PT0S, minutes returns PT0M, and diffInMillis returns 0.   What am I doing wrong here?  Thanks!

A: You are using the method withZone() which is defined to preserve the (POSIX) instant in milliseconds since 1970-01-01T00:00Z. So dtFrom and dtTo have still the same instant meaning they describe the same global time although their local time representations are different due to different time zones.
Result: The difference between two same instants is exactly equal to zero regardless which time unit you use.
However, if you are interested into the local time difference instead please determine the zone offset difference, for example using the method getOffset().


text:
Q: Morphism from Automorphism group of stable curve to automorphism group of its dual graph surjective I currently study the strata of the moduli stack of algebraic curves and have understood, that for a stable curve with markings $p_1, \dots, p_n$ there is a morphism of groups $Aut(C, p_1, \dots, p_n) \to Aut(\Gamma)$, where $\Gamma$ is the associated stable graph. I also see, that because of automorphisms of the connected components of the normalisation that are not "seen" by the graph, in general this morphism is not injective.
But is it surjective? In all the examples I have considered I think it is, but I do not see a general argument to show that, so I am thankful for any hints.


text:
Q: Dropdown menu disappear when i'm trying to hover the list I have an issue with dropdown menu. I've tried different solutions, but seems that no one of them works. I'm using SCSS, and i need that my dropdown menu keep being active once i hover the burger menu.
What happen is that whenever i hover it, it disappear after moving the mouse out of the div.
Here is my code:
    .burger {
    cursor: pointer;
    color: white;
    position: relative;
    &:before{
        font-family: "Font Awesome 5 Free";
        font-weight: 900;
        content: "\f0c9";
        margin-right: .2rem;
    }
    &:after{
        content: 'Menu';
        text-transform: uppercase;
    }
    &:hover .dropdown, .dropdown:hover {
        display: block;
        z-index: 99;
    }
}
.dropdown {
    display: none;
    position: absolute;
    width: 150px;
    top: calc(5vh - 1px);
    right: -10vw;
    background: black;

}

This is my template, using Pug.js Template Engine:
            ul.mobile
            div.burger
                div.dropdown
                    ul
                        each item in navigation
                            li
                                i(class=item.icon)
                                a(href=item.link)= item.name

Thank you very much for your help!
https://codepen.io/makkoyev/pen/abojxvG


text:
Q: Hibernate Relationship Mapping/Speed up batch inserts I have 5 MySQL InnoDB tables: Test,InputInvoice,InputLine,OutputInvoice,OutputLine and each is mapped and functioning in Hibernate. I have played with using StatelessSession/Session, and JDBC batch size. I have removed any generator classes to let MySQL handle the id generation- but it is still performing quite slow.
Each of those tables is represented in a java class, and mapped in hibernate accordingly. Currently when it comes time to write the data out, I loop through the objects and do a session.save(Object) or session.insert(Object) if I'm using StatelessSession. I also do a flush and clear (when using Session) when my line count reaches the max jdbc batch size (50).

*

*Would it be faster if I had these in a 'parent' class that held the objects and did a session.save(master) instead of each one?

*If I had them in a master/container class, how would I map that in hibernate to reflect the relationship? The container class wouldn't actually be a table of it's own, but a relationship all based on two indexes run_id (int) and line (int).

*Another direction would be: How do I get Hibernate to do a multi-row insert?

A: The final solution for me was to use voetsjoeba's response as a jumping off point.
My hibernate config uses the following options:
hibernate.order_inserts = true
hibernate.order_updates = true

*

*I changed from using Session to
StatelessSession

*Re-ordered the
Java code to process all the elements
in a batch a table at a time. So all
of table x, then table y, etc.

*Removed the <generator> from each
class. Java now creates it and
assigns it to the object

*Created logic that allowed me to determine if just
an id was being set and not write
'empty' lines to the database

*Finally, I turned on dynamic-insert
for my classes in their hibernate
definitions like so: <class name="com.my.class" table="MY_TABLE" dynamic-insert="true">

A: The ID generation strategy is critical for batch insertion in Hibernate. In particular, IDENTITY generation will usually not work (note that AUTO typically maps to IDENTITY as well). This is because during batch insert Hibernate has a flag called "requiresImmediateIdAccess" that says whether or not generated IDs are immediately required or not; if so, batch processing is disabled.
You can easily spot this in the DEBUG-level logs when it says "executing identity-insert immediately" - this means it has skipped batch processing because it was told that generated IDs are required immediately after insertion.
Generation strategies that typically do work are TABLE and SEQUENCE, because Hibernate can pre-generate the IDs, thereby allowing for batch insertion.
A quick way to spot whether your batch insertion works is to activate DEBUG-level logs as BatchingBatcher will explicitly tell you the batch size it's executing ("Executing batch size: " + batchSize ).
Additionally, the following properties are important for achieving batch insertion. I daren't say they're required as I'm not enough of a Hibernate-expert to do so - perhaps it's just my particular configuration - but in my experience they were needed nonetheless:
hibernate.order_inserts = true
hibernate.order_updates = true

These properties are pretty poorly documented, but I believe what they did was enable for the SQL INSERT and UPDATE statements to be properly grouped for batch execution; I think this might be the multi-row inserts you're after. Don't shoot me if I'm wrong on this, I'm recalling from memory.
I'll also go ahead and assume that you set the following property; if not, this should serve as a reminder:
hibernate.jdbc.batch_size = xx

Where xx is your desired batch size, naturally.


text:
Q: Git Bash behavior changed after Windows restart - won't run login script on launch After a Windows 10 restart, Git Bash behavior changed.
Previously I used to get like below

After Windows 10 restart, I get like below. Looks like it isn't executing the login script on launch.

Also get this warning now

Reinstallation of Git doesn't help.


text:
Q: change maven j2ee deploy name I'm developing an app in maven and it's deploy name is concatenation of artifactId + "_" + groupId + "_" + "packaging" + "_" + version which is pretty ugly. And I'm lookuping for an EJB and I would need to change the uri after eventual version change.
Do you know how to change this deploy name?
I'm deploying it via netbeans.

A: it's a netbeans bug and will be available in build 201102050000.
Netbeans bug

A: Check documentation about finalName which should do the trick.


text:
Q: How does the "Send Mail As" feature work (at a technical level) in Gmail? I don't have any technical problems, but I have a question that I would like to be answered out of curiosity.
Here is my current understanding of how email works:
One of the privileges of having your own domain is that you can hook it up to IMAP/POP3/SMTP servers and use them to send and receive messages to and from "anyone@yourdomain.com". With spam being such a problem, however, the SMTP server that you use to send messages must add a bunch of headers (DKIM, SPF, etc) to each message that you send in order to prove that the SMTP server has the authority to send emails from that domain. The receiving SMTP server can cross-check those headers with DNS records that it finds to verify the legitimacy of the email message.
So if you want to send emails with your domain cheaply, you can use Gmail's "Send Mail As" feature. I followed this help article to get mine working: https://support.google.com/domains/answer/9437157
Note: I unchecked the "Treat as an alias" option during the setup.
But wait... no additional DNS configuration required? I have my domain registered with Cloudflare, and there are no entries related to Google in there.
There is this step in the setup process:

But it seems that this only for Google to prevent you from using their servers to send spam. What is stopping Google from impersonating any email address they want? Why do receiving SMTP servers trust an email from "anyone@yourdomain.com" if Google's SMTP servers have no way of adding legitimate SPF/DKIM headers?

A: The short answer is that nothing prevents Google from doing this, and that DMARC was created for exactly this case.

There is nothing that stops Google from impersonating any domain. However, there are things receivers can (and should) do when they receive an email which isn't send from the server indicated in the From: field.
Try sending an email from the alias you just added to a different @gmail.com inbox. You will see that it says via gmail.com behind the sender email address. But other email receivers might do more: flag this message with red exclamation marks and scam warnings, throw it into spam or even deny receiving it completely. Gmail probably has some hardcoded trust, but try doing this from your own SMTP server and the above will very likely happen.
As you say in your question, you can authorize your emails by marking gmail.com as an authorized sender with SPF (which protects against forging from other domains, but doesn't stop Google), or even sign your emails with DKIM (not possible from Gmail UI, but you can do this in some email clients or send email with a custom Python script like me; Google can't do this without knowing the key).
However, that only solves one side of the problem – authorizing legitimate email messages. But what if an SMTP server still receives an unverified email? What if they have previously received an email from the same sender which was DKIM signed? What if DKIM passes, but SPF fails?
Because the behavior in that case is largely unspecified, and also the sender wants to check if their DKIM/SPF authorizations are actually working, and if anyone is attempting to spoof them, another standard was created: DMARC. It introduces another DNS TXT record where you can say what checks are required to pass, what to do if they fail, and also what basic analytics should the receivers report to the owner of the domain.

A: Of all webmail client providers, Google's Send mail as is actually the most well-implemented for a variety of reasons.
First of all, how it works is not different from when you set up POP3 or IMAP using a mail client like Outlook or Thunderbird. You have to specify the domain and port where you receive emails from, and the domain and port where you send emails from. For example, Google's incoming and outgoing servers for IMAP are as follows:

*

*imap.gmail.com:993

*smtp.gmail.com:465

The Send mail as feature is a partial implementation of that. It only implements the outgoing part.
How mail clients like Outlook and Thunderbird send emails, is basically that it sends the email to the outgoing mail server, and the outgoing mail server then sends the email. Usually, outgoing mail servers will require some sort of authentication, and will allow authenticated users to only send from specific email addresses.
Gmail works the same way. The outgoing mail server is the one that has to pass the SPF and DKIM tests, not Google's servers.
No other webmail clients do this. Hotmail used to do this, but they recently removed the feature. Now, the option is very difficult to find, and they just rewrite your FROM address and sends your email from Hotmail's SMTP server, which creates delivery problems.
They don't provide you with the option to send emails from another SMTP server, because this allows people to very easily set up virtual mail servers that can send emails under a domain of your choice, but use say a typical free Hotmail account to store incoming mails. This takes away business from their paid services, because both Hotmail and Gmail sell the option to host your company emails. I'm sure Google also knows about this, but it is really awesome of them to still keep the option available to free Gmail users.
If you want to learn more about virtual email servers, you can check out this article here: https://blog.terresquall.com/2022/01/setting-up-a-virtual-postfix-mail-server-part-1/


text:
Q: How to trigger a phone field to format a phone number Our Custom_Object__Primary_Phone__c field (type: phone) has tens-of-thousands of numbers not formatted and I am looking for a way to touch this field to initiate an update so the result will be a correctly-formatted US phone number, e.g. (###) ###-####.
Is there a trick that anyone knows other than: export; strip excess characters and spaces; import?

A: You could use apex or even writte trigger to make shure that any new record would be set up right :)
There is function REGEX with which you can check if that field is in corret format and if it is not some small code could change it.
To match you phone number use regex: "\([0-9]{3}\)[0-9]{3}-[0-9]{4}" if i am not misstaken at some moment ( still learning regex so please check it with some programer )
Edit:
Usefull article: https://help.salesforce.com/articleView?id=000181563&language=en_US&type=1
And usefull page for regex: https://www.regular-expressions.info/nonprint.html

A: I was initially using the Data Loader to no avail and decided to use the Data Import Wizard with the same data file - this works!
Just map ID in the CSV file to Salesforce.Com:ID and the custom phone fields in the DB to the file.


text:
Q: ModuleNotFoundError: No module named 'qgis' MacOS trying to setup pycharm for QGIS development in MacOS. I added to the interpreter path the QGIS bin path  /Applications/QGIS.app/Contents/MacOS/bin but still no luck.
All the guides I find are for windows.
    from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
ModuleNotFoundError: No module named 'qgis'

Any suggestions?

A: Before executing your python code, export the QGIS Python path:
export PYTHONPATH=/Applications/QGIS.app/Contents/Resources/python

if QGIS is installed in the default path.


text:
Q: Is there a way to fire over events ignoring z-index? If I have something like this:

Is there a way to fire the mouseover events on BOTH divs?
Edit: Sorry all .. I tried to simplify the problem so it was clear to understand and I forgot to mention I have more than 100 divs like that so probably those solutions don't work. I'm going to see if I can adapt them.

A: I put together a working example here with JSFiddle:
http://jsfiddle.net/gfosco/CU5YT/
It's similar to madeinstefanos answer, but specific to your example..
var mouseX = 0;
var mouseY = 0;
var front = 0;
var back = 0;

function log(text) {
    $("#log").append(text + '
');
}

function mouseWithin(selector) {
  var pos = $(selector).position();
  var top = pos.top;
  var left = pos.left;
  var height = $(selector).height();
  var width = $(selector).width();

  if (mouseX >= left && mouseY >= top && mouseX <= left + width
                     && mouseY <= top + height) {
    return true;
  }
  return false;
}

$(document).bind('mousemove', function(e) {
    mouseX = e.pageX;
    mouseY = e.pageY;
    if (front == 1 && !mouseWithin("#front")) {
            front = 0;
            log('Front Leave');
    }
    if (back == 1 && !mouseWithin("#back")) {
            back = 0;
            log('Back Leave');
    }
    if (front === 0 && mouseWithin("#front")) {
            front = 1;
            log('Front Hover');
    }
    if (back === 0 && mouseWithin("#back")) {
            back = 1;
            log('Back Hover');
    }

});

A: It's possible. You cannot get the mouseenter|mouseover event for a part of a element that is below another element, but if you know the dimensions and the position of the element, you can listen for mousemove event and get when the mouse enters in some particular area.
I created two divs, like yours:

And I want to know when the mouse enters the area occuped by the div that is below, to do that I wrote this script:
$(function (){

  var divOffset = {
    top: $("#belowDiv").position().top,
    left: $("#belowDiv").position().left,
    right: $("#belowDiv").position().left + $("#belowDiv").width(),
    bottom: $("#belowDiv").position().top + $("#belowDiv").height(),
    isOver: false
  }

  $(window).mousemove(function (event){
    if (event.pageX >= divOffset.left && event.pageX <= divOffset.right && event.pageY >= divOffset.top && event.pageY <= divOffset.bottom){
      if (!divOffset.isOver){
        divOffset.isOver = true;

        /* handler the event */
        alert("gotcha");
      }
    }else{
      if (divOffset.isOver){
        divOffset.isOver = false;
      }
    }
  });
});

It's not simple as listen for mousenter|mouseover, but works fine.
Here a link to fiddle


text:
Q: Sqlplus Segmentation fault I am getting a Segmentation fault when trying to login to Oracle through sqlplus.
gary@gary-desktop /usr/lib/oracle/12.1/client64 $ sqlplus web@DEV1
SQL*Plus: Release 12.1.0.1.0 Production on Thu Jul 17 13:26:13 2014
Copyright (c) 1982, 2013, Oracle.  All rights reserved.

Enter password:
Segmentation fault

I can connect successfully with Oracle JDBC This client(ojdbc6.jar). My url looks like this: jdbc:oracle:thin:@192.168.153.72:1521:DEV1
My OS is Linux Mint 14 Nadia
I installed installed the following oracle packages:
 - oracle-instantclient12.1-basic_12.1.0.1.0-2_amd64.deb
 - oracle-instantclient12.1-devel_12.1.0.1.0-2_amd64.deb
 - oracle-instantclient12.1-sqlplus-12.1.0.1.0-1.x86_64.rpm

tnsnames.ora looks like this:
DEV1 =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.153.72)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SID = DEV1)
    )
  )

If anyone has the answer I would appreciate it.

A: this is linking problem you must try this Another option would be re-install Oracle database software but relinking is a much faster.
   $ORACLE_HOME/bin
              relink all

A: Was trying to connecting to an Oracle 11.2.0.3.0 server.
After uninstalling instant client 12.1.0.1.0 and installing instant client 11.2.0.3.0 everything worked fine.

A: Using sudo works for me.
sudo ./sqlplus
That's because i read it couldn't access to the memory.


text:
Q: DRF canned filter - best practice? I use Django REST Framework in my Django app to provide an API, and have recently added filtering. To support a couple of things in the UI, I'd like to be able to provide some canned/named filter presets - for example, there's a /api/tasks viewset that gives you a list of all the tasks. Tasks have a completed status field and a completion date. In the UI, I'd like to be able to fetch a list of all tasks that are either incomplete, or completed but within the last couple of hours. This is easy enough with Django querysets but not with the DRF filters - the final goal would be to be able to fetch /api/tasks?recent or something similar.
Is there a best practice for doing this kind of thing? I can create a new ViewSet with a different queryset field, but is there a nicer way?
Edit: Here's my current solution:
class PushTaskViewSet(AuthenticatedAPIModelViewSet):
    queryset = PushTask.objects.all()
    serializer_class = PushTaskSerializer
    filter_fields = ('complete', 'date_created', 'date_completed', 'progress')

class RecentPushTaskViewSet(AuthenticatedAPIModelViewSet):
    # Get all tasks which are either incomplete, or only recently completed
    serializer_class = PushTaskSerializer

    def get_queryset(self):
        return PushTask.objects.filter(Q(complete=False) | Q(date_completed__gt=self.get_completed_threshold()))

    def get_completed_threshold(self):
        return datetime.now(tz=pytz.utc) - timedelta(hours=4)

router.register(r'master-tasks', viewsets.PushTaskViewSet)
router.register(r'recent-master-tasks', viewsets.RecentPushTaskViewSet, base_name="recent-master-tasks")

which does work, but just feels clunky.

A: You can use DjangoFilterBackend. For detailed information, see the documentation.
After installation django-filter lib don't forget to add DjangoFilterBackend in the settings.py file:
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',
     )
}

and then use it in the view:
class TaskListCreateView(ListCreateAPIView):
    filter_backends = (DjangoFilterBackend,)
    filter_fields = ('status', )
    serializer_class = TaskSerializer

Alternative way to filter objects is use Filtering against query parameters. For this just to override get_queryset method:
class TaskListCreateView(ListCreateAPIView):
    def get_queryset(self):
        queryset = Task.objects.all()
        status = self.request.query_params.get('status', None)
        if status:
            queryset = queryset.filter(status=status)
        return queryset


text:
Q: Unable to enable logs in MySQL - error : Found option without preceding group in config file I am trying to enable logs on my MySQL server but with no success.
What I have done :
1) I have created the log file with the right permissions :
touch /var/log/mysql/mysql.log
chown mysql:mysql /var/log/mysql/mysql.log

2) I have added the needed change to the my.cnf file :
general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

My my.cnf file is the following :
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

I am unable to restart MySQL and when I try to logging, I have this error :

error: Found option without preceding group in config file:
  /etc/mysql/my.cnf at line: 23 Fatal error in defaults handling.
  Program aborted

What does that mean and how I can fix this ?
I am using Ubuntu 15.05 with MySQL 5.6.24-0ubuntu2

A: Perhaps you should add [mysqld] as a first line of your my.cnf file.

A: Open my.conf, look for [mysqld] under that write the server variable as mentioned below.
log = /var/log/mysqld.log
log-error = /var/log/mysqld.error.log

Make sure the file has 644 or above permission. Look for mysql error log variable using
show variables like '%log%';
Latest mysql is using log, log-error variables.
Thanks
Amit

A: In my case I had the section [mysqld] correctly set, but this error was caused by invalid whitespace character at the begin of the file. It caused failure in parsing the file. Character was inserted there somehow during copying/uploading from windows to linux. I needed to open file by linux file viewer and then delete invalid character and then it worked fine.


text:
Q: Sending private messages to user I'm using the discord.js library and node.js to create a Discord bot that facilitates poker. It is functional except the hands are shown to everyone, and I need to loop through the players and send them a DM with their hand.
bot.on("message", message => {
  message.channel.sendMessage("string");
});

This is the code that sends a message to the channel when any user sends a message. I need the bot to reply in a private channel; I've seen dmChannel, but I do not understand how to use it. I have the username of the member that I want to send a message to.
An example would be appreciated.
Edit:
After looking around for a user object, I found that I can get all of the users using the .users property of the client (bot). I will try using the user.sendMessage("string") method soon.

A: To send a message to a user you first need to obtain a User instance.
Obtaining a User instance

*

*use the message.author property of a message the user sent .

*call client.users.fetch with the user's id

Once you got a user instance you can send the message with .send
Examples
client.on('message', (msg) => {
 if (!msg.author.bot) msg.author.send('ok ' + msg.author.id);
});

client.users.fetch('487904509670337509', false).then((user) => {
 user.send('hello world');
});

A: The above answers work fine too, but I've found you can usually just use message.author.send("blah blah") instead of message.author.sendMessage("blah blah").
-EDIT- : This is because the sendMessage command is outdated as of v12 in Discord Js
.send tends to work better for me in general than .sendMessage, which sometimes runs into problems.
Hope that helps a teeny bit!

A: In order for a bot to send a message, you need <client>.send() , the client is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use message.author as your client. (you can replace author as mentioned user in a message or something, etc)
Hence, the answer is: message.author.send("Your message here.")
I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.

A: If your looking to type up the message and then your bot will send it to the user, here is the code. It also has a role restriction on it :)

case 'dm':
  mentiondm = message.mentions.users.first();
  message.channel.bulkDelete(1);
  if (!message.member.roles.cache.some(role => role.name === "Owner")) return message.channel.send('Beep Boing: This command is way too powerful for you to use!');
  if (mentiondm == null) return message.reply('Beep Boing: No user to send message to!');
  mentionMessage = message.content.slice(3);
  mentiondm.send(mentionMessage);
  console.log('Message Sent!')
  break;

A: Just an FYI for v12 it's now
client.users.fetch('487904509670337509', false).then((user) => {
 user.send('heloo');
});

where '487904509670337509' is an id number.

A: This is pretty simple here is an example
Add your command code here like:
if (cmd === `!dm`) {
 let dUser =
  message.guild.member(message.mentions.users.first()) ||
  message.guild.members.get(args[0]);
 if (!dUser) return message.channel.send("Can't find user!");
 if (!message.member.hasPermission('ADMINISTRATOR'))
  return message.reply("You can't you that command!");
 let dMessage = args.join(' ').slice(22);
 if (dMessage.length < 1) return message.reply('You must supply a message!');

 dUser.send(`${dUser} A moderator from WP Coding Club sent you: ${dMessage}`);

 message.author.send(
  `${message.author} You have sent your message to ${dUser}`
 );
}

A: If you want to send the message to a predetermined person, such as yourself, you can set it so that the channel it would be messaging to would be their (your) own userID. So for instance, if you're using the discord bot tutorials from Digital Trends, where it says "to: ", you would continue with their (or your) userID. For instance, with how that specific code is set up, you could do "to: userID", and it would message that person. Or, if you want the bot to message you any time someone uses a specific command, you could do "to: '12345678890'", the numbers being a filler for the actual userID. Hope this helps!

A: Make the code say if (msg.content === ('trigger') msg.author.send('text')}


text:
Q: How to format the result set of parent child records? All,
I have a result set coming from several SQL Server tables, and I need to know what the best way to get the sorted records I need would be.
I have the following records; a user name and module number as parent records, and then for each of these modules there are multiple sub-module child records. The problem I'm having is that the module record has an association with each sub-module record. Therefore I get the following records back from my stored procedure:
NAME            Module  Sub-module
Derek Kenney    1       1
Derek Kenney    1       2
Derek Kenney    1       3
Derek Kenney    1       4
Derek Kenney    1       5

What I want is:
NAME            Module  Sub-module
Derek Kenney    1       1
                        2
                        3
                        4
                        5

I think my problem is within my sproc which I posted below.

ALTER PROCEDURE [dbo].[uspGetReportData]

AS
BEGIN
    SELECT first_name, last_name, email, country_id, T_User_Info.user_id, T_Modules_Viewed.module_id as 'modules viewed', T_Modules_Completed.module_id as 'modules completed'
     FROM T_User_Info inner join T_Modules_Viewed on T_User_Info.user_id = T_Modules_Viewed.user_id left outer join T_Modules_Completed
 on T_Modules_Viewed.user_id = T_Modules_Completed.user_id
END

Perhaps there is a way within ADO.NET to get the result set I want and I'm not aware of it. Any help would be appreciated.
Derek Kenney

A: try something like this:
DECLARE @YourData table (YourName varchar(20), Module char(1), SubModule char(1))

INSERT INTO @YourData VALUES ('Derek Kenney',1,1)
INSERT INTO @YourData VALUES ('Derek Kenney',1,2)
INSERT INTO @YourData VALUES ('Derek Kenney',1,3)
INSERT INTO @YourData VALUES ('Derek Kenney',1,4)
INSERT INTO @YourData VALUES ('Derek Kenney',1,5)
INSERT INTO @YourData VALUES ('Derek Kenney',2,1)
INSERT INTO @YourData VALUES ('Derek Kenney',2,2)
INSERT INTO @YourData VALUES ('Derek Kenney',2,3)
INSERT INTO @YourData VALUES ('Joe Smith'   ,1,1)
INSERT INTO @YourData VALUES ('Joe Smith'   ,2,1)
INSERT INTO @YourData VALUES ('Joe Smith'   ,2,2)

SELECT
    CASE WHEN NameRank=1 /*OR NameModuleRank=1*/ THEN YourName ELSE '' END AS YourName
        ,CASE NameModuleRank WHEN 1 THEN Module ELSE '' END AS Module
        ,SubModule
    FROM (SELECT
              YourName,Module,SubModule
                  ,ROW_NUMBER() OVER(partition by YourName ORDER BY YourName) AS NameRank
                  ,ROW_NUMBER() OVER(partition by YourName,Module ORDER BY YourName,Module) AS NameModuleRank
              FROM @YourData
         ) dt

OUTPUT:
YourName             Module SubModule
-------------------- ------ ---------
Derek Kenney         1      1
                            2
                            3
                            4
                            5
                     2      1
                            2
                            3
Joe Smith            1      1
                     2      1
                            2

(11 row(s) affected)

if you want, you can uncomment the OR in the case to show the YourName when the Module changes


text:
Q: R inline code not executing in RMarkdown only when generating HTML through javascript I am currently building a RMarkdown Flexdashboard and generating HTML code template through javascript. When I generate my HTML my inline R does not seem to work. The code is as such below.
```{js, class.source="vis1", results='asis'}
for(i = 1; i < 2; i++){
    $('<p id="vis">`r {1 + 1;}`</p>').insertAfter(".vis1");
}
```

I've also tried the following below to no avail.
```{js, class.source="vis1", results='asis'}
for(i = 1; i < 2; i++){
    $('<div id="vis">```\n {r} 1 + 1 \n```</div>').insertAfter(".vis1");
}
```

This is the output the "test: 2" <- uses inline `r 1 + 1` just to show that it is working otherwise.

* I have started to think this may be due to setting results='asis' *

A: set i to 0 otherwise it would only run once
for(i = 0; i < 2; i++){
    $('<p id="vis">`r {1 + 1;}`</p>').insertAfter(".vis1");
}

A: You cannot have inline R code inside a code chunk. In your case, you cannot have inline R code in a js code chunk. You can use the <script> tag directly, e.g.,
<script>
alert("`r 1 + 1`");
</script>


text:
Q: Putting 'that' after 'have always been' What I've known so far concerning the usage of past perfect is that this tense will be used when someone did something and he/she wants to talk about it in the present or the event itself still holds in the present (that'd be my best definition of its usage).
However, there was a sentence from my book that has confused me:

That argument is out-of-date in a modern technology. Our position
has always been that we should encourage technology.

I feel there's a missing word there i.e.
Our position has always been [something] that we should encourage technology.
Why did the writer leave that something out if my prediction is correct? Did he/she try to introduce their position since x?

A: A position is a noun, so after "Our position has always been...", we should expect a noun, the same way as if it were the simpler, "Our position is..."
The words, "that we should encourage technology" form a noun clause, which means it's a noun.
So your sentence is correct as is, and nothing is missing.


text:
Q: Почему ответ не выводится? Сколько существует целых значений числа A, при которых формула
((x < A) → (x^2 < 100)) ∧ ((y^2 ≤ 64) → (y ≤ A))
тождественно истинна при любых целых неотрицательных x и y?
Мой код:
for a in range(0,1000):
    f=True
    for x in range(1,100):
        for y in range(1,100):
            if ((not (x < a) or (x ** 2 < 100)) and (not(y ** 2 <= 64) or (y <= a))) == False:
                f=False
                if f == True:
                    print(a)

Я не вижу в нем ошибки

A: Поправить ваш код не сложно. Нужно исправить число пробелов в последних двух строках. Работает как задумано:
for a in range(0,1000):
    f=True
    for x in range(1,100):
        for y in range(1,100):
            if ((not (x < a) or (x ** 2 < 100)) and (not(y ** 2 <= 64) or (y <= a))) == False:
                f=False
    if f == True:
        print(a)

Некоторые доработки. Вы знаете логику, значит поймёте пару правил:
expr == False    ->    not expr
expr == True     ->        expr

Правила применимы только если expr имеет булев тип. Так что ещё правило: избегайте неявного приведения выражений другого типа к булеву.
Следующее правило: все операторы в коде одного уровня абстракции. Сейчас не так: смешано вычисление f (низкий уровень), проверка и печать (высокий уровень). Прячем вычисление:
def check(a):
    f=True
    for x in range(1,100):
        for y in range(1,100):
            if not ((not (x < a) or (x ** 2 < 100)) and (not(y ** 2 <= 64) or (y <= a))):
                f=False
    return f

for a in range(0,1000):
    if check(a):
        print(a)

Оптимизация: если единственное действие цикла присвоение константы, прерываем цикл немедленно. Функция check делает единственное действие, выходим из неё быстро:
def check(a):
    for x in range(1,100):
        for y in range(1,100):
            if not ((not (x < a) or (x ** 2 < 100)) and (not(y ** 2 <= 64) or (y <= a))):
                return False
    return True

Бизнес логика смешана с вычислениями. Разделяем:
def formula(a, x, y):
    # ((x < A) → (x^2 < 100)) ∧ ((y^2 ≤ 64) → (y ≤ A))
    return (not (x < a) or (x ** 2 < 100)) and (not (y ** 2 <= 64) or (y <= a))

def check(a):
    for x in range(1,100):
        for y in range(1,100):
            if not formula(a, x, y):
                return False
    return True

Знай и люби библиотеку языка. all проверяет что все элементы истинны:
def check(a):
    return all(
        formula(a, x, y)
        for x in range(1,100)
        for y in range(1,100)
    )

Всё вместе:
def formula(a, x, y):
    # ((x < A) → (x^2 < 100)) ∧ ((y^2 ≤ 64) → (y ≤ A))
    return (not (x < a) or (x ** 2 < 100)) and (not (y ** 2 <= 64) or (y <= a))

def check(a):
    return all(
        formula(a, x, y)
        for x in range(1, 100)
        for y in range(1, 100)
    )

for a in range(1000):
    if check(a):
        print(a)

$ time python formula.py
8
9
10

real  0m0.552s
user  0m0.548s
sys   0m0.000s

A: Для начала нужно сделать как-то так
count = 0
for a in range(0,1000):
    f=True
    for x in range(1,100):
        for y in range(1,100):
            if ((not (x < a) or (x ** 2 < 100)) and (not(y ** 2 <= 64) or (y <= a))) == False:
                if f == True:
                    count += 1
                    print(a)
                    f=False
print(count)

Но у тебя какие-то странные значения, почему ты выбрал такой диапазон, для А - 1000 и по 100 для x и y? Есть какое-то дополнительное условие?


text:
Q: KineticJS mouse position wrong after layer rotated My demo is here http://jsfiddle.net/akuma/7NmXw/1/

*

*First, draw something in the blue box.

*Then, click the rotate button once.

*After the box has been rotated, draw something again.

*Finally the draw poisitoin was wrong.

How can I fix that, thanks!
Code:
var stage = new Kinetic.Stage({
    container: 'container',
    width: 500,
    height: 500
});

var layer = new Kinetic.Layer({
    width: 400,
    height: 400
});

var rect = new Kinetic.Rect({
    x: 0,
    y: 0,
    width: 400,
    height: 300,
    fill: '#00D2FF',
    stroke: 'black',
    strokeWidth: 5
});

layer.add(rect);
stage.add(layer);

$(document).on('click', '#rotateBtn', function () {
    var w = layer.getWidth(),
        h = layer.getHeight();
    layer.setOffset(w / 2, h / 2);
    layer.setPosition(w / 2, h / 2);
    layer.rotateDeg(90);
    layer.draw();
});

var points = [],
    drawing = false;

stage.on('mousedown', function () {
    drawing = true;

    var pos = stage.getMousePosition();
    points.push([pos.x, pos.y]);

    var line = new Kinetic.Line({
        id: 'line',
        points: [
            [pos.x, pos.y],
            [pos.x + 1, pos.y + 1]
        ],
        stroke: 'white',
        strokeWidth: 5,
        lineCap: 'round',
        lineJoin: 'round'
    });

    layer.add(line);
    layer.drawScene();
});

stage.on('mousemove', function () {
    if (!drawing) {
        return;
    }

    // Remove previous line
    layer.get('#line').remove();

    var pos = stage.getMousePosition();
    points.push([pos.x, pos.y]);

    // Redraw line
    var line = new Kinetic.Line({
        id: 'line',
        points: points,
        stroke: 'white',
        strokeWidth: 5,
        lineCap: 'round',
        lineJoin: 'round'
    });
    layer.add(line);
    layer.drawScene();
});

stage.on('mouseup', function () {
    drawing = false;
    points = [];
});

A: Even after rotating, Kinetic will still give you un-rotated mouse coordinates
That's because you are asking for stage.getMousePosition and the stage is not rotated.
There is no method like layer.getMousePosition, so you'll have to create one.

If you rotate your layer 90-degrees, you must also rotate stage's mouse coordinates by 90-degrees.
Here's how you rotate the stage mouse position to match the layer rotation:
    // get the unrotated mouse position from Kinetic

    var pos=stage.getMousePosition();

    // rotate that point to match the layer rotation

    var x1 = rotationX
              + (pos.x-rotationX)*rotationCos
              + (pos.y-rotationY)*rotationSin;

    var y1 = rotationY
              + (pos.y-rotationY)*rotationCos
              - (pos.x-rotationX)*rotationSin;

Since you will be doing this math with each mousemove, you should pre-calculate the rotation values to maximize performance:
    // reset the current rotation information

    function setRotation(degrees){
        var radians=layer.getRotation();
        rotationX=layer.getOffsetX();
        rotationY=layer.getOffsetY();
        rotationCos=Math.cos(radians);
        rotationSin=Math.sin(radians);
    }

Also, a bit off-topic to your question, but...
Instead of removing / recreating a new line on every mousemove, you can "recycle" your existing line:
  // set the points property of the line to your updated points array

  line.setPoints(points);

Here's code and a Fiddle:  http://jsfiddle.net/m1erickson/cQATv/
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Prototype</title>

    <button id="rotateBtn">rotate</button>


text:
Q: How to test if a string starts with a prefix from a list of prefixes in a shell I have a requirement in a shell script.  I get this location information from a text file; it is always valid.
/opt/sasuapps/senny/publish/gbl/SANDHYA/drop1

I need to check if the directory is empty or not which I have done. If the directory is not empty, I need to delete the files and directory under that location.
As a part of security check, I would like to check if the drop location got from the file  (/opt/sasuapps/senny/publish/gbl/SANDHYA/drop1) starts with any of the below.
/mnt/senny_publish/gbl
/mnt/senny/publish/gbl
/opt/sasuapps/senny/publish/gbl

If yes then only go ahead and delete; else don't do anything.
How can I compare the location given with those fixed strings?

A: This will work in bash and any other Posix-style shell, i.e., it's OK for systems where /bin/sh is not bash.
check () {
  [ "x$1" = x ] && return 1
  for pf in /mnt/senny_publish/gbl              \
            /mnt/senny/publish/gbl              \
            /opt/sasuapps/senny/publish/gbl; do
      suf="${1#$pf}"
      [ x"$pf$suf" = x"$1" ] && return 0
  done
  return 1
}

testcheck () {
  echo -n "$1" :
  if check "$1"; then
      echo OK
  else
      echo BAD
  fi
}

testcheck /how/now
testcheck /not/this
testcheck /mnt/senny_publish/gbl
testcheck /mnt/senny/publish/gbl
testcheck /opt/sasuapps/senny/publish/gbl
testcheck /mnt/senny_publish/gbl/a/b
testcheck /mnt/senny/publish/gbl/a/b
testcheck /opt/sasuapps/senny/publish/gbl/a/b

So...
/how/now :BAD
/not/this :BAD
/mnt/senny_publish/gbl :OK
/mnt/senny/publish/gbl :OK
/opt/sasuapps/senny/publish/gbl :OK
/mnt/senny_publish/gbl/a/b :OK
/mnt/senny/publish/gbl/a/b :OK
/opt/sasuapps/senny/publish/gbl/a/b :OK

By avoiding grep and other external programs, we keep execution entirely in the shell, avoiding fork's and exec's, and which may also give additional protection against XSS attacks. Still, it would be a good idea to filter metachars early.

A: Assuming you are using bash for your shell script:
if [ -n "$(echo $LOCATION|grep -lE '/mnt/senny_publish/gbl|/mnt/senny/publish/gbl|/opt/sasuapps/senny/publish/gbl')" ]
then
    # Contains one of these paths
else
    # Does not contain one of these paths
fi

If you have a longer list of paths to look through, you could dump them to a tempfile, one per line, and use grep -lEf tempFileWithPaths.txt

A: Using case is a lot cleaner:
case $d in
/mnt/foo/gbl/*|/mnt/bar/publish/gbl/*|/opt/sasu/bar/publish/gbl/*)
    rm -fr "$d"
esac

..for everyday use. This is POSIX-compliant and quick.
If you want to make it into a function, you could do:
# prefixed_by "$locn" "$safe_pfx" '/dir/list'
prefixed_by() {
    [ -n "$1" ] || return
    local i f=$1; shift
    for i; do
        i=${i%/}
        case $f in
        "$i/"*) return 0
        esac
    done
    return 1
}

So, if you know the list never has spaces or wildcard characters in it (ie: it's set directly in your script with a string literal) you could do:
readonly safe_list='/mnt/foo/gbl /mnt/bar/publish/gbl /opt/sasu/bar/publish/gbl'

..in initialisation, and then later:
prefixed_by "$d" $safe_list && rm -fr "$d"

I've used local in the function, which isn't specified in POSIX, though most modern shells have it: you can change that to fit your circumstance, as the rest is all POSIX-compliant.
In BASH, you don't have to use case in the for loop: you can just use [[ which pattern-matches, ie:
[[ $f = "$i"/* ]] && return

It also doesn't word-split nor perform any filename expansion. Quoting the "$i" is needed, however to ensure any wildcard characters like * or ? are not used as wildcards.

A: use sed command


text:
Q: HTML5 - Anchor separate from base link I've been practising some HTML5 as of recent, and come to a halt. I've added an anchor to a part of the code, but when I try to link to it, the link goes straight to the base link. Is there anyway to get past this?
This is the snippet of the code:

<base href="http://en.wikipedia.org/wiki/" target="_blank" />

(...)
Link to anchor: Link!

(...)

Welcome!

Thanks!

A: Try:
Welcome!

The name attribute is for form elements in HTML5.

A:
<base href="http://en.wikipedia.org/" target="_blank" />

(...)
Link to anchor: Link!

(...)

Welcome!


text:
Q: PDF takes 22 seconds to download but at second execution 5 seconds (JAVA) - Why My API REST looks like this (i am using JAVA, APACHE CAMEL):
http://server3343.erp.local:5464/api/rest/invoices/receipts/pdf?companyNumber=45&accountNumber=000333&documentType=FC&transactionNumber=BG534530SF

These parameters are completed to look for a file, in the given example i set:
companyNumber: 45
accountNumber: 000333
documentType: FC
transactionNumber: BG534530SF

The PDF file has this name:
45000333FCBG534530SF

The filename is specified and then, my code try to find it in the FTP DIRECTORY

The problem is that everytime time it is executed it TAKES more than 20 seconds to get the file:

But the second time it is executed it takes 5 seconds or less:

My code:
  package ar.com.newsan.esb.route;

    import ar.com.company.camel.common.route.RestRouteBuilder;
    import ar.com.company.esb.Constants;
    import org.apache.camel.LoggingLevel;
    import org.apache.camel.model.rest.RestParamType;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import javax.ws.rs.core.MediaType;

    @Component
    public class GetReceiptsPDFRoute extends RestRouteBuilder {

        @Value("${timeout.FTP}")
        private Long timeoutFTP;

        @Override
        public void configure() {
            super.configure();
            rest(restApiPath)
                .get("/receipts/pdf?companyNumber={companyNumber}&accountNumber={accountNumber}&documentType={documentType}&transactionNumber={transactionNumber}").id("receipts PDF")
                .param().name("companyNumber").type(RestParamType.query).dataType("String").required(true).endParam()
                .param().name("accountNumber").type(RestParamType.query).dataType("String").required(true).endParam()
                .param().name("documentType").type(RestParamType.query).dataType("String").required(true).endParam()
                .param().name("transactionNumber").type(RestParamType.query).dataType("String").required(true).endParam()
                .consumes(MediaType.APPLICATION_JSON)
                .produces("application/pdf")
                .to("direct:receiptsPDF");

            /**
             *  set name and location to look for the PDF in FTP DIRECTORY
             */
            from("direct:receiptsPDF").routeId("ReceiptsPDF")
                .setProperty("currentOperation", constant("ReceiptsPDF"))
                .log(LoggingLevel.INFO,"ReceiptsPDF", "[Inicia ${property.currentOperation}]")
                .log(LoggingLevel.INFO, "company Number: ${header.companyNumber}")
                .log(LoggingLevel.INFO, "account Number: ${header.accountNumber}")
                .log(LoggingLevel.INFO, "document Type: ${header.documentType}")
                .log(LoggingLevel.INFO, "transaction Number: ${header.transactionNumber}")
                .doTry()
                    .choice()
                        .when(header("documentType").isEqualTo(Constants.FILE))
                            .log(LoggingLevel.INFO, "ReceiptsPDF","[${property.currentOperation}] Find FILE")
                            .setHeader("TARGET_DIR", simple("{{source.ebs.FILEs}}"))
                    .endChoice()
                    .otherwise()
                        .log(LoggingLevel.INFO, "ReceiptsPDF","[${property.currentOperation}] Find FILES")
                        .setHeader("TARGET_DIR", simple("{{source.ebs.FILES}}"))
                    .end()
                    .setProperty("fileName", simple("${header.companyNumber}${header.accountNumber}${header.documentType}${header.transactionNumber}.pdf"))
                    .to("direct:findPdfInFTP")
                    .log(LoggingLevel.INFO,"ReceiptsPDF", "[Ending ${property.currentOperation}]")
                .endDoTry()
                .doCatch(Exception.class)
                    .log(LoggingLevel.ERROR, "ReceiptsPDF", "[ERROR: ${exception.message}")
            .end();

            /**
             *  search in FTP DIRECTORY
             */
            from("direct:findPdfInFTP").routeId("find file in ftp")
                .doTry()
                    .to("direct:searchInFTP")
                    .choice()
                        .when(simple("${body} == null"))
                            .log(LoggingLevel.INFO, "findPdfInFTP", "Search in processed sub-direcotries")
                            .setHeader("TARGET_DIR", simple("${header.TARGET_DIR}/Procesados"))
                            .to("direct:searchInFTP")
                    .otherwise()
                    .log(LoggingLevel.INFO,"findPdfInFTP","FILE OBTAINED: ${headers.CamelFileName}")
                .endDoTry()
                .doCatch(Exception.class)
                    .log(LoggingLevel.ERROR, "findPdfInFTP", "[ERROR: ${exception.message}")
                .end();

            from("direct:searchInFTP").routeId("searchInFTP")
                .doTry()
                    .log(LoggingLevel.INFO, "searchInFTP","Search: {{ebs.sftp}}/${header.TARGET_DIR}/${property.fileName}")
                    .pollEnrich().simple("{{ebs.sftp}}/${header.TARGET_DIR}?password={{ebs.sftp.password}}&fileName=${property.fileName}&disconnect=true&useList=false&ignoreFileNotFoundOrPermissionError=true&useUserKnownHostsFile=false").timeout(timeoutFTP)
                .endDoTry()
                .doCatch(Exception.class)
                    .log(LoggingLevel.ERROR, "searchInFTP", "[ERROR: ${exception.message}")
                .end();
        }
    }

What's wrong with my code? I need to find it in 5 seconds, at once.


text:
Q: Google map: How to rotate `groundoverlay` need trick I'm making map project for use like adding shapes and location on map and save it.
but i'm getting problem with groundoverlay.
i know there is no property exist for rotation in google map document.
but i need a way/trick to rotate groundoverlay image, by any other way.
here code
var srcImage = "http://demo/image/uploads/demo.jpg";
var bounds = {
    north: 44.599,
    south: 44.490,
    east: -78.443,
    west: -78.649
}
var overlay = new google.maps.GroundOverlay(srcImage ,bounds);
overlay.setMap(map);

i am using slider for rotate overlay.
$("#overlayslider").slider().on('slide',function(e){
     var angle = e.newVal;
     // i want rotate overlay by angle/degree as per slider
})

I have tried with projection but no success.
Any posible way will be appreciate.
Any help will be useful, thank you.

A: You can achieve this by using a custom overlay: https://developers.google.com/maps/documentation/javascript/examples/overlay-simple.
Add an event listener to the overlay slider in USGSOverlay.prototype.onAdd and then set the rotation of the div on input.
document.getElementById('overlayslider').addEventListener('input', function() {
    div.style.transform = 'rotate(' + this.value + 'deg)';
});

And here is the modified custom overlay example: https://jsfiddle.net/b0tLd46u/4/. You can set the rotation of the overlay by the range slider above the map.

A: Here is my solution mostly inspirered from This Answer
rotated-overlay.ts
export class CustomOverlay extends google.maps.OverlayView {
  private div;

  constructor(
    private bounds: google.maps.LatLngBounds,
    private image: string,
    private rotation: number
  ) {
    super();

    // Define a property to hold the image's div. We'll
    // actually create this div upon receipt of the onAdd()
    // method so we'll leave it null for now.
    this.div = null;
  }

  /**
   * onAdd is called when the map's panes are ready and the overlay has been
   * added to the map.
   */
  onAdd() {
    const div = document.createElement('div');
    div.style.borderStyle = 'none';
    div.style.borderWidth = '0px';
    div.style.position = 'absolute';

    // Create the img element and attach it to the div.
    const img = document.createElement('img');
    img.src = this.image;
    img.style.width = '100%';
    img.style.height = '100%';
    img.style.position = 'absolute';
    div.appendChild(img);

    this.div = div;

    // Add the element to the "overlayLayer" pane.
    const panes = this.getPanes();
    panes.overlayLayer.appendChild(div);
  };

  draw() {

    // We use the south-west and north-east
    // coordinates of the overlay to peg it to the correct position and size.
    // To do this, we need to retrieve the projection from the overlay.
    const overlayProjection = this.getProjection();

    // Retrieve the south-west and north-east coordinates of this overlay
    // in LatLngs and convert them to pixel coordinates.
    // We'll use these coordinates to resize the div.
    const sw = overlayProjection.fromLatLngToDivPixel(this.bounds.getSouthWest());
    const ne = overlayProjection.fromLatLngToDivPixel(this.bounds.getNorthEast());

    // Resize the image's div to fit the indicated dimensions.
    const div = this.div;
    div.style.left = sw.x + 'px';
    div.style.top = ne.y + 'px';
    div.style.width = (ne.x - sw.x) + 'px';
    div.style.height = (sw.y - ne.y) + 'px';
    div.style.transform = 'rotate(' + this.rotation + 'deg)';
  };

  // The onRemove() method will be called automatically from the API if
  // we ever set the overlay's map property to 'null'.
  onRemove() {
    this.div.parentNode.removeChild(this.div);
    this.div = null;
  };
};

map-component.ts
public addOverlay(imageUrl: string, rotation: number, bounds: google.maps.LatLngBounds, map: google.maps.Map){
  let overlay = new CustomOverlay(
    bounds,
    imageUrl,
    rotation,

  );
  overlay.setMap(map);
}


text:
Q: Regexp breaks Angular lazy load module from loading (Safari only) I have the following line in an Angular lazy loaded module (originally not called 'evilRegex').
It doesn't get executed, only defined - and the RegExp and lazy module work just fine as intended in Chrome.
  const evilRegex = new RegExp(/(?<=<)([a-z0-9]+)(?=[ >])/g);

I am getting a ChunkLoadError is raised when the lazy module is loaded, but the URL returned in the error is valid and accessible if loaded directly.
I know that no code is executing because I see this alert box.
 loadChildren: () => import(/* webpackChunkName: "pages_home" */ './rr2/page-designer/pages/pages.module')
                     .then(m => { return m.PagesModule; } ).catch(e => alert('***' + e))

In addition, putting try / catch around it does nothing so the error must be some kind of module load error. It only happens in Safari and only with this exact RegExp - so it's also not a caching issue.
I'm seeing this only on my iPhone so I can't view the console for any errors.
Does Safari not support negative lookbehind Regex? Is it because somehow <=< is tripping over the module parser?
More concerning is perhaps that since the actual error doesn't propagate all I would see in my log files is 'ChunkLoadError' which is indistinguishable from a connection issue.
Note: I am using Safari 14 Beta, but see the same in 13.5. If someone with a Mac could add this to a lazy module - just the definition - I'm hoping it would show some details in the console.


text:
Q: Subtracting numeric contents of one text field from another and displaying the results in real time? I am using jQuery keypad to build a point of sale interface
http://keith-wood.name/keypadBasics.html
I have two text fields namely
PREVIOUS RENT and RENT PAID
as the user enters data I would like the page to run the following formula in real-time
PREVIOUS RENT - RENT PAID
I would like it to display the results below the text fields in real-time (without refreshing the page or submitting the code)
How would this be done?

A: Assuming you want to update to happen when the 'rent paid' field loses focus:
$('#rent-paid').blur(function({
      var diff =  $('#previous-rent').attr('value') - $(this).attr('value');
      $('#total').text(diff);
 }));

A: Binding to change or blur should work.
<html>
<body>

  <script src='jquery.js'></script>
  <script>

    $(document).ready(function(){

      $('#previousRent').change(function(){
        calcResult();
      });

      $('#rentPaid').change(function(){
        calcResult();
      });

    });

    function calcResult() {
      $('#result').val( parseFloat($('#previousRent').val() - $('#rentPaid').val()) );
    }

  </script>

  <input type="text" id="previousRent">
  <input type="text" id="rentPaid">
  <input type="text" id="result">

</body>
</html>


text:
Q: Fejer's theorem and convergence of Fourier series in measure Fejer's theorem says that for any continuous function $f \colon S^1 \to \mathbb C$ with Fourier coefficients $a=(a_n)_{n \in \mathbb Z}$ the sequence
$$\sigma_n(a) := \frac1n \sum_{k=1}^n \sum_{l=-k}^k a_l \exp(2\pi i \cdot l\phi)$$
convergences uniformly to $f$. Moreover, by the Riemann-Lebesgue Lemma, the sequence $a=(a_n)_{n \in \mathbb Z}$ is in $c_0(\mathbb Z)$.

Question: Let $a=(a_n)_{n \in \mathbb Z}$ be in $c_0(\mathbb Z)$.
  Does $\sigma_n(a)$ converge in measure to some measurable function on $S^1$?

More generally, is there any summing procedure (or in fact any assignment whatsoever), which leads to a linear map $\Phi \colon c_0(\mathbb Z) \to M(S^1)$, which extends Fourier summation on finitely supported functions (and preferably also Fejer summation for Fourier series of continuous functions). Here, $M(S^1)$ denotes the space of measurable functions on $S^1$ (up to measure zero) with the usual measure topology given by the metric
$$d(f,g) := \inf\lbrace\varepsilon \mid \mu(\lbrace x \mid |f(x)-g(x)|\geq \varepsilon \rbrace \leq \varepsilon \rbrace.$$

A: There is no continuous linear operator from $c_0$ to $M(S^1)$  that maps the unit vector basis to the characters.  In fact, any continuous linear operator from $c_0$ to $M(S^1)$ maps the unit vector basis to a sequence which converges to zero at a good rate.  To see this, note that by Maurey-Nikishin, the operator factors through $L_p$ for all $0<p<1$, and these spaces have cotype 2.
Does this answer your question? If not, I don't see a good formulation for your question. If there is anything like a summation method, the Banach-Steinhaus theorem would imply that the operator is continuous.


text:
Q: Trying to connect to an USB Zebra printer from a Windows Mobile emulator via the Zebra SDK in C# I have a Zebra GK420t printer plugged in via USB to a PC.
The PC is running MS Visual Studio.
I have created a new Project -> Other Languages -> Visual C# -> Smart Device -> Windows Mobile 6 Professional project.
I have created a class:
using System;
using System.Collections.Generic;
using System.Text;
using ZSDK_API.Comm;
using ZSDK_API.ApiException;

namespace Zebra2
{
    class CTest
    {
        static void Main(string[] args)
        {
            try
            {
                // Instantiate connection for ZPL USB port with a given port name.
                ZebraPrinterConnection thePrinterConn = new UsbPrinterConnection("USB001:");
                // "LPT" is the default prefix for most Windows CE/Mobile USB ports

                // Open the connection - physical connection is established here.
                thePrinterConn.Open();

                // This example prints "This is a ZPL test." near the top of the label.
                String zplData = "^XA^FO20,20^A0N,25,25^FDThis is a ZPL test.^FS^XZ";

                // Send the data to printer as a byte array.
                thePrinterConn.Write(Encoding.Default.GetBytes(zplData));

                // Close the connection to release resources.
                thePrinterConn.Close();
            }
            catch (ZebraPrinterConnectionException e)
            {
                // Handle communications error here.
                Console.Write(e.StackTrace);
            }
        }
    }
}

In Visual, I added a Reference for the ZSDK_API.dll successfully.
When I try to add a reference for the ZebraUsb.dll, I get the error message:
A reference to 'ZebraUsb.dll' couldn't be added.

If I build the code without the reference for this dll, the build is successful.
But at runtime, an exception is raised on the line where the Open() method is invoked.
The error message is:
An unhandled exception of type ZSDK_API.ApiException.ZebraGeneralException' occurred in ZSDK_API.dll.
Additional information: Can't find PInvoke DLL 'ZebraUsb.dll'.

Second problem:
I'm not sure what argument I should give to the UsbPrinterConnection constructor.
On the PC, the port for the printer is USB001.
I'm not sure how it's being seen from the emulator.
The printer can also be seen as a share via \\PC\printer.
Can you help me?
Best regards.

A: For all USB printers on Windows PC you normally have to add the printers USB driver first. This driver can be a USB Serial one or something special. Such drivers do not exist for Windows Mobile.
The Zebra GK420t is a desktop barcode label printer and not designed to be used from Windows Mobile.
You may install the printer on your Windows PC and share it over the network, either using Windows Printer Sharing or TCP/IP printer services (LPR). Then you might write an application that sends print commands over the network to this shared connection.
Zebra also offers a range of portable printers and a Windows Mobile SDK. These may match your needs more than the GK420t.


text:
Q: Show/Hide Dropbox using Radio Button and JQuery This is my HTML:
<input type="radio" value="rural" id="rural" name="landtype" checked>Rural
<input type="radio" value="urban" id="urban" name="landtype" checked>Urban

<select id="budget1" class="dbox1">
                    <option value="9000">8000php-10000php</option>
                    <option value="13000">12000php-14000php</option>
                    <option value="17000">16000php-18000php</option>
                </select>

<select id="budget2" class="dbox2">
                    <option value="10000">9000php-11000php</option>
                    <option value="14000">12000php-15000php</option>
                    <option value="18000">17000php-19000php</option>
                </select>

This is my javascript code:
<script type="text/javascript">

    $(document).ready(function(){
                      $('input[type="radio"]').click(function(){
                           if($(this).attr("value")=="rural"){

                                document.getElementById("budget2").hide();
                                document.getElementById("budget1").show();

                           }
                           if($(this).attr("value")=="urban"){
                                document.getElementById("budget1").hide();
                                document.getElementById("budget2").show();
                           }
    });
    });

</script>

What I would want is that if i click my "Rural" Radio Button, "dbox2" will hide then "dbox1" will show.
And if i click my "Urban" Radio Button, "dbox1" will hide then "dbox2" will show.
What I get so far is an "Error" from the line "document.getElementById("budget1").hide();" that says "Uncaught TypeError: undefined is not a function"
Any solution?

A: If you are using jQuery use it and change that lines:
document.getElementById("budget2").hide();
document.getElementById("budget1").show();

to:
$("#budget2").hide();
$("#budget1").show();

EDIT: Sorry, I forgot to add the ID selector.

A: hide() and show() are jQuery functions thats why you where getting those errors. use $() to get those elements and then call hide and show.

A: $("#budget2").hide();

$("#budget1").show();


text:
Q: Extract information from function definition returned by DefineDLLFunction I have an application using DefineDLLFunction whose output is:

Function[Null,  If[NETLinkDLLPrivatecheckArgCount["DRV_AOVoltageOut", {##1},2],
      WolframNETLinkDynamicDLLNamespaceDLLWrapper2DRVUAOVoltageOut[##1], $Failed], {HoldAll}]

How to extract the information "DynamicDLLNamespaceDLLWrapper2" from the output above?

A: This question was heavily edited to remove the (badly formatted) long preamble that explained the motivation. What the questioner is trying to do is call a DLL function with an argument whose type is dynamically defined in the call to DefineDLLFunction. To get the full name of this type programmatically, you need to extract the name of the dynamically-defined namespace from the function returned by DefineDLLFunction. This namespace is given by the context of the DRVUAOVoltageOut symbol, which is "Wolfram`NETLink`DynamicDLLNamespace`DLLWrapper2`" in the example (this got messed up a bit above because of bad formatting). The questioner wants to extract this context and use it to create the string name of the .NET type he wants to create to pass as an argument, which in this case will be "Wolfram.NETLink.DynamicDLLNamespace.DLLWrapper2+PT_AOVoltageOut".
Here is one way to do it. The original DefineDLLFunction call looked like this:
f = DefineDLLFunction["
       public class PT_AOVoltageOut
           {
              public ushort chan;
              public float OutputValue;
           }
       [DllImport(\"Adsapi32.dll\",CallingConvention = CallingConvention.StdCall,
                 CharSet = CharSet.Auto, SetLastError = true)]
       public static extern short DRV_AOVoltageOut( [In, Out] Int32 DriverHandle, PT_AOVoltageOut IntPtr);"
]

This returns the somewhat cryptic Function shown in the original question. To create the type name:
ctxt = Context[Evaluate @ First @ Cases[f, If[_, sym_[_], _] :> sym]];
typeName = StringDrop[StringReplace[ctxt, "`" -> "."], -1] <> "+PT_AOVoltageOut";

Then, to create an object:
voltageOut = NETNew[typeName]


text:
Q: Can there be a badge encouraging answering a certain ratio of questions? Can we encourage answering questions?
When i see a profile like this one I start to think.
Should we be encouraging answering questions to some ratio?
Maybe a badge if you have 2:3 answers to questions (or 1:3 even) then you can get a badge.
Full badge requirements:

*

*Answer at least 40 questions.

*Ask at least 60 questions.

*If the ratio of answers to answers is 1:3 then you get the badge (to be named soon)

A: I don't ask questions, at least not on SO and programmers. I have about 19K rep between the two sites, from a little over 500 answers. Zero questions. I need people to ask questions that I can answer. If they start answering after a while, they are sure to benefit - you can learn a TON by answering. To that end there are already badges that should get you started answering. I don't see a behaviour we want to reward in the "both asking and answering" zone - people may do it, but it's possible to be a valued user of the site without ever doing so.

A: This general topic, although not a badge specifically, has been discussed extensively in the past. We want to encourage good posts regardless of whether they're questions or answers.
Newbies will naturally have lots of questions while lacking the experience needed to provide good answers. Experts will know the answers to many questions while having few questions of their own. The badge you're proposing would be sort of a "in the middle of my career" badge, and I can't think of a positive Stack Exchange behavior that that would encourage.

A: The system already encourages answers more than questions:

*

*Answers get 10 rep per up vote, while questions only get 5.

*There are more badges related to good answers than good questions, especially when you include tag badges.

*There is less "risk" in answering: a poor question is much more likely to gather down votes, close votes or being deleted. Poor answers are more likely ignored unless they're really bad.

Answers also tend to get more up votes than questions.


text: Q: Shopify error code with reCAPTCHA – "Parameter Missing or Invalid: Required parameter missing or invalid: customer" Keep getting this error code when attempting to register account on Shopify. Go to register, enter details and PW, then after clicking 'I'm not a robot' clicking appropriate images and submit, the error code appears.enter image description here


text:
Q: Is it possible to anchor a CGPattern-image background color to the center of a CALayer? I've set up a layer as follows:
CALayer *layer = [CALayer layer];
layer = /* create a CGColorRef with a pattern image */;

This layer is simply displayed in my window. My draw/release functions for the pattern are as follows:
void drawPattern(void *info, CGContextRef c) {
    CGContextDrawImage(c, CGRectMake(0, 0, CGImageGetWidth(info), CGImageGetHeight(info)), info);
}
void releaseInfo(void *info) {
    CGImageRelease((CGImageRef)info);
}

By default, the pattern is anchored at the lower-left corner of the window, so when I resize the window, that point is fixed.
I figured out that I can anchor it at the upper-left corner with two steps:

*

*set layer.geometryFlipped = YES;

*use CGAffineTransformMakeScale(1, -1) as an argument to CGPatternCreate instead of CGAffineTransformIdentity.

But how can I anchor it at the center? (Changing the layer's anchorPoint doesn't seem to do anything.)

A: I think you'll have to pass the layer, not the image, as the info parameter, and have your drawing function retrieve the layer's frame and use that to compute a translation to apply.


text:
Q: Possible bug in `toc` function in Matlab R2015b Usually calling a Matlab function with an empty comma-separated list is the same as calling it without arguments. For example,
in={}; spy(in{:});

is the same as
spy %// call without inputs

However, I'm getting strange behviour for the 1-output version of toc: this works as expected
tic; t=toc

whereas this crashes (closes Matlab) in R2015b, Windows 7 64 bits:
tic; in={}; t=toc(in{:})

It works properly in Matlab R2014b, Windows 7 64 bits.
Can someone reproduce this behaviour in R2015b? Any explanation? Possible bug?

A: Just to close this question:
From the comments above, this problem happens in Matlab R2015b in various operating systems. It doesn't happen in older Matlab versions.
I reported a bug to Mathworks. They told me be the developers are aware of this issue and it will be fixed for R2016b.
EDIT (October 3, 2016): I confirm that the bug has been corrected in R2016b.


text:
Q: How to extract Excel file header names into array list using POI? I have a requirement, where dynamic data comes from excel, and I need to extract header(column) names(1st row) into array list.
file =new FileInputStream(new File("excel file"));
HSSFWorkbook workbook = new XSSFWorkbook(file);
Any input greatly appreciated, I am very new to java programming.
Thanks

A: Do it as follows:
// Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook(file);

// Get the first sheet from the workbook
XSSFSheet firstSheet = workbook.getSheetAt(0);

// Get the first row from the sheet
Row row = firstSheet.getRow(0);

// Create a List to store the header data
ArrayList<String> headerData = new ArrayList<>();

// Iterate cells of the row and add data to the List
for (Cell cell : row) {
    switch (cell.getCellType()) {
    case NUMERIC:
        if (HSSFDateUtil.isCellDateFormatted(cell)) {
            DataFormatter dataFormatter = new DataFormatter();
            headerData.add(dataFormatter.formatCellValue(cell));
        } else {
            headerData.add(String.valueOf(cell.getNumericCellValue()));
        }
        break;
    case STRING:
        headerData.add(cell.getStringCellValue());
        break;
    case BOOLEAN:
        headerData.add(String.valueOf(cell.getBooleanCellValue()));
        break;
    default:
        headerData.add("");
        break;
    }
}

// Print the List
System.out.println(headerData);

Feel free to comment in case of any doubt/issue.


text:
Q: What is the best way of embedding a java applet into my webpage? I've been looking into putting a little Java application in my web page, but the more research I do, the more confused I become about how I should do it. Sun suggests many ways of doing it, but it looks suspiciously like it's from the Netscape era.
So, should I use <applet>, as suggested by eclipse, <embed>, or <object>?
And how should I use the correct tag?

A: Since Java 6 Update 10 they've released a Java Deployment Kit:

The Java Deployment Toolkit makes
  deploying Java applets or Java Web
  Start programs a snap. The Deployment
  Toolkit JavaScript file provides:
* Accurate detection of installed JREs
* Seamless JRE installation
* Complete applet launching (JRE detection and, if necessary, upgrading)
  in a single line of code
* Complete Web Start program launching in a single line of code

The following HTML code is all it
  takes to ensure that Java 1.6 is
  installed and then a Java applet is
  launched:

<script src="http://java.com/js/deployJava.js"></script>

<script>
  deployJava.runApplet({codebase:"http://www.example.com/applets/",
     archive:"ExampleApplet.jar", code:"Main.class",
     width:"320", Height:"400"}, null, "1.6");
</script>

A: Well if you want to strictly follow standards then a quick look here at the W3C standards says that applet is depreciated and you should use object instead.


text:
Q: Splitting Power Tracks/Planes into Different Layers I'm just wondering that, in terms of EMC/EMI, what the effect of splitting a power track/plane into different layers can be.
Assume a power track/plane/pour area (with enough thickness and/or total area for, say, 5A DC) is split into two tracks/planes/pour areas (equally or not) and each track/plane/pour area is drawn on different (i.e. bottom and top) layers then connected with enough amount of vias and/or through-hole components' terminal pads (filtering caps, parallel diodes etc).
Doing so is good or bad for EMI/EMC?
Sorry for my English.

A: This is certainly a good idea for a ground plane (also called a power plane). With sufficient stitching vias, two parallel ground planes results in lower volt drops at high frequencies and imporved performance especially with sensitive analogue circuits in the presence of digital circuits. Having said that, when you have mixed signals it will probably be better to keep a digital ground plane separated from the analogue ground plane to avoid circulating digital currents in the analogue ground plane. Stitching the digital and analogue planes at just one main area is also something to be recommended.
For non-ground power planes the benefits are less obvious. My general philosophy is that I make non-ground power planes sufficient for the current that are passing and use the "extra space" for more true ground plane. Using tracks (rather than planes) to feed individual chips can be regarded as a good idea because the track's self inductance (along with the chip's decoupler) make a nice power supply filter and you end up with a fair amount of filtering when this is extended to a multi-chip PCB design.
On the other hand, for low voltage MCU's (circa 1 V logic levels), it probably makes sense to keep a true Vcc power plane and having two (with stitching vias) probably is a good idea.
So many of these decisions are based on the target design and therefore generalizations are fraught with subtle dangers.

Doing so is good or bad for EMI/EMC?

Well, before you consider EMI or EMC, the PCB has to be fit for purpose and perform to the required expectations and that, is the motive to my previous paragraphs.When it comes to EMI or EMC it's ground all the way rather than a non-ground power plane.


text:
Q: Finding index of target using recursive binary search in C I'm only allowed to use the given parameters. I can't wrap my head around the thought of finding the index of the target. Any ideas?
#include <stdio.h>

int RecBinarySearch(int arr[], int len, int target) {

    if (len <= 0)
        return 0;

    int mid = len/2;

    if (target == arr[mid]){
        return 1;
    }
    if (target < arr[mid]){
        int i=0;
        return RecBinarySearch(arr, mid, target);
    }

    else {
        return RecBinarySearch(arr+mid+1, len-mid-1, target);
    }
}

int main(void){
    int arr[6]={1,2,3,4,5,6};
    int len=sizeof(arr)/sizeof(arr[0]);
    int target = 5;
    RecBinarySearch(arr,len,target);
}

A: 1st : you don't really need recursivity in this goal. You might more efficiently replace it with a loop, using left and right marker (recursivity is quite expensive for various reasons).
2nd : Instead of returning 0 or 1, which you don't use, you should return mid or -1 if not found, and since you shifted your array in the recursive call (passing array+mid+1), you should add the shift value to the return value, and then you get the position in the return value in main.

A: Ideone link
#include <stdio.h>
int RecBinarySearch(int arr[], int len, int target) {
    if(len <= 0) return -1;
    int mid = len / 2;
    if(arr[mid] == target) return mid;
    if(arr[mid] < target) {
        int rightIndex = RecBinarySearch(arr+mid+1, len-mid-1, target);
        return rightIndex == -1 ? -1 : mid+rightIndex+1;
    } else {
        int leftIndex = RecBinarySearch(arr, mid, target);
        return leftIndex == -1 ? -1 : leftIndex;
    }
}

int main(void){
    int arr[6]={1,2,3,4,5,6};
    int len=sizeof(arr)/sizeof(arr[0]);
    int target = 5;
    printf("%d", RecBinarySearch(arr,len,target));
}

A: Given that, I'm only allowed to use the given parameters, you can use following. See it working here:
int BinarySearch(int arr[], int len, int target) {
    int startI = 0, endI = len-1;

    while(startI<=endI)
    {
        int mid= (startI+endI)/2;
        if(arr[mid] == target)
            return mid;
        if(arr[mid] < target)
        {
            startI = mid +1;
        }
        else
        {
            endI = mid -1;
        }
    }
    return -1;
}


text:
Q: Replacing parts of a Matrix with lists I want to use lists to easily replace parts of a matrix. As an example, I want to replace the code
ReplacePart[{{1, 0}, {0, 1}}, {{1, 1} -> 13, {1, 2} -> 14}]

by something like
ReplacePart[{{1, 0}, {0, 1}}, {{1, 1}, {1, 2}} -> {13, 14}]

which doesn't work. For a general matrix m, I want to, given a list of indices of the type (x,y), li and a list of replacement values, lr, use something like
ReplacePart[m, li -> lr}]

Any idea how to do this?

A: ReplacePart[{{1, 0}, {0, 1}}, Thread[{{1, 1}, {1, 2}} -> {13, 14}]]

so
ReplacePart[m, Thread[li -> lr]]

in general.
But a CompiledFunction will probably do the job quicker because Thread[li -> lr] unpacks arrays. Let's see.
cReplacePart =
  Compile[{{A0, _Real, 2}, {pos, _Integer, 2}, {val, _Real, 1}},
   Block[{A = A0},
    If[
      1 <= Max[pos[[All, 1]]] <= Dimensions[A0][[1]] &&
      1 <= Max[pos[[All, 2]]] <= Dimensions[A0][[2]],
     Do[
      A[[Compile`GetElement[pos, i, 1],
        Compile`GetElement[pos, i, 2]]] = Compile`GetElement[val, i],
      {i, 1, Min[Length[pos], Length[val]]}
      ]
     ];
    A
    ],
   CompilationTarget -> "C",
   RuntimeOptions -> "Speed"
   ];

And indeed, it's 100 times as fast:
n = 1000;
m = 1000000;
A = RandomReal[{-1, 1}, {n, n}];
li = RandomInteger[{1, n}, {m, 2}];
lr = RandomReal[{-1, 1}, m];

B = ReplacePart[A, Thread[li -> lr]]; // AbsoluteTiming // First
cB = cReplacePart[A, li, lr]; // AbsoluteTiming // First
Max[Abs[B - cB]]

4.91402
0.047307
0.

One may also use SparseArray; this is only a tiny bit slower than the compiled approach:
spB = A SparseArray[li -> 0., Dimensions[A], 1.] +
     SparseArray[Reverse@li -> Reverse@lr, Dimensions[A], 0.]; //
  AbsoluteTiming // First
Max[Abs[B - spB]]

0.086657
0.

A: ReplacePart has a undocumented four variables form that permits this :
oldValuesList = {{1, 0}, {0, 1}}
newValuesList = {13, 14}
modifiedPositionsList = {{1, 1}, {1, 2}}
newValuesPositions = (* gives the origin of the new data *)
 List /@ Range[Length[newValuesList]] (* simply {{1},{2}} *)

ReplacePart[oldValuesList
 , newValuesList
 , modifiedPositionsList
 , newValuesPositions]

{{13, 14}, {0, 1}}

I have retrieved this information in Michael Trott' s book "Mathematica Guidebook for Programming" page 628.
According to this It was documented until Version 5.2.
EDIT
ReplacePart is known to be often not memory/speed optimal. It may be slow and memory consuming with large data sets.
Henrik Schumacher's comments below confirm this in this particular case.


text:
Q: Webview is not getting notifications in windows 8.1 We have an existing Windows store application which was developed by using WPF4.5. It has a sign-in mechanism which uses the webview(Windows.UI.Xaml.Controls.WebView). It loads a url into the webview and passes the windows credentials to that url. The url checks the user credentials if passes it will notify the webview with security token. If not it will notify the webview with error code or message.
This is working perfectly in Windows 8 store. However it is not working in windows 8.1 store. The webview is not getting any notifications from Html page that was loaded into it.
How to find root cause for this issue and resolve this issue?
Things that I have tried out:
I have searched in google and get the following articles which talks about webview in windows8.1.
http://msdn.microsoft.com/library/windows/apps/br227713
http://blogs.windows.com/windows/b/appbuilder/archive/2013/07/17/what-s-new-in-webview-in-windows-8-1.aspx
As per the articles specified I have added the application uris in the app manifest file. Still issue is not get resolved

A: Can you confirm that the URL you are loading in the WebView is an https:// website?
You said you declared the URL I am assuming you did this in the AppManifest Content URI section.
I work for Microsoft (MSFT)


text:
Q: CSS Search Box Alignment Issue in iPad/iPhone Only I am encountering issues with aligning a CSS Search Input Box like the Google style one found on this tutorial page.
I have edited the code to suit my design but for some reason I am unable to get this to align properly within the iPhone/iPad with the right element not aligning with the left element at the bottom.
The alignment issue can be seen here
The code is as follows:
HTML:

    <form name="" action="" type="">
    <input type="text" name="field" id="field" />

x

    </form>

CSS:
#search {float:left; margin:11px 0 0 156px;}
#field {float:left;width:200px; height:22px; line-height:22px; text-indent:0px; font-family:arial,sans-serif; font-size:12px; color:#999; background: #fff; background:url('search-icon.png') no-repeat left center; padding-left:25px; border:solid 1px #d9d9d9; border-right:none; -webkit-appearance:none; -webkit-border-radius:0px;}
#field:focus {outline:none;}
#delete {float:left; width:16px; height:24px; line-height:22px; padding:0 0 0 6px; font-family:"Lucida Sans", "Lucida Sans Unicode",sans-serif; font-size:14px; background:#FFFFFF; border:solid 1px #D9D9D9; border-left:none; -webkit-appearance:none; -webkit-border-radius:0px;}
#delete #x {color:#999999; cursor:pointer; display:none; }
#delete #x:hover {color:#666666;}

I noticed that changing the height:24px below:
#delete {float:left; width:16px; height:24px; line-height:22px; padding:0 0 0 6px; font-family:"Lucida Sans", "Lucida Sans Unicode",sans-serif; font-size:14px; background:#FFFFFF; border:solid 1px #D9D9D9; border-left:none; -webkit-appearance:none; -webkit-border-radius:0px;}

To height:27px; aligns correctly in Safari on the iPad/iPhone but then doesn't display correctly on IE/FF/Chrome.
Any help would be very much appreciated with this. Thanks

A: I tested locally it works, if you add the following on top of your page then the problem should be fixed.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

A: Set #delete {height:22px;}
The height on your #field is set to 22px so it must be the same on #delete.
As a side note, I'm sure you do already, but if not, Firebug or Chrome tools can be very helpful in debugging CSS, HTML, Javascript, and much more.
THE FIX
OK. I troubleshooted further for you. This seemed to work for me (and made sense), but I didn't have a good way to test on iOS, so you will have to update the link. For some reason, it was adding padding - 1px - to three sides of the #field form. Try changing #field { padding-left:25px } to #field { padding: 0 0 0 25px; } This should work as long height is set to the same value on both #field and #delete. Let me know if it works, and I'll update my answer.