text:
Q: CSS Link Static Page Before you mark this as a duplicate, I have indeed already looked at the django forums, tutorials, etc.
I have a blog I made with Django, the blog's index page template needs to have a css stylesheet that I have linked in my static folder. (Folder Tree attached
attached).
In the html for the template I have the following code:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}" />

Why is this not working! Thanks!
EDIT: I found this in my sitename/base.py file:
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

STATICFILES_DIRS = [
    os.path.join(PROJECT_DIR, 'static'),
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Could it be a problem with the directories? manage.py collectstatic -l says:

196 static files symlinked to
  '/home/myusername/webapps/mysite/static'.

A: Check the console while opening the view accessing this CSS file. The cmd console will print the absolute URL they will use to find CSS file. From the url, you can identify what is the problem. See how the URL is built.

A: comment the STATICFILES_URL [..], STATICFILE_FINDERS [..] and add the staticfiles_url like this:
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)


text:
Q: Select data from DBMS_UTILITY.LNAME_ARRAY DECLARE
ltab_vals DBMS_UTILITY.LNAME_ARRAY;
  v_tablen BINARY_INTEGER;
BEGIN

DBMS_UTILITY.COMMA_TO_TABLE(list   => 'AA,B,CC,DEF'
                              ,tablen => v_tablen
                              ,tab    => ltab_vals);

END;
/

How to use ltab_vals variable in select statement?
I need to write something like this:
SELECT val INTO variable_ FROM v_tablen WHERE ...;

A: you can only use SQL types in SQL statements. so you have to convert that PL/SQL array into a SQL one.
for example if we create a your_array type.
SQL> create table your_table(col varchar2(3));

Table created.

SQL> insert into your_table values ('AA');

1 row created.

SQL> insert into your_table values ('DEF');

1 row created.

SQL> create type your_array as table of varchar2(4000);
  2  /

Type created.

SQL> DECLARE
  2  ltab_vals DBMS_UTILITY.LNAME_ARRAY;
  3    v_tablen BINARY_INTEGER;
  4     v_t your_array := your_array();
  5  BEGIN
  6
  7    DBMS_UTILITY.COMMA_TO_TABLE(list   => 'AA,B,CC,DEF'
  8                                ,tablen => v_tablen
  9                                ,tab    => ltab_vals);

copy the array over to an SQL one:
 10    for idx in 1..ltab_vals.count
 11    loop
 12      v_t.extend;
 13      v_t(v_t.last) := ltab_vals(idx);
 14    end loop;
 15

now form the select using the table() function. The cardinality hint should be a reasonable guess on the number of elements in the array. without this hint, you may find that oracle picks a worse plan (as by default, it will assume ~8k rows in the array).
 17    for r_row in (select /*+ cardinality(p, 10) */ t.*
 18                    from your_table t
 19                         inner join table(v_t) p
 20                                 on t.col = p.column_value)
 21    loop
 22      dbms_output.put_line(r_row.col);
 23    end loop;
 24
 25  END;
 26  /
AA
DEF

PL/SQL procedure successfully completed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass exception information to an error page? I'm trying to pass error information back from an error on a Spring Webflow 2 page through an AbstractFlowHandler.    The relevant code looks like this:
@Override
public String handleException(FlowException e, HttpServletRequest request, HttpServletResponse response) {
    if (e instanceof NoSuchFlowExecutionException) {
        return DEFAULT_URL;
    } else {
        logger.warn(String.format("Flow threw exception %1$s", e.getMessage()), e);
        return ERROR_URL;
    }
}

EDIT: The "normal" result of simply returning back to the calling routine at this point is always a 302 REDIRECT, so the "request" and "response" objects attached to this call are lost, and fresh objects are created when the redirect is executed.   LeandreM's comment below (using forward()) gives a workaround, but it would be nice if there was some way around that redirect INSIDE the normal processing path.  However, I have not been able to find one.
What I would like to do is pass the exception object "e" along to the error page, so that I can print some information about it.  But I can't figure out the "proper" way to do this - do I attach it to the request object, the response object, or do it some other way?


text:
Q: PowerShell / Chocolatey, how to do an offline install of Chocolatey itself I would like to get chocolatey onto multiple systems. The normal way I do this is:
if (!(Test-Path "C:\ProgramData\chocolatey\bin")) {
    Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
}

That's fine, but this will connect to the internet, pointlessly re-downloading the Chocolatey package that I should be able to keep pre-downloaded, then extracting and setting up Chocolatey. This is like having to download a setup.exe every single time that you just want to install a program (for 20 systems, you would then have to download setup.exe 20 times), which slows things down and feels wasteful when I just want to get the choco.exe command available on systems as quickly as possible. I also don't mind if I have a slightly older version of chocolatey, I can redownload the main copy whenever I need.
It occurs to me that it should be easy to have the components pre-downloaded, so that I can just point at those files:

*

*What files do we need to pre-download to have everything required to setup Chocolatey?

*What command would we run against those files to set it up?

Note that this is quite a different question from How do you setup an offline Chocolatey instance?


text:
Q: Operator product expansion (of free field theory) in functional quantization approach (Note: Those who are already familiar with the notion of OPE's might prefer to skip directly to the Question section below)
Setup:
Consider, for simplicity, the quantum theory of the Euclidean K-G field.  That is, the "quantization" of the the classical field which obeys the equations of motion,
\begin{align}
(\partial^2-m^2)\phi=0,
\end{align}
where $\partial^2\equiv \sum^4_{i=1} \partial^2/\partial (x^i)^2$ with $x^i$ denoting elements of 4-dimensional Cartesian coordinates.
Following the "canonical" quantization procedure for the free field a la Peskin and Schroeder, I find the 2-point (Schwinger?) function
\begin{align}
\langle 0| \phi(x_1)\phi(x_2)|0\rangle=\Delta_E(x_1-x_2), \tag{1} \label{2point}
\end{align}
where $\Delta_E$ denotes the Euclidean propagator/Green's function,
\begin{align}
\Delta_E (x_1-x_2)= \int \frac{d^4p}{(2\pi)^4}\frac{e^{i p\cdot (x_1-x_2)}}{p^2+m^2},
\end{align}
where $p,x_1,x_2$ are 4-vectors and "$\cdot$" denotes the usual Euclidean inner product.
Now, the 2-point function \eqref{2point} clearly diverges in the coincidence limit $x_1\to x_2$, so it is customary to define the quadratic field operator via a "normal ordering" procedure.  This procedure is described in Peskin and Schroeder as "moving all the annihilation operators, $a_\vec{p}$, to the right of the creation operators, $a^\dagger_\vec{p}$" by hand, but this is essentially equivalent to subtracting off the vacuum contribution as,
\begin{equation}
:\phi(x_1)\phi(x_2):\equiv \phi(x_1)\phi(x_2)-\Delta_E(x_1-x_2), \tag{2}\label{normal}
\end{equation}
so that the vacuum expectation of the normal-ordered operators vanish: $\langle 0|:\phi(x_1)\phi(x_2):0\rangle=0$, by definition.  Hence, one now has a well-defined quadratic operator,
\begin{align}
:\phi^2(x_2):\equiv \lim_{x_1\to x_2} \left\{\phi(x_1)\phi(x_2)-\Delta_E (x_1-x_2)\right\},
\end{align}
in the sense that $\langle0|:\phi^2(x):|0\rangle$ is finite--and, in fact, zero for this choice of normal ordering.  (Of course, one could get a different vacuum expectation value via a different choice of normal ordering)
Definition of OPE coefficients: By an "operator product expansion" (OPE), I have in mind a short-distance asymptotic relation (see Scholarpedia article) which holds in any arbitrary (well-behaved) state,
\begin{align}
\langle \phi(x_1)\phi(x_2)\rangle \sim \sum_{A} C^{\phi\phi}_{A}(x_1,x_2) \langle \mathcal{O}^A(x_2) \rangle,
\end{align}
where $C^{\phi\phi}_A$ are the OPE coefficients of this expansion around $x_1\to x_2$ and the summation runs over all monomials of the fields and its derivatives.
For the free theory, it would appear such an expansion can be obtained via Taylor expanding the terms inside the normal ordering sign of \eqref{normal} as
\begin{align}
\phi(x_1)\phi(x_2)= \sum_{\alpha} \frac{(x_1-x_2)^\alpha}{\alpha!} :\partial_\alpha \phi(x_2)\phi(x_2):+\Delta_E (x_1-x_2), \label{expansion} \tag{3}
\end{align}
where $\alpha$ is a multi-index.
Clearly, the preceding expansion holds trivially in the vacuum state.  Because the particle states of the free theory can be expressed in terms of the vacuum, I believe such an expansion will hold for an arbitrary particle state.
Reading off the nontrivial coefficients of the expansion \eqref{expansion}, I find
\begin{align}
C^{\phi\phi}_{I}(x_1,x_2)&=\Delta_E (x_1-x_2)\\
C^{\phi\phi}_{\partial_\alpha\phi\phi}(x_1,x_2)&=\frac{(x_1-x_2)^\alpha}{\alpha!}. \tag{4} \\
\end{align}
I expect to obtain more complicated OPE's in the free theory simply from applications of Wick's theorem.
Question: In the "canonical" approach, I seem to obtain the OPE coefficients for the free theory via normal ordering and Wick's theorem.  However, it's not clear to me how one defines/obtains the OPE coefficients working instead strictly in the path integral approach or even how to get started in this direction.

A: The OPE is a statement about the asymptotic expansion when $x_1\longrightarrow x_2$ inside correlations. For this you need to introduce other fields just sitting there called spectator fields. It does not matter which formalism you use for calculating these correlations: canonical or path integral. For more mathematical precision about the OPE see my article https://arxiv.org/abs/1604.05259 If that's too much math look-up ref [114] I cited by Witten.

Edit with a bit more detail:
The correlations for the free field are given by the Isserlis-Wick's theorem:
$$
\langle \phi(x_1)\cdots\phi(x_n)\rangle=\sum_{\mathcal{W}}\prod_{\{a,b\}\in\mathcal{W}} \langle\phi(x_a)\phi(x_b)\rangle
$$
where $\mathcal{W}$ runs over all set partitions of $\{1,2,\ldots,n\}$
which only contain blocks of size two.
One the other hand
$$
\langle :\phi(x_1)\phi(x_2):\ \phi(x_3)\cdots\phi(x_n)\rangle=
\sum_{\mathcal{W}\ {\rm nonsingular}}\prod_{\{a,b\}\in\mathcal{W}} \langle\phi(x_a)\phi(x_b)\rangle
$$
where by "nonsingular" I mean all pair partitions $\mathcal{W}$ that do not contain the pair $\{1,2\}$. For these contributions there is no divergence when you take the limit $x_1\rightarrow x_2$ with $x_2,\ldots,x_n$ distinct and fixed. The full expansion is indeed obtained by writing the Taylor expansion (in multiindex notation)
$$
\phi(x_1)=\sum_{\alpha\in\mathbb{N}_{0}^d}\frac{(x_1-x_2)^{\alpha}}{\alpha!}\ \partial^{\alpha}\phi(x_2)
$$
"inside" these expressions.
The full OPE is obtained from
$$
\langle \phi(x_1)\cdots\phi(x_n)\rangle=
\langle \phi(x_1)\phi(x_2)\rangle\ \langle\phi(x_3)\cdots\phi(x_n)\rangle+
\langle :\phi(x_1)\phi(x_2):\ \phi(x_3)\cdots\phi(x_n)\rangle
$$
namely
$$
\langle \phi(x_1)\cdots\phi(x_n)\rangle=\sum_{A}\mathcal{C}_{A}^{\phi\phi}(x_1,x_2)
\langle \mathcal{O}_{A}(x_2)\phi(x_3)\cdots\phi(x_n)\rangle
$$
with
$$
\mathcal{C}_{1}^{\phi\phi}(x_1,x_2)=\langle \phi(x_1)\phi(x_2)\rangle
$$
and
$$
\mathcal{C}_{:(\partial^{\alpha}\phi)\phi:}^{\phi\phi}(x_1,x_2)=\frac{(x_1-x_2)^{\alpha}}{\alpha!}
$$


text:
Q: How to convert string to NSDate in Swift? How can I convert a string like 05/18/2017 this to NSDate?
I am trying to convert this string to NSDate so that I can extract the day as 18 and month as 05 and year as 2017. How can I convert this or can extract those values from strings.
func toDate(dateString : String, dateFormat : String = "yyyy-MM-dd'T'HH:mm:ssX")-> NSDate!{
  let dateFormatter = NSDateFormatter()
  dateFormatter.dateFormat = dateFormat
  dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
  dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
  let convertedDate = dateFormatter.dateFromString(dateString)
  return convertedDate
}

Now in code below selectedValue is 05/18/2017 but NSDateFromString always shows nil value:
let nsdateFromString = String.toDate(selectedValue)

What can I do in this case?

A: The default dateFormat value of your function toDate not matching the selectedValue's date format, so you need to pass dateFormat argument also with your method call with value MM/dd/yyyy.
let nsdateFromString = String.toDate(dateString: selectedValue, dateFormat: "MM/dd/yyyy")

A: **in SWIFT 3.0,**

let strDate = "12/21/2017"
let datefrmter = DateFormatter()
datefrmter.dateFormat = "mm/dd/yyyy"
let date = datefrmter.date(from: strDate)
print(date)

A: func convertSToD(date : String)-> Date?{
        if date != "NA"{
        let interval = Double(date)
        let dateFormat = Date(timeIntervalSince1970: interval!)
        return dateFormat
        }
        return nil
    }

A: Try this :-
func toDate(dateString : String, dateFormat : String = "MM/dd/yyyy")-> NSDate!{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let convertedDate = dateFormatter.dateFromString(dateString)
return convertedDate
}

A: Convert Current date and time
let formatter1 = DateFormatter()

        let date1 = Date.init()
        formatter1.dateFormat = "dd-MMM-yyyy hh:mm a"
        let days = formatter1.string(from: date1 as Date)

        print(days)

A: //in Swift 3.0 converting string to NSDate with its format
let dateString = self.scoring_date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
dateFormatter.locale = Locale.init(identifier: "en_GB")

self.dateObj = dateFormatter.date(from: dateString! as String )!

dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: self.dateObj))")

//converting NSDate to String
let today = Date()
today.toString(dateFormat: "dd-MM")


text:
Q: Check User's connections I am currently working on a discord bot (using the discord.js library). This bot uses steam integration to get a user's inventory. Is there a way to check if the person has steam connected to their account and get their steam account ID? If not, how should I make sure people can link their steam account to my bot?

A: I think you might search for this specific documentation/implementation (User -> UserProfile -> UserConnection), but I wouldn't recommend using it, since it is really instable and you can only use it as a normal user not as a bot.
I would rather think about implementing a link system on your own, where user can try to link their accounts and mods must approve those linkings.

A: The Discord API does not support this through Bot Accounts as far as I'm aware. As noted previously it's only possible using User accounts, though automating user accounts is against the Discord Terms Of Service and the Discord API Terms so I wouldn't recommend it.


text:
Q: slider gallery with touch recognition HI
i was following this example to create a slider gallery
"http://lievendekeyser.net/index.php?module=messagebox&action=message&msg_id=1351"
But i stuck at one point. what i am trying to do is, when user double tap on current image, it should navigate to another view, like to view B.
But i am not able to navigate and detect double tap on current image.
suggestions needed.
regards

A: you can find the number of tap in touch event. and when count of tap == 2 then you should write code for further movements.
else put all these images in UIButton and provide the IBActions to all the buttons and perform the action.
use following code
[ScrollViewFavButton addTarget:self action:@selector(FavClickButton:) forControlEvents:UIControlEventTouchUpInside];
        ScrollViewFavButton.tag = i;
[ScrlViewFavorite insertSubview:ScrollViewFavButton atIndex:i];
insert button in the scrollview and perform action in FacClickButton:.
I think now you'll get your answer.


text:
Q: Drawing Cash Flows I was wondering if there is any way to draw such diagrams on LaTeX. Those are cash flows I have a few to draw and need to integrate to my tex document.

A: \documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}[thick]
\draw (0,0) -- (5,0);
\foreach \Y [count=\X starting from 0] in {2,-1,-1,1,-2}
{\draw[-latex] (\X,0) node[below left]{\X} (\X,{-0.1*sign(\Y)}) -- (\X,\Y)
node[anchor={sign(\Y)*(-90)}]{$F_{\X}$};}
\end{tikzpicture}
\end{document}


text:
Q: Firebase Remote Config getInt() missing Firebase provides the following methods:

*

*getBoolean()

*getByteArray()

*getDouble()

*getLong()

*getString()

https://firebase.google.com/docs/remote-config/use-config-android#get-parametervalues-to-use-in-your-app
But getInt() is missing from this list, I'm curious if there's a reason for this? Is the preferred approach to use Long or String and cast/convert to an int?

A: Looks like iOS has it, oddly enough.
Since int is a subset of long, you should use this to store your integer.


text:
Q: Mybatis skipping update the specific column if its parameter is null I HAVE A FOLLOWING UPDATE QUERY IN A MAPPER
<update id="updTest" parameterType="TestDTO">
    <![CDATA[
        UPDATE   TEST_USER

        SET
              EMAIL          =  #{email, jdbcType=VARCHAR}
            , USERNAME       =  #{username, jdbcType=VARCHAR}
            , PASSWORD       =  #{password, jdbcType=VARCHAR}
            , DOMAIN         =  #{domain, jdbcType=VARCHAR}
            , COMPANY        =  #{company, jdbcType=VARCHAR}
            , DEPARTMENT     =  #{department, jdbcType=VARCHAR}
            , JOBTITLE       =  #{jobtitle, jdbcType=VARCHAR}
            , SIZE           =  #{size, jdbcType=INTEGER}
            , SEX            =  #{sex, jdbcType=VARCHAR}
            , BIRTH          =  #{birth, jdbcType=VARCHAR}
            , MOBILE         =  #{mobile, jdbcType=VARCHAR}
            , STATUS         =  #{status, jdbcType=VARCHAR}
            , AUTH_KEY       =  #{authKey, jdbcType=VARCHAR}
            , UPDATE_DATE    =  SYSDATE
            , UPDATE_ID      =  #{updateId, jdbcType=VARCHAR}
            , CREATE_DATE    =  SYSDATE
            , CREATE_ID      =  #{createId, jdbcType=VARCHAR}
            , DEL_YN         =  #{delYn, jdbcType=VARCHAR}
            , DEL_ID         =  #{delId, jdbcType=VARCHAR}

        WHERE   USERNAME= #{username, jdbcType=VARCHAR}
        OR      EMAIL = #{email, jdbcType=VARCHAR}
        OR      AUTH_KEY = #{authKey, jdbcType=VARCHAR}
    ]]>
</update>

WHAT I WANT TO ACHIEVE is to skip updating a column if its parameter is null.
I have a form that users will fill in these below out.

*

*JOBTITLE

*SIZE

*MOBILE

*BIRTH

*SEX

*STATUS

This is additional information, which comes after a successful login. But when a user fills out the form and submits it, updating process works great.
But the exisiting EMAIL, USERNAME, PASSWORD and others are set to null except for those 6 fields in the form. it drives me crazy, I always thought that Mybatis would skip updating the field if its parameter is null. Is there any special configuration for it?

A: Your gripe is with SQL, not MyBatis. If your update statement includes say SET mobile = null, the SQL will do just that.
But MyBatis provides good dynamic SQL facilities with the if statement. See https://mybatis.github.io/mybatis-3/dynamic-sql.html. That should put you on the right track for a custom solution.
Also, consider changing your schema (if it is under your control). There should be a numeric userId field as primary key, allocated by a sequence or similar. Alternatively USERNAME is common key in such situations. Either will simplify your WHERE clause, and is pretty much standard practice. As it stands, EMAIL appears to be part of the primary key, so changing an email address will mean they become a different user.
And a last comment. I have never used CDATA in a MyBatis SQL query, but it probably does no harm.
<editFollowingComment>
I think you need to revisit your requirements, as some don't make a lot of sense.

*

*Your WHERE clause is really odd. If a family of six all share the same email address, do you really want to update all six records when one logs in? You need to decide on a unique primary key and USERNAME makes perfect sense.

*Having decided on USERNAME as the unique primary key for the table, you can delete the last two lines of the WHERE clause and also take USERNAME out of the SET list, as it can never change.

*How are you going to handle the case of an existing user that decides they are no longer going to own a mobile? It seems you do need to set MOBILE to null in this case.

*The AUTH_TOKEN field is a strange one to find in a database. Authorisation tokens are usually only valid for the duration of a login session - but I might have misunderstood your use case.

So getting back to your comment, I suggest that you write a MyBatis update that only updates the six fields on your form (named something like updateLoginFields), with a WHERE clause that specifies only USERNAME. You don't need to worry about nulls, as you can control what is optional in the presentaion layer.
</editFollowingComment>


text:
Q: Understanding Test Coverage I have a simple package in my Go program to generate a hash ID.
I've also written a test for it but not able to understand why I'm only getting 83% of statements covered.
Below is my package function code:
package hashgen

import (
    "math/rand"
    "time"

    "github.com/speps/go-hashids"
)

// GenHash function will generate a unique Hash using the current time in Unix epoch format as the seed
func GenHash() (string, error) {

    UnixTime := time.Now().UnixNano()
    IntUnixTime := int(UnixTime)

    hd := hashids.NewData()
    hd.Salt = "test"
    hd.MinLength = 30
    h, err := hashids.NewWithData(hd)
    if err != nil {
        return "", err
    }
    e, err := h.Encode([]int{IntUnixTime, IntUnixTime + rand.Intn(1000)})

    if err != nil {
        return "", err
    }

    return e, nil
}

Below is my test code:
package hashgen

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestGenHash(t *testing.T) {
    hash, err := GenHash()
    if err != nil {
        assert.Error(t, err, "Not able to generate Hash")

    }
    assert.Nil(t, err)
    assert.True(t, len(hash) > 0)
}

Running Go test with coverprofile mentions that following portions are not covered by the test:
if err != nil {
        return "", err
    }

Any advice?

A: Thanks for the replies.
I broken down my function GenHash() into smaller pieces to test the errors returned by the go-hashids package. Now I'm able to increase the test coverage percentage.

package hashgen

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestGenHash(t *testing.T) {
    hash, err := GenHash()
    if err != nil {
        assert.Error(t, err, "Not able to generate Hash")

    }
    assert.Nil(t, err)
    assert.True(t, len(hash) > 0)
}

func TestNewhdData(t *testing.T) {
    hd := newhdData()

    assert.NotNil(t, hd)
}

func TestNewHashID(t *testing.T) {
    hd := newhdData()

    hd.Alphabet = "A "
    hd.Salt = "test"
    hd.MinLength = 30

    _, err := newHashID(hd)

    assert.Errorf(t, err, "HashIDData does not meet requirements: %v", err)

}


text:
Q: Make an element draggable diagonally / on path I've made elements draggable on a straight path and fixed to an axis before using jQuery UI, like so:
$('#element').draggable({
    axis:'y'
});

However, I'm wondering how to make an element draggable while following a certain path that is essentially a draggable line.
I basically have one style / position of the element in the beginning and another style / position of its end location and I want it to be draggable along the path between these two positions.
How can I do this with javascript or jQuery?

A: I don't think jQuery provides that kind of functionality. However, you can do it in pure JavaScript, or use this plugin I made:
$.fn.dragBetween = function(eles) {
    var dragEle = this,
        md = false, offset, a, b, ab;
    eles[0] = $(eles[0])[0];
    eles[1] = $(eles[1])[0];
    dragEle.on("mousedown", function(e) {
        if (e.which == 1) {
            mD = true;
            offset = new Vector(
                e.clientX - this.offsetLeft,
                e.clientY - this.offsetTop
            );
            a = new Vector(eles[0].offsetLeft, eles[0].offsetTop);
            b = new Vector(eles[1].offsetLeft, eles[1].offsetTop);
            ab = b.sub(a);
        }
    });
    $(window).on("mousemove", function(e) {
        if (!mD) return false;

        var cursor = new Vector(e.clientX, e.clientY).sub(offset).sub(a),
            mag = cursor.dot(ab) / ab.dot(ab),
            proj = ab.times(Math.max(0, Math.min(1, mag)));
        var final = proj.add(a);
        dragEle.css({
            top: final._arr[1],
            left: final._arr[0]
        });
        e.preventDefault();
    }).mouseup(function() {
        mD = false;
    });
};

And this is the Vector class I wrote in a hurry:
function Vector(x, y) {
    this._arr = [x, y];
}
Vector.prototype.dot = function(v2) {
    var v1 = this;
    return v1._arr[0] * v2._arr[0] + v1._arr[1] * v2._arr[1];
}
Vector.prototype.add = function(v2) {
    var v1 = this;
    return new Vector(v1._arr[0] + v2._arr[0], v1._arr[1] + v2._arr[1]);
}
Vector.prototype.sub = function(v2) {
    var v1 = this;
    return new Vector(v1._arr[0] - v2._arr[0], v1._arr[1] - v2._arr[1]);
}
Vector.prototype.times = function(n) {
    var v = this;
    return new Vector(v._arr[0] * n, v._arr[1] * n);
}

To call it, simply do:
$("#drag").dragBetween(["#a", "#b"]);

Demo: http://jsfiddle.net/DerekL/0j6e60d8/
For formula explanation, see: https://www.desmos.com/calculator/tpegbbk8gt

A: I wasn't able to use Derek's answer because you lose the other features jquery ui draggable provides like containment.
I found to make it drag diagonally, you can modify the css using the drag event like this:
$(".leftTopCircle").draggable({ axis:"x", containment: ".topLeft", scroll: false });
$(".leftTopCircle").on( "drag", function(event, ui){
    $(this).css("top", ui.position.left+"px");
});


text:
Q: Apache Spark Temp files Size on DIsk I have a setup where the incoming data from Kafka cluster is processed by Apache Spark streaming job.
Version Info :-
Kafka = 0.8.x
Spark Version = 2.3.1
Recently when the capacity of Kafka cluster was increased(by adding new nodes) we suddenly saw an exponential increase in disk usage of spark clusters(most of the space was occupied by spark temp files)
I am not sure if these are related and wanted some pointers to address/debug the same.
As a precaution we have increased the disk space of spark clusters to avoid "No space left on device" error.


text:
Q: chromecast on chrome packaged app I would like to add the ability to cast my chrome packaged app to a google chromecast device.
So far google states that all you have to do is add
to your page and the API will inject itself.
For me that doesn't happen. No code is injected.
Am I doing something wrong?
There doesn't seem to be a demo showing this type of capability.
EDIT:
I just wanted to clarify a bit. All that I would like to do is display my app to a screen.
I have no media. I simply want to display it exactly as the chrome extension in the chrome browser would.Therefore I would follow the directions for a sender only. The app is packaged so it is running only CSS/JS/HTML5 code. The app is designed to run offline.
Steps I've taken to cast:
1. I've added the extra bit to the HTML line:

2. I've followed the whitelisting, to the best of my understanding, by adding my "website address" to the chrome extension. So I've added the only two address that should matter.
127.0.0.1
192.168.1.106

A: There is a good chance Content Security Policy is blocking the implementation of the cast API being injected. I see that you've filed Issue 287254: Google cast (chromecast) ability for packaged apps, and suspect we will need to wait for it to be implemented in a packaged apps compliant way.

A: You must whitelist your device and your Chrome app.  See here for more details:
https://developers.google.com/cast/whitelisting#whitelist-chrome


text:
Q: How to assert the result of a form submission I have the following test:
var start_url = 'http://example.com/';
var account_email = 'olav@example.com';
var account_password = '****';

module.exports = {
  'test login': function (test) {
    'use strict';
    test
      .open(start_url)
      .assert.visible('#login')
      .click('#login')
      .type('#email-field', account_email)
      .type('#password-field', account_password)
      .submit('#login-form')
      .assert.visible('#logout')
      .done();
  }
};

The .assert.visible('#logout') does not work. I suspect that I need to introduce some kind of waitFor() but I have not found an example of how to do this.
-- Olav

A: You should add a

test.waitForElement('#logout')

after your submit() & before your assert.visible('#logout') calls.
If this does not work, than it is maybe you hit the max timeout of the waitForElement function, you can extend the timeout by setting a second parameter like this:

test.waitForElement('#logout', 10000)

You can find more information in the docs
If this still does not work then, please open up an issue here
As a workaround I would suggest, to use the test.wait(7500) method, but this should be the last option if the solution described above does not work. If thats the case, please open up an issue.
Thanks.


text:
Q: Implement Long press on button and show delete button on top of that button like deleting app from background I want to implement a long press on my button and after that long press a cross button should appear on the top of the button to remove that button from scroll view which is added in table view.
I search on web and got UILongPressGestureRecognizer to implement.I tried with it but I have many button in my scroll view and I put UILongPressGestureRecognizer on every button but how will I give reference of the pressed button to the selector method so that I can add a cross button on that particular pressed button.
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(deleteAppFromList:)];
UIButton *btn=(UIButton *)[cell.contentView viewWithTag:101+i];
[btn addGestureRecognizer:longPressGesture];
[longPressGesture release];

Please suggest me how to implement this.I want to do the functionality just as when we delete an app from ios device or simulator.

A: I've just done something similar. I detect the touchDown event, schedule a timed method which sets a flag after 1 second, then when the touch up event is detected it checks the flag and calls the appropriate method.
[myButton addTarget:self action:@selector(itemTouchDown) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(itemTouchUpInside) forControlEvents:UIControlEventTouchUpInside];

-(void)itemHoldTimer:(NSTimer *)timer
{
    self.itemHoldTimer = nil;
    didHold = YES;
}

-(void)itemTouchDown{
    didHold = NO;
    self.itemHoldTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(itemHoldTimer:) userInfo:nil repeats:NO];
}

-(void)itemTouchUpInside {
    if (didHold) {
        didHold = NO;
        [self itemWasTouchedUpAndDidHold];
    } else {
        didHold = NO;
        [self itemWasTouchedUp];
    }
}

A: In your handler method that you set up as the target of the gesture recognizer you are passed a reference to the recognizer that fired, e.g.:
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;

The recognizer has a 'view' property, which is the view the recognizer is attached to. Use this directly or get the tag of this view and you can work out which button was pressed.
UIView *myButton = gestureRecognizer.view;

Having said that, adding a gesture recognizer to each button seems the wrong way to do this. I would create a custom control and handle 'touchesBegan' and 'touchesEnded' directly.

A: In the handler method of the long press recognizer, use the view property and its tag to identify the view.
-(void)handleLongPress:(UILongPressGestureRecognizer*)longPressRecognizer
{
    //longPressRecognizer.view.tag
}


text:
Q: Google's shebang #! syntax for ajax crawling not resulting in crawled pages I have a site which has implemented Google's shebang '#!' syntax for ajax crawling.
Both sides of the system have been implemented as discussed at https://developers.google.com/webmasters/ajax-crawling/docs/specification
In other words, URLs for an Ajax-created page such as: http://avianguitars.ca/configurator/#!S
is mapped to static HTML versions which is cached server side at http://avianguitars.ca/configurator/?_escaped_fragment_=S
Google should see the #! syntax, crawl the _escaped_fragment_ version, and display it on Google with the original http://avianguitars.ca/configurator/#!S URL.
I have also added URLs in the format http://avianguitars.ca/configurator/#!S to the site's sitemap, which is submitted through Google's developer tools, however the !# URLs all appear to be ignored and are still not indexed.
Another example of a 'shebanged' URL is http://avianguitars.ca/configurator/#!action=showline&lineid=46 which maps to http://avianguitars.ca/configurator/?_escaped_fragment_=action%3Dshowline%26lineid%3D46
All other (non-ajax) URLs submitted via the sitemap are accepted, and I assume that general crawling would have picked up the URLs by now too.
Is there anything obvious I am missing which is preventing the links from being indexed?

A: Yes, you have missed something. You need to add <meta name="fragment" content="!" /> to tell that your shebang URL uses an identifier fragment.
This will tell you more on the side of Google: https://developers.google.com/webmasters/ajax-crawling/docs/specification

A: Make sure to output a link rel=canonical tag in your HEAD when the page is requested using the _escaped_fragment parameter.
So when your page is requested using the special parameter, include this in your output:
<link rel="canonical" href="http://avianguitars.ca/configurator/#!action=showline&lineid=46"/>

I have a site that is completely hashbang-based and it is fully indexed (312 URLs submitted, 309 URLs indexed). I just compared your site to mine, and this is the only thing that seems to be missing. I am not sure this is the solution to your problem, but i dont see it in your html. I added this tag because i read it somewhere in the google documentation, but now i cant seem to find it anymore ...
Also, my site does not include this:
<meta name="fragment" content="!" />

... but that didnt prevent it from being indexed.
Also, the url's in google sitemap should use the hashbang syntax, NOT the _escaped_fragment syntax. If you keep having problems, try registering your website with google webmaster tools and see if any problems are reported there:
https://www.google.com/webmasters/tools/


text:
Q: What is the best way to manage interdependent indexes So I have a table of items as so
|firstIndex|subIndex|relatedIndexes|
-----------------------------------
|     1    |   1    |  2 ,6 , 8    |
-----------------------------------
|     1    |   2    |  2 ,6 , 8    |
-----------------------------------
|     1    |   3    |  2 ,6 , 8    |
-----------------------------------
|     2    |   1    |  1, 10 , 12  |
-----------------------------------
|     3    |   1    |  20, 50, 77  |
-----------------------------------
|     4    |   1    |  ...         |
-----------------------------------

So both firstIndex an subIndex are the primary keys (they cannot be two times the same combination, hope I'm clear :) ), subIndex is the index representing the number of the variation of firstIndex and finally relatedIndexes is the array of  firstIndex related to other firstIndex. As you can see in the sample firstIndex 1 is related to firstIndex 2 and 2 to 1
My question is how can I represent, store and manage this model the easiest and quickiest way in MYSQL?

A: It can looks like
CREATE TABLE indices (firstIndex INT NOT NULL,
                      subIndex INT NOT NULL,
                      PRIMARY KEY (firstIndex, subIndex)
                     );

CREATE TABLE refs (baseIndex INT NOT NULL,
                   relatedIndex INT NOT NULL,
                   PRIMARY KEY (baseIndex, relatedIndex),
                   FOREIGN KEY fk_bi (baseIndex) REFERENCES indices (firstIndex),
                   FOREIGN KEY fk_ri (relatedIndex) REFERENCES indices (firstIndex)
                  );

Update

why there's a baseIndex + relatedIndex

It is a "link" table (instead of non-relational CSV-field relatedIndexes). The (2,6,8) value for firstIndex=1 in a source scheme is transferred to 3 separate records in refs with (1,2),(1,6),(1,8) value pairs.

what is Foreign Key

It is constraint references which do not allow to insert into refs an index value which not exists in indices table. And prevents deletion a record from indices while at least one reference exists in refs.


text:
Q: Any known ways to convert CSV arrays to JSON files with nodes & edges brief example
CSV file :
name, source, target
John  , A ,    None
Emma  , B ,    A
Mike  , C ,    A

theoretical corresponding JSON file :
{
  "comment": "example code",
  "nodes": [
    {
      "name": John,
      "source" : A
    },
    {
      "name": Emma ,
      "source" : B
    },
    {
      "name": Mike ,
      "source" : C
    }
  ],
  "links": [
    {
      "source": B,
      "target": A
    },
    {
      "source": C,
      "target": A
    }
  ]
}

resulting graph concept:
B  -> A  <-  C

the JSON file above is not absolute. It can have a variety of schemas. Above example is just very basic.
I am hoping there is a software or library that can easily turn CSV array to JSON files or something along those lines.
I have many CSV files that I'd like to turn into JavaScript graphs, but first I need a JSON input file that has data well structured. I would like to automate JSON file construction.

A: Here is an example using csvtojson.
const csv = require('csvtojson');

const csvFilePath = 'test.csv';
var data = [];

csv().fromFile(csvFilePath)
    .on('json', (jsonObj) => {
        data.push(jsonObj);
    })
    .on('done', (error) => {
        if (error) {
            console.error(error);
        } else {
            formatData(data);
        }
    });

function formatData(data) {

    var formatted = {
        comment: "hello",
        nodes: [],
        links: []
    };

    data.forEach(function(r){

        //check for your empty or 'None' fields here
        if(r.name && r.source){
            formatted.nodes.push({ name: r.name, source: r.source });
        }

        if (r.source && r.target) {
            formatted.links.push({ source: r.source, target: r.target });
        }
    });

    //do something with the finished product
    console.log(formatted);
}

A: Here is a solution using jq
If the file filter.jq contains
[
  split("\n")                                                    # split string into lines
| [.[0]    | split(",")[] | gsub("[[:space:]]+";"")] as $headers # split header
| (.[1:][] | split(","))                                         # split data rows
| select(length>0)                                               # get rid of empty lines
| [   [ $headers, map(gsub("[[:space:]]+";"")) ]                 #
    | transpose[]                                                # assemble objects
    | {key:.[0], value:.[1]}                                     # from keys and values
  ] | from_entries                                               #
]
| {
    "comment":"example code",                                    # convert objects
    "nodes": map({name,source}),                                 # to requested format
    "links": map(select(.target!="None")|{source,target})        #
  }

and data contains
name, source, target
John  , A ,    None
Emma  , B ,    A
Mike  , C ,    A

then the command
jq -M -R -s -r -f filter.jq data

will produce
{
  "comment": "example code",
  "nodes": [
    {
      "name": "John",
      "source": "A"
    },
    {
      "name": "Emma",
      "source": "B"
    },
    {
      "name": "Mike",
      "source": "C"
    }
  ],
  "links": [
    {
      "source": "B",
      "target": "A"
    },
    {
      "source": "C",
      "target": "A"
    }
  ]
}


text:
Q: Combine/sort columns with dplyr and/or tidyr EDIT: I've tried a solution below, but as I need to convert the factors to characters and back to factors, I lose some important information.
Having this table, I want it to be sorted from this,
From    To  count
A       B     2
A       C     1
C       A     3
B       C     1

to this,
  From To count
1    A  B     2
2    A  C     4
3    B  C     1

So far I see two options, either to do this:
df[1:2] <- t(apply(df[1:2], 1, sort))
aggregate(count ~ From + To, df, sum)

which is quite slow as I'm working with 9.000.000 observations. Or simply to convert this into an iGraph network, and merge the edges.
g <- graph_from_data_frame(df, directed = TRUE, vertices = nodes)
g <- as.undirected(g, mode = "mutual", edge.attr.comb=list(weight = "sum"))

The 2 problems I have are that the first option I've mentioned should actually use dplyr or tidyr, but I couldn't figure out how to do it so far.
The network/igraph option which is quicker than the "t(apply(" option, but I still need to convert the graph back to a data.table for further analysis.
Any idea on how to run the "t(apply(" option with dplyr or tidyr?

A: We can use pmin/pmax.  Should be faster
library(dplyr)
df1 %>%
    group_by(From1 = pmin(From, To), To = pmax(From, To)) %>%
    summarise(count = sum(count)) %>%
    rename(From = From1)
#  From    To count
#  <chr> <chr> <int>
#1     A     B     2
#2     A     C     4
#3     B     C     1

A: In base R, we can combine akrun's pmin and pmax suggestion with aggregate using the non-formula interface as follows:
aggregate(df$count, list(From=pmin(df$From, df$To), To=pmax(df$From, df$To)), sum)
  From To x
1    A  B 2
2    A  C 4
3    B  C 1

Note that this requires that df$From and df$To are character vectors, not factors.
timings
This method is faster than using apply as it doesn't involve conversion to matrices. Using the data larger data set below, with 9 million observations, the time to completion using pmin and pmax with aggregate was 14.5 seconds on my computer whereas the OP's method with apply took 442.2 seconds or 30 times longer.
data
df <-
structure(list(From = c("A", "A", "C", "B"), To = c("B", "C",
"A", "C"), count = c(2L, 1L, 3L, 1L)), .Names = c("From", "To",
"count"), class = "data.frame", row.names = c(NA, -4L))

larger sample data
set.seed(1234)
df <- data.frame(From=sample(LETTERS, 9e6, replace=TRUE),
                 To=sample(LETTERS, 9e6, replace=TRUE),
                 count=sample(100, 9e6, replace=TRUE),
                 stringsAsFactors=FALSE)

A: library(tidyverse)
cols_before_merge <- c("From", "To")
out_cols <- c("col_1", "col_2")

df <- tibble::tribble(
  ~From, ~To, ~count,
  "A", "B", 2,
  "A", "C", 1,
  "C", "A", 3,
  "B", "C", 1,
)

With the above, I think the  tidyverse approach to creating the unique keys would be:
df_out <- df %>%
  dplyr::mutate(
    key = purrr::pmap_chr(
      list(From, To),
      ~ stringr::str_c(stringr::str_sort(c(...)), collapse = "_")
    )
  )

Or for a more programmatic approach using tidy evaluation:
merge_sort <- function(cols_values) {
  purrr::pmap_chr(
    cols_values,
    ~ stringr::str_c(stringr::str_sort(c(...)), collapse = "_")
  )
}

add_key <- function(cols) {
  # column names need to be evaluated using the dataframe as an environment
  cols_quosure <- rlang::enquo(cols)

  # column names should be symbols not strings
  cols_syms <- rlang::syms(cols)

  cols_values <- purrr::map(
    cols_syms,
    ~ rlang::eval_tidy(.x, rlang::quo_get_env(cols_quosure))
  )

  merge_sort(cols_values)
}

# Adding columns for key construction programmatically
df_out <- df %>%
  dplyr::mutate(key = add_key(cols_before_merge))

And finally to get a count and make sure the output columns are factors (as akrun points out the factor levels before and after within row sorting could very easily be different).
df_out %>%
  dplyr::count(key, name = "count") %>%
  tidyr::separate(key, sep = "_", into = out_cols) %>%
  dplyr::mutate_at(out_cols, as.factor)


text:
Q: Detect if any key is pressed in C# (not A, B, but any) [EDIT 3]
I kind of "solved it" by at using the "strange" version. At least for the most important keys. It is suffient for my case, where I want to check that ALT and ALT+A are not the same (thereby making sure A is not pressed). Not perfect, but already to much time for such a tiny problem. Thanks for all the answers anyway...
[EDIT 3]
[EDIT 4] Solved it much cleaner thanks to 280Z28 [/EDIT 4]
I know how to check for modifier keys and how to test for a single key.
The problem is, I want to check if any key is pressed. The following approach seems "strange" :-)
WPF Application written in C#
if (Keyboard.IsKeyDown(Key.A)) return true;
if (Keyboard.IsKeyDown(Key.B)) return true;
if (Keyboard.IsKeyDown(Key.C)) return true;

I know it is an enum, so I thought about a loop, but what is the "biggest number" to use. And is this possible? btw, its a very special case, normally I would use an event, but in this case I have to do it this way. Unfortunatily, the there is no "list" Keyboard.CurrentlyDownKeys. At least I didnt see it.
Thanks,
Chris
EDIT: Ok, because it seems to be a bigger deal, here the reason for this:
I have defined a "KeySet" which serves as DictionaryKey for custom functions. If anybody clicks on an element, the wrapper iterates through the dictionary and checks if any of the predefined "Keysets" is active.
This allows me to define simple triggers, like e.g. Run this function if ALT+A+B is pressed. Another option is e.g. Run this function if ALT+STRG+A is pressed (during a mouse click on a WPF element).
The only "problem" with the current implementation, if I define a Keyset which does NOT contain any REAL keys, like run if ALT is pressed, it is also triggered if ALT+A is pressed. Oh, while writing this, I realize that there is another problem. ALT+A+B would currently also trigger if ALT+A+B+C is pressed.
Perhaps my approach is wrong, and I should create a "static key tracker" and compare the keyset to its values (aquired via events).. I will give this a try.
EDIT 2
This is not working, at least not in a simple way. I need an FrameworkElement to attach to KeyDown, but I do not have it in a static constructor. And I am not interested in KeyDownEvents of a certain element, but "globally"...I think I juts postpone this problem, its not that important. Still, if anybody knows a better of different approach...
So long, for anyone who cares, here some code:
public class KeyModifierSet
{
    internal readonly HashSet<Key> Keys = new HashSet<Key>();
    internal readonly HashSet<ModifierKeys> MKeys = new HashSet<ModifierKeys>();

    public override int GetHashCode()
    {
        int hash = Keys.Count + MKeys.Count;
        foreach (var t in Keys)
        {
            hash *= 17;
            hash = hash + t.GetHashCode();
        }
        foreach (var t in MKeys)
        {
            hash *= 19;
            hash = hash + t.GetHashCode();
        }
        return hash;
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as KeyModifierSet);
    }

    public bool Equals(KeyModifierSet other)
    {
        // Check for null
        if (ReferenceEquals(other, null))
            return false;

        // Check for same reference
        if (ReferenceEquals(this, other))
            return true;

        // Check for same Id and same Values
        return Keys.SetEquals(other.Keys) && MKeys.SetEquals(other.MKeys);
    }

    public bool IsActive()
    {
        foreach (var k in Keys)
            if (Keyboard.IsKeyUp(k)) return false;

        if ((Keys.Count == 0) && !Keyboard.IsKeyDown(Key.None)) return false;

        foreach (var k in MKeys)
            if ((Keyboard.Modifiers & k) == 0) return false;

        if ((MKeys.Count == 0) && Keyboard.Modifiers > 0) return false;

        return true;
    }

    public KeyModifierSet(ModifierKeys mKey)
    {
        MKeys.Add(mKey);
    }

    public KeyModifierSet()
    {

    }

    public KeyModifierSet(Key key)
    {
        Keys.Add(key);
    }

    public KeyModifierSet(Key key, ModifierKeys mKey)
    {
        Keys.Add(key);
        MKeys.Add(mKey);
    }

    public KeyModifierSet Add(Key key)
    {
        Keys.Add(key);
        return this;
    }

    public KeyModifierSet Add(ModifierKeys key)
    {
        MKeys.Add(key);
        return this;
    }
}

A: Using the XNA framework you can use thw follow for checking if any key has been pressed.
Keyboard.GetState().GetPressedKeys().Length > 0

A: Quite an old question but in case anyone comes across this and doesn't want to use external dll's, you could just enumerate the possible keys and loop over them.
bool IsAnyKeyPressed()
{
    var allPossibleKeys = Enum.GetValues(typeof(Key));
    bool results = false;
    foreach (var currentKey in allPossibleKeys)
    {
        Key key = (Key)currentKey;
        if (key != Key.None)
            if (Keyboard.IsKeyDown((Key)currentKey)) { results = true; break; }
    }
    return results;
}

You could optimize this a bit by doing the enum outside of the function and retaining the list for later.

A: [DllImport("user32.dll", EntryPoint = "GetKeyboardState", SetLastError = true)]
private static extern bool NativeGetKeyboardState([Out] byte[] keyStates);

private static bool GetKeyboardState(byte[] keyStates)
{
    if (keyStates == null)
        throw new ArgumentNullException("keyState");
    if (keyStates.Length != 256)
        throw new ArgumentException("The buffer must be 256 bytes long.", "keyState");
    return NativeGetKeyboardState(keyStates);
}

private static byte[] GetKeyboardState()
{
    byte[] keyStates = new byte[256];
    if (!GetKeyboardState(keyStates))
        throw new Win32Exception(Marshal.GetLastWin32Error());
    return keyStates;
}

private static bool AnyKeyPressed()
{
    byte[] keyState = GetKeyboardState();
    // skip the mouse buttons
    return keyState.Skip(8).Any(state => (state & 0x80) != 0);
}

A: If you're using Windows.Forms, use the KeyDown event and read out the specific key using the appropriate KeyEventArgs. You can access the KeyCode property on the KeyEventArgs variable.
To check for ranges, say between A and Z:
if (e.KeyCode>=Keys.A && e.KeyCode<=Keys.Z)
{
  // do stuff...or not
}

A: Where is this code running from? Is it in an event handler? Many forms and controls will fire a KeyPress event as well as a KeyDown event. You may want to look into those events and set your flag to true when one of them occurs. You'd also have to listen for the corresponding event that tells you when the key is released (KeyUp, also, I think).

A: http://sourceforge.net/projects/keystate/ shows "special" keys.  Otherwise I think you're just going to have to monitor them.  SOunds like you want to do this systemwide?  What are you trying to accomplish?

A: You can increment a counter for each keydown event, and decrement it for each keyup event. When the counter is zero, no keys are down.

A: To detect which key is pressed, you need to check every key state and which key is currently pressed or down.
Remember:Press & Down have difference.
    Public Sub Main()
        While True
            For i As Integer = 8 To 222
                Select Case i
                    Case 8, 13, 32, 48 To 57, 65 To 90, 186 To 192, 219 To 222
                        If GetAsyncKeyState(i) = -32767 And Not IsKeyDown(Keys.Control) Then
                            Console.Write(CodeToChar(i))
                        End If
            End Select
        Next
    End Sub

    Public Function IsKeyDown(Key As Keys) As Boolean
        Return (Control.ModifierKeys And Key) = Key
    End Function

    Function CodeToChar(i As Integer) As String
        Dim Character = Nothing
        IsShiftDown = IsKeyDown(Keys.Shift)
        If i > 64 And i < 91 Then c = If(Control.IsKeyLocked(Keys.CapsLock) Or IsShiftDown, Chr(i).ToString.ToUpper, Chr(i).ToString.ToLower)
        If i = 8   Then Character = "[BACK]"
        If i = 13  Then Character = vbnewline
        If i = 32  Then Character = " "
        If i = 48  Then Character = If(IsShiftDown, ")", "0")
        If i = 49  Then Character = If(IsShiftDown, "!", "1")
        If i = 50  Then Character = If(IsShiftDown, "@", "2")
        If i = 51  Then Character = If(IsShiftDown, "#", "3")
        If i = 52  Then Character = If(IsShiftDown, "$", "4")
        If i = 53  Then Character = If(IsShiftDown, "%", "5")
        If i = 54  Then Character = If(IsShiftDown, "^", "6")
        If i = 55  Then Character = If(IsShiftDown, "&", "7")
        If i = 56  Then Character = If(IsShiftDown, "*", "8")
        If i = 57  Then Character = If(IsShiftDown, "(", "9")
        If i = 186 Then Character = If(IsShiftDown, ":", ";")
        If i = 187 Then Character = If(IsShiftDown, "+", "=")
        If i = 188 Then Character = If(IsShiftDown, "<", ",")
        If i = 189 Then Character = If(IsShiftDown, "_", "-")
        If i = 190 Then Character = If(IsShiftDown, ">", ".")
        If i = 191 Then Character = If(IsShiftDown, "?", "/")
        If i = 192 Then Character = If(IsShiftDown, "~", "`")
        If i = 219 Then Character = If(IsShiftDown, "{", "[")
        If i = 220 Then Character = If(IsShiftDown, "|", "\")
        If i = 221 Then Character = If(IsShiftDown, "}", "]")
        If i = 222 Then Character = If(IsShiftDown, """", "'")
        Return Character
    End Function

Convert here if you want to use c# version.
Read keylogger codes to learn more about key-states.

A: normally I would use an event

You should still be using an event, preferably KeyDown since you don't mind what key is pressed, if you are programming on windows. If not, you could use something like Console.ReadLine();.
edit: If you are looking for something like
if (Keyboard.IsKeyDown(Key.AnyKey)) return true;

then you must be joking...
edit 2: Well, the approach of your logger is interesting, but I think that you are reinventing the wheel. All programming languages provides some way to handle wich key was pressed, when this can be known. In C# for Windows, this is done using events. Besides, I think you won't be able to handle this kind of things by yourself in .NET, since you need to access some system functions from the Win32 API, and AFAIK you aren't allowed to do this (at least easily...) in managed code. Some solution would be to create a HOOK and send messages from there to your application, but I don't know how to do this in C#. This was the way in Delphi, where I have more experience.

A: In the Key Enumeration there is an Enumeration value of Zero(0), which basically tests "No Key Pressed", which is opposite of "Any key pressed". So, something like this might work;
If !GetKeyState(0)==True then
    Do Something
End If

Or
If GetKeyState(0)==False then
    Do Something
End If


text:
Q: Google API PHP client with Composer I made a WP plugin which depends on the Youtube API. So, to do it well, I use Google API PHP client.
My issue is quite simple: the Google API PHP client is huge (more than 12 000 files), including clients for all Google services, when I just need to use Youtube service. So I'm not confortable committing all those files to the WP plugins repo when most of them are useless in my case.
So, right now, my composer.json looks like this:
{
    "require": {
        "google/apiclient": "^2.0"
    }
}

Any way to use only the Youtube API client (using composer if it's possible)?

A: Unfortunately, I don't think this is possible without manually including the relevant files in your project (which is a really bad idea).
The reason why its impossible, is because Google places all service APIs for the PHP library in a single GitHub repository found here:
https://github.com/google/google-api-php-client-services
If Google does split them into multiple repositories, then it could be possible to include a single repo.
For now, though, all services are under one composer project and one repo. Maybe its worth making a GitHub issue to ask Google about this?

A: This is not for the feign of heart but it is doable.

*

*Go to this branch of the repo https://github.com/google/google-api-php-client/tree/v1-master

*Grab the full src/Google directory you will need all of that.

*In the src/Google/Service directory is the stuff for all the different APIs.  Remove everything except for YouTube.

*cross your fingers it should work.

This wont remove all 12000 files but it should give you just what you absolutely need.  I used to do this but its been a few years.


text:
Q: Keras - Add attention mechanism to an LSTM model With the following code:
model = Sequential()

num_features = data.shape[2]
num_samples = data.shape[1]

model.add(
    LSTM(16, batch_input_shape=(None, num_samples, num_features), return_sequences=True, activation='tanh'))
model.add(PReLU())
model.add(Dropout(0.5))
model.add(LSTM(8, return_sequences=True, activation='tanh'))
model.add(Dropout(0.1))
model.add(PReLU())
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))

I'm trying to understand how can I add an attention mechanism before the first LSTM layer. I've found the following GitHub: keras-attention-mechanism by Philippe Rémy but couldn't figure out how exactly to use it with my code.
I would like to visualize the attention mechanism and see what are the features that the model focus on.
Any help would be appreciated, especially a code modification. Thanks :)

A: You may find an example of how to use a LSTM with an activation mechanism in Keras in this gist
https://gist.github.com/mbollmann/ccc735366221e4dba9f89d2aab86da1e
And in the following answer on SO:
How to add an attention mechanism in keras?
And to visualize your activations you can use the following repository https://github.com/philipperemy/keras-activations

A: There are at least half a dozen major flavours of attention, most of them are minor variations over the first Attention model that came out - Bahdanau et al in 2014. Each of this flavour can be implemented in multiple ways, so this can be confusing to someone who wants to add a simple attention layer to her/his model. Looking at your model, I would recommend adding an attention layer after your second LSTM layer. This can be a custom attention layer based on Bahdanau.
An implementation is shared here:
Create an LSTM layer with Attention in Keras for multi-label text classification neural network
You could then use the 'context' returned by this layer to(better) predict whatever you want to predict. So basically your subsequent layer (the Dense sigmoid one) would use this context to predict more accurately.
The attention weights too are returned by the above layer. These can be routed to a simple display.
For more specific details, please refer https://towardsdatascience.com/create-your-own-custom-attention-layer-understand-all-flavours-2201b5e8be9e


text:
Q: Can a string pointer in C be directly assigned a string literal? The following program works fine, and I'm surprised why :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void xyz(char **value)
{
        // *value = strdup("abc");
        *value = "abc"; // <-- ??????????
}

int main(void)
{
        char *s1;

        xyz(&s1);

        printf("s1 : %s \n", s1);
}

Output :
s1 : abc

My understanding was that I have to use strdup() function to allocate memory for a string in C for which I have not allocated memory. But in this case the program seems to be working fine by just assigning string value using " ", can anyone please explain ?

A: String literals don't exist in the ether. They reside in your programs memory and have an address.
Consequently you can assign that address to pointers. The behavior of your program is well defined, and nothing bad will happen, so long as you don't attempt to modify a literal through a pointer.
For that reason, it's best to make the compiler work for you by being const correct. Prefer to mark the pointee type as const whenever possible, and your compiler will object to modification attempts.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void xyz(char const **value)
{
        *value = "abc";
}

int main(void)
{
        char const *s1;

        xyz(&s1);

        printf("s1 : %s \n", s1);
        s1[0] = 'a'; << Error on this line
}

A: Your program works fine because string literal "abc" are character arrays , and what actually happens while assigning a string literal to a pointer is , the compiler first creates a character array and then return the address of the first element of the array just like when we call the name of any other array.
so in your program you have passed address of a char pointer to the function xyz
and
*value = "abc";

for this statement , compiler first creates a character array in the memory and then returns its address which in turn gets stored in the char pointer.It is worth knowing that the compiler creates the char array in read only memory.Thus , the address returned refers to a const char array.Any attempt to modify its value will return it compile-time error.

A: You can define a string in C with char *str = "some string";, str is a pointer which points to the location of the first letter in a string.


text:
Q: Downsampling a video with avconv / ffmpeg I know really little about encoding and using avconv / ffmpeg. I am trying to downsample a video as follows:
avconv -i blah_in.avi -s 640x360 -pass 1 blah.avi
avconv -i blah_in.avi -s 640x360 -pass 2 blah.avi

I am aware that this is very simplistic, yet I can't figure out what the problem is. Here is the error message from pass 1:
avconv version 0.8.3-4:0.8.3-0ubuntu0.12.04.1, Copyright (c) 2000-2012 the Libav developers
  built on Jun 12 2012 16:37:58 with gcc 4.6.3
[avi @ 0x9fdd240] non-interleaved AVI
Input #0, avi, from 'blah_in.avi':
  Metadata:
    encoder         : MEncoder svn r34540 (Ubuntu), built with gcc-4.6
  Duration: 01:21:59.24, start: 0.000000, bitrate: 8996 kb/s
    Stream #0.0: Video: mpeg4 (Advanced Simple Profile), yuv420p, 1920x1080 [PAR 1:1 DAR 16:9], 23.98 tbr, 23.98 tbn, 23.98 tbc
    Stream #0.1: Audio: mp3, 44100 Hz, stereo, s16, 128 kb/s
File 'blah.avi' already exists. Overwrite ? [y/N] y
[buffer @ 0x9fe1e00] w:1920 h:1080 pixfmt:yuv420p
[scale @ 0x9fdcfa0] w:1920 h:1080 fmt:yuv420p -> w:640 h:360 fmt:yuv420p flags:0x4
Incompatible sample format 's16' for codec 'ac3', auto-selecting format 'flt'
[ac3 @ 0x9fdc740] invalid bit rate
Output #0, avi, to 'blah.avi':
  Metadata:
    encoder         : MEncoder svn r34540 (Ubuntu), built with gcc-4.6
    Stream #0.0: Video: mpeg4, yuv420p, 640x360 [PAR 1:1 DAR 16:9], q=2-31, pass 1, 200 kb/s, 90k tbn, 23.98 tbc
    Stream #0.1: Audio: ac3, 44100 Hz, stereo, flt, 200 kb/s
Stream mapping:
  Stream #0:0 -> #0:0 (mpeg4 -> mpeg4)
  Stream #0:1 -> #0:1 (mp3 -> ac3)
Error while opening encoder for output stream #0:1 - maybe incorrect parameters such as bit_rate, rate, width or height

I have tried a number of things, but either they end up with a similar error message, or the quality is extremely poor; not so much due to low resolution, but full of compression artifacts.
Now, what I would like to achieve is the same resolution / encoding as the following avi file, which plays fine on my kids video device:
Stream #0.0: Video: mpeg4 (Advanced Simple Profile), yuv420p, 624x352 [PAR 1:1 DAR 39:22], 25 fps, 25 tbr, 25 tbn, 25 tbc
Stream #0.1: Audio: mp3, 48000 Hz, stereo, s16, 128 kb/s

A: The final line in the output log is too generic — you'll have to look up further. The error is this:
[ac3 @ 0x9fdc740] invalid bit rate

The problem is that for some reason avconv wants to encode your MP3 audio to AC3. In fact, when you're only resizing video, you can leave the audio bitstream alone.

Note that resizing and re-encoding will lower your quality drastically. So, unless you really need to, don't do it. Your video will suffer from generation loss.
If you can, avoid using MPEG-4 Part 2 codecs (Xvid, or the libavcodec-native mpeg4), and use MPEG-4 Part 10 / H.264 codecs instead (e.g., x264). Since H.264 isn't properly supported in AVI containers, we'll use MP4 instead, which should be your container of choice instead of AVI most of the time.
ffmpeg -i in.avi -c:a copy -c:v libx264 -crf 23 -s:v 640x360 output.mp4

This will copy the audio stream (-c:a copy), encode the video to x264 (-c:v libx264) with a constant quality of 23 (-crf). Use a lower value here for better quality (with sane values from 18–28). The size will be changed with -s:v.
I'm using FFmpeg synonymously with Libav here, since the syntax should be the same. I would however recommend you to ditch the default Libav version that ships with Ubuntu and compile FFmpeg from source or use a recent Linux static build.

A: The video bitrate specified is very low: 200kpbs. Try this command
ffmpeg -i input_video -b 800 -s 640x360 -vcodec xvid -acodec copy output_video

As suggested in comments if the device supports h.264 it would be a better choice.


text:
Q: Python PyQt4 QTableWidget CellWidget Roll Column values I have a QTablWidget with the following properties:
        mytable.setEditTriggers(QtGui.QTableWidget.NoEditTriggers)
        mytable.setSelectionBehavior(QtGui.QTableWidget.SelectRows)
        mytable.setSelectionMode(QtGui.QTableWidget.SingleSelection)
        mytable.horizontalHeader().setStretchLastSection(True)
        mytable.verticalHeader().hide()

On each row of my table, I have a QPushButton set at a CellWidget like this:

Is there any way to get the Row number of table that the QPushButton is in once user press on any of the button?
For example, if user click on the QPushButton on the row 2 of the table, it returns a value of 2.
EDIT 2
According to one of the answer, i have updated the code to this: but  I am still not getting anything. Where have i gone wrong? I tried to print out the output of self.table.itemAt(button.pos()) and i am getting None .
from PyQt4 import QtGui,QtCore
import sys

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self,parent)
        self.table = QtGui.QTableWidget()
        self.table.setColumnCount(3)
        self.setCentralWidget(self.table)
        data1 = ['orange','apple','banana','lemon']
        data2 = ['3','4','5.5','2']

        self.table.setRowCount(4)

        for i in range(4):
            item1 = QtGui.QTableWidgetItem(data1[i])
            self.table.setItem(i,0,item1)
            item2 = QtGui.QTableWidgetItem(data2[i])
            self.table.setItem(i,1,item2)
            self.button = QtGui.QPushButton('TEST')
            self.button.clicked.connect(self.handleButtonClicked)
            self.table.setCellWidget(i,2,self.button)

    def handleButtonClicked(self):
        button = self.sender()
        item = self.table.itemAt(button.pos())
        if item is not None:
            print (item.row(),item.column())

def Main():
    app = QtGui.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    app.exec_()

if __name__ == '__main__':
    Main()

A: If you can get a reference to the button that was clicked, then QTableView.indexAt can be used to get the corresponding index:
    button.clicked.connect(self.handleButtonClicked)
    ...

    def handleButtonClicked(self):
        button = QtGui.qApp.focusWidget()
        # or button = self.sender()
        index = self.table.indexAt(button.pos())
        if index.isValid():
            print(index.row(), index.column())


text:
Q: External Yeti Michrophone not detected on Ubuntu 18.04 I have external Usb Microphone by Yeti. With every Ubuntu upgrade it takes me hours to set it up. However, after upgrade to 18.04 the microphone is not detected at all.
The result of dmesg is:
[ 1723.642721] usb 3-1: new full-speed USB device number 26 using xhci_hcd
[ 1723.770713] usb 3-1: device descriptor read/64, error -71
[ 1724.006692] usb 3-1: device descriptor read/64, error -71
[ 1724.242693] usb 3-1: new full-speed USB device number 27 using xhci_hcd
[ 1724.370702] usb 3-1: device descriptor read/64, error -71
[ 1724.606727] usb 3-1: device descriptor read/64, error -71
[ 1724.714717] usb usb3-port1: attempt power cycle
[ 1725.366737] usb 3-1: new full-speed USB device number 28 using xhci_hcd
[ 1725.366894] usb 3-1: Device not responding to setup address.
[ 1725.574909] usb 3-1: Device not responding to setup address.
[ 1725.782715] usb 3-1: device not accepting address 28, error -71
[ 1725.910731] usb 3-1: new full-speed USB device number 29 using xhci_hcd
[ 1725.910884] usb 3-1: Device not responding to setup address.
[ 1726.118876] usb 3-1: Device not responding to setup address.
[ 1726.326694] usb 3-1: device not accepting address 29, error -71
[ 1726.326786] usb usb3-port1: unable to enumerate USB device

Any ideas how it can be solved are welcome!

A: lo,
Had some troubles too with my external microphone (not USB but with micro in-plug), this one:
Philips SBC MM300
Looked around on the Net and wrote a small bash script with my modest knowledge (see further on).
The number '1' loads microphone module and the number '0' resets sound.
As mentioned in the script, 'Pavucontrol', should be installed but that should be alright on Ubuntu 18.04 (I use Linux Mint 19 Xfce myself).
Give the script Rights Everyone in all cases (maybe easiest by rightclicking the script).
To reload it, the name of the script file has to be the exact name as the file name at the bottom of the script. In the example: 'Microphonesound_On-Off.sh'.
Put the script somewhere and possibly shortcut it to your pc desktop (easy with PCman FM file explorer). Start by clicking or rightclicking and 'Open in terminal'.
If you still experience trouble after activating the micro sound module, go to your volume settings and check under 'Configuration' tab if 'Analog Stereo Duplex' is selected under 'Built-in Audio'.
Test your Volume settings in general after having activated the microphone sound with the script.
Different systems, different configurations. But it gives an idea.
Finally the script (copy all the text until 'Microphonesound_On-Off.sh' and save as 'Microphonesound_On-Off.sh'):

#!/bin/bash

clear

echo "MICROPHONE SOUND ON OR OFF"

# Requires Pavucontrol

echo

echo "Sound On = 1, Sound Off = 0 (zero):"

echo

read INPUT

if [ $INPUT == '1' ] # space before/after brackets!

then

echo

sleep 2 # required to load module

pactl load-module module-loopback latency_msec=10 # microphone sound On

echo "Micro sound On!"

elif [ $INPUT == '0' ]

then

echo

pulseaudio -k # reset all sound to default

echo "Micro sound Off!"

else

echo

echo "Wrong Input."
echo "Type 1 or 0."

fi

echo

echo "Enter = Reload"

echo

read

./Microphonesound_On-Off.sh


text:
Q: Choose Random xml entry once per load with jquery I am trying to choose from a number of entries in an xml file and show them on a webpage. I can't seem to figure out what I am doing wrong... does anyone have suggestions?
Thank you for your time :-)

Above looks like it 'should' work but it doesn't actually select an random entry...

A: I think what you're after is something like this:
$(xml_list).find('entry').each(function(i) {
  var xml_id = $(this).attr('id');
  if(i != numRand) return; //keep going if this wasn't the right ID
  var xml_name = $(this).find('name').text(),
      xml_link = $(this).find('link').text(),
      xml_url  = $(this).find('url').text();

  var div = $('
' { 'id': xml_id, 'class': 'ad' });
  div.append($('', { 'href': xml_url, 'title': xml_name }));
  div.append($('', {'class': 'ad', 'src': xml_link }));
  div.appendTo('div.adviewer');
}); // end each loop

There are currently a few syntax errors, mainly with this:
if(id == numRand).appendTo(div +' class="adviewer"');

.appendTo() is called on a jQuery object to append to something, the selector for
 would look like div.adviewer, like I have above.
The rest of the changes center around switching to the $(html, props) DOM element creation method to property handle encoding and such (if you have a quote in anything for example).  Also id is undefined in your question/code...I'm assuming you meant index here, if you didn't then change the if(i != numRand) to be if(xml_id == numRand) instead, that'll compare to the ID from the XML.


text:
Q: Joomla - Determining whether logged-in user is an Admin I am having tons of fun working on a big project that was, for reasons hard to justify, based on Joomla! (which I don't mean to criticise, Joomla! is great, just not for the task I am faced with currently) and when I googled for a way of determining whether the currently logged-in user is an Admin, I found a post that quite boldly recommends using the following code:
$user =& JFactory::getUser();
if($user->usertype == "Super Administrator" || $user->usertype == "Administrator"){ ... }

To me, this looks like a rather strange way of checking for Admin users. I would appreciate a $user->isAdmin() method to do this rather than a couple of hard-coded strings.
I fail to find a more elegant solution to checking for admin users within the Joomla! framework. Can anyone help?

A: Actually, as the Access levels are hard coded into the database in Joomla! 1.5, the only way this string comparison could fail is when someone deliberately hacked new groups into it. Strings can be changed in the .ini-Files (so that non-english installations still use the english words in the database - this is not true for other tables like the names of plugins or components.)
You could get the group id via JFactory::getACL(), and then $acl->getGroupsByUser($userid, false) (see docs), but assuming that a greater id means greater privileges as well, seems a bit hacky, too (though true for a standard installation).
Other than that, you could take over a Joomla! capability: define more explicitly, what a "admin user" is: someone who can install new software? who can change the system's configuration? Just make a reasonable assumption, something related to what you want him to do as a admin user, use it in a authorize()-Call (see docs), and maybe document it in your interface.
The only clean solution (that I know of) would be to define new entries for the ACL-authorize-lookuptable (currently implemented in php only, not SQL). This is the only way to ensure that it will be Joomla! 1.6-proof, where custom user groups will be possible (and so the admin user can choose to give this authorization to a user group or not). For example:
$acl =& JFactory::getACL();
$acl->addACL('{com_nameOfExtension}', '{action}', 'users', 'super administrator');
$acl->addACL('{com_nameOfExtension}', '{action}', 'users', 'administrator');

And there we have them again, hard-coded groupnames. Well.

A: Peter,
I concur on the joomla sentiments, we use .net/php here as well and have a few projects that were started on joomla for some unknown reason !!
amnyway, another finer grained approach may be to examine the actual rights that the user has, rather than them being suoper admin etc. you can get to this info along the following lines:
    $user =& JFactory::getUser();

    if ($user->authorize('com_content', 'edit', 'content', 'all')) {
            echo "
You may edit all content.
";
    } else {
            echo "
You may not edit all content.
";
    }

    if ($user->authorize('com_content', 'publish', 'content', 'own')) {
            echo "
You may publish your own content.
";
    } else {
            echo "
You may not publish your own content.
";
    }

i know it's still hardcoded but at least it's user specific, rather than priviledge specific. this approach does however allow you to target specific 'component' related priviledges, so might be useful for you.
I'll track the replies to see if there's a 'proper' answer as it definately is an omission.
jim

A: The following could be a hack on Joomla. I tried it and got worked.
Take the case of sessions
$_SESSION[__default][user]->usertype;

This will give the type of user logged in you can use this in any conditional statements

A: You can check 'assigned user groups' of the logged in user using getUser() function.
$user =& JFactory::getUser();

$assigned_usergroups = $user->groups; // Array of assigned User Group

    if (in_array(8, $assigned_usergroups)) {
        echo "Super Admin";
    }

    else if (in_array(7, $assigned_usergroups)) {
        echo "Admin";
    }

    else {
        echo "Other"; //Any of Guest/Public/Others
    }

You can see the following snapshot of the Joomla's predefined IDs for each User Group in the Database:
Snapshot here

A: If ur joomla administrator username is admin then u can use below code aspeter described before
$user =& JFactory::getUser();
if($user->usertype == "Super Administrator" && $user->username == "admin")
{
  //... do what ever
}


text:
Q: why "Completed 406 Not Acceptable" has gone after removing respond_to? when I used $.ajax() to submit the form's content with the following respond_to block:
respond_to do
  render :json => { :url => question_path(resource, :recent => :true),
          :uploadPath => question_path(@question, :format => "json"),
          :editPath => edit_question_path(@question),
          :exitPath => question_path(resource)
  }
end

I got a error:
Completed 406 Not Acceptable in 124690.7ms (Views: 0.4ms | ActiveRecord: 16.7ms | Sphinx: 0.0ms)

After I removed respond_to, as the above code is changed into:
  render :json => { :url => question_path(resource, :recent => :true),
          :uploadPath => question_path(@question, :format => "json"),
          :editPath => edit_question_path(@question),
          :exitPath => question_path(resource)
  }

The error has gone, why this happens? what things I miss? Thank you!

A: respond_to is used when you want to produce different responses for the same controller action. For example perhaps you want to render HTML for browsers but JSON for an API client. You list all the responses you can generate (and how they should be generated) and rails picks the one that matches the request:
respond_to do |format|
   format.html { ... }
   format.json { ... }
end

In the example above rails would know how to generate HTML and JSON responses but if a request came in requesting an XML response then rails would produce a 406 error (not acceptable ) because it doesn't know how to produce such a response.
In your code snippet you are calling respond_to so you are telling rails to only use the response formats given by the block but you are not defining any response formats (you're not using the object yielded to the block), therefore rails produces a 406.
When you remove the call to respond_to Rails no longer worries about trying to pick the correct response format and just uses your call to render (and would do so no matter what format the request was asking for).
If you wanted to use respond_to you would do
respond_to do |format|
  format.json { render :json => { ... }}
end

when doing so you do need to ensure that the request is requesting json - if rails though it was requesting HTML then you'd be back to your 406 error.  You can use jQuery's dataType option for this or use an extension of .json (ie make your request to /foo/bar.json)


text:
Q: Assigning boost::iterator_range to singular range I'm using Boost.Range to pass around some data and a container class for this data. The data is loaded in a different thread and may in some cases not be ready yet. In this case the container is initialized with the default iterator_range, hence containing singular iterators. I'm doing assignments and copying of the data containers (hence the iterator_ranges). However, the iterator_range copy constructor calls begin() and end() which will assert when the original is singular. Therefor, it is not possible to copy an empty data container.
Is there any way to avoid this limitation?
Why is this limitation been implemented? The following works just fine, shouldn't ranges behave similarly?
typedef std::vector<int>::iterator iterator;
iterator it; // Singular
iterator it2 = it; // Works

boost::iterator_range<iterator> range; // Singular
boost::iterator_range<iterator> range2 = range; // Asserts in debug, but why?

A: If by "works", you mean "it does not blow up with my current compiler version and invocation options", then yes, assigning a singular iterator might "work".
Actually, the code
typedef std::vector<int>::iterator iterator;
iterator it; // Singular
iterator it2 = it; // Works

results in undefined behaviour, so you are up to the whims of your compiler for what may happen.
The C++ standard has this to say about it (section [lib.iterator.requirements]/5):

[...] Results of most expressions are undefined for singular values; the only exception is an assignment of a non-singular value to an iterator that holds a singular value. In this case the singular value is overwritten the same way as any other value. Dereferenceable and past-the-end values are always non-singular.

So, in the end ranges do work similar to single iterators. It just doesn't work the way you would like.
I think the best way is to use an empty range (explicitly constructed with to non-singular iterators) when the data is not yet ready, instead of a singular range.


text:
Q: How to enable use of cursors to navigate commands in Linux Shell I'm running a Docker container on Windows to enable me to work with Linux for some projects where that's required.  When using the CLI I'm unable to use the cursor keys to navigate the commands / the command history.  I'd expect pressing the up/down arrows to navigate through the previously run commands, and the left/right arrows to allow me to move the cursor to a part of the currently selected command to allow me to edit from that point.  Instead when I press the cursor keys I see the characters output to the console (i.e. up, down, left, right resolving to ^[[A, ^[[B, ^[[C, and ^[[D respectively).
Is there an option / install I'm missing to enable the expected behaviour?
I've seen information about set -o; but I have no history entry:
# set -o | grep history
# set -o
Current option settings
errexit         off
noglob          off
ignoreeof       off
interactive     on
monitor         on
noexec          off
stdin           on
xtrace          off
verbose         off
vi              off
emacs           off
noclobber       off
allexport       off
notify          off
nounset         off
priv            off
nolog           off
debug           off
# set -o history
/bin/sh: 21: set: Illegal option -o history

The version of bash used is 4.4.20:
# bash --version
GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

A: Per SteelDriver's comment, I'd misunderstood which shell I was in, as running bash --version had given output, I'd assumed I was within a bash shell.  In fact, I'd just called the exe with a command line parameter.  I'd been using /bin/sh.
The solution to enabling the expected cursor behavior was to switch to a shell which supported it; i.e. bash.  To do that; I just had to run the command: bash.
Per @StefanSkoglund's comment, to change things permanently, run chsh -s /bin/bash.
You can also list valid login shells via: cat /etc/shells.
You can see each users' default shell via: cat /etc/passwd; or better; getent passwd.


text:
Q: Contains does not show proper info I keep trying to make this piece of code work.
I know it is very simple but for some reason it does not work, neither with matches or contains. It always go to "It does not work"
  def var="pst-dhn-publisher1.prg-dc.dada.com"

            if (var.contains("pen|pst|uat1|uat2|uat3|test")) {
             println "works"
            }
            else {

                  println "It does not work"
            }

Why is that?

A: Contains is whole string match
is this what u are looking for ?
def var="pst-dhn-publisher1.prg-dc.dada.com"

            if (var =~ ("com|pst|uat1|uat2|uat3|test")) {
               println "works"
            }
            else {

                  println "It does not work"
            }

A: I think you need to use matches, like this:
def var="pst-dhn-publisher1.prg-dc.dada.com"
if (var.matches(".*pen.*|.*pst.*|.*uat1.*|.*uat2.*|.*uat3.*|.*test.*"))
{
   println "works"
}
else
{
   println "It does not work"
}


text:
Q: replace  tag data with empty javascript Hi I am having string contents <xml>.....</xml>
I want to replace xml tag with its inner content with the empty string.
How can I achieve it by regular expression or javascript.
My Code is  -
var tempHtml =  "Test Data Test Data
Test data Test Data data ata
data

Testerbr>
 here data";

ht = ht.replace("<xml>(.+?)<\/xml>/gi", "");

A: The regex just needed to be modified, alongside with using the right variable name:
var tempHtml =  "Test Data Test Data
Test data Test Data data ata
data

Testerbr>
 here data";
tempHtml = tempHtml.replace(/<xml>(.+?)<\/xml>/gi, "");
// Now tempHtml = "Test Data Test Data
Test data Test Data data ata
data

Testerbr>
 here data"


text:
Q: Versioning software without having to edit lots of config files We have a project that uses a couple of assemblies.
Is there an easy way of handling the version of all those assemblies at once?
We have a version like
major.minor.patch.revision

Most of the times on a release, just the minor version gets a change.
A critical part is the revision which is the fileversion in the repository.
At the moment I think this makes impossible to use one AssemblyInfo.cs for all assemblies.
How can I avoid to change the AssemblyInfo.cs of all those assemblies?

A: If you want all of the assemblies to have the same version, you can make a single .cs file for the versioning in one of your libraries, and add it as a link to the other projects.
This will cause the single file to be part of all three assemblies, and keep the version constant across them all.

A: I've found that this is easiest to do when you're going to create your build artifacts. From a process standpoint, you would:
1. Tag/Label Source
2. Get by Tag/Label
3. Edit AssemblyInfo files
4. Build, Test, Etc
5. Capture Build Artifact
This is all pretty easy to do in BuildMaster(disclaimer: I work for Inedo as a set of actions. In this case it'd be just using the Write Assembly Versions action after doing a Get Latest action.
You can see this pattern used a lot in the specifics libraries. When we build ProGet, for example, you'll notice that Write Assembly Versions shortly after comparing the directories for changings, and right before running msbuild.


text:
Q: How to improve this animation? I have three divs on the same line. You can check the example here: http://yoyo.ro/abw just scroll to the bottom of the page to the three boxes: Made to Measure, Instagram and Video Tracking.
When I click the left one, I want the other two to slide to the right and some text to appear. I tried to do it, but it seems that I complicated it so much and it isn't even smooth.
function hideTest(){
         $(".instagram").addClass("slideout");
         $(".videotracking").addClass("slideout");
         $(".instagram").animate({left:"150%"},500);
         $(".videotracking").animate({left:"150%"},500);
         }
function showTest(){
         $(".instagram").animate({left:"33.3%"},500);
         $(".videotracking").animate({left:"66.6%"},500);
         $(".instagram").removeClass("slideout");
         $(".videotracking").removeClass("slideout");
         }

     $(".madetomeasure").on('click',function(){
         var testwidth = $(this).find(".vc_btn3-container").width();
         $(this).find(".vc_btn3-container").css("width", testwidth);

     if(!$(this).hasClass("openslide")){
         hideTest();
         $(".madetomeasure").addClass("openslide");
         $(this).find(".txtbox").animate({left:0},500);}

      else {
            $(this).find(".txtbox").animate({left:"-100%"},500);
            $(".madetomeasure").removeClass("openslide");
            showTest();
             }

         });

here is the css relevant to the JS
   .txtbox{
-webkit-transition: all 0.3s ease-out;
        -moz-transition: all 0.3s ease-out;
        -o-transition: all 0.3s ease-out;
        transition: all 0.3s ease-out;
        width: 66.5%;
        display:none;
        left:-100%;
        padding:0px 15px;
        float:left;
        position:relative;}
   .instagram, .videotracking{position:static;}
   .instagram {left:33.3%;}
   .videotracking{left:66.5%;}
   .instagram.slideout{position:absolute;}
   .videotracking.slideout{position:absolute;}
   .madetomeasure .button{
     z-index:1;
     height:300px;
     background: url(http://yoyo.ro/abw/wp-content/uploads/2016/02/instagram.jpg) 100% 30% !important;
     border: none !important;}
   .madetomeasure.openslide {width:100%;}
   .madetomeasure.openslide .wpb_wrapper {display:flex;}
   .madetomeasure.openslide .txtbox {display:block;}

Thank you so much for the patience... :) I really appreciate it

A: As far as I know, your problem of smoothness is because:

*

*jQuery change the inline styling of the animated element per frame. That is a lot of work and you can actually see the action if you inspect your element when it's animating.

*CSS does poorly on animating left and right. There are many articles about this but here's one if you don't want to search: https://css-tricks.com/tale-of-animation-performance/

The Solution
Fiddle: https://jsfiddle.net/kv5twc64/1/
The solution is very common, and is used by many CSS libraries, a trick using .active, CSS animation and some JS.
Here I used the transition property for .card:
.card {
  display:inline-block;
  float:left;
  max-width:33.333%;
  position:relative;
  cursor: pointer;
  transition: 0.5s all ease-out;
}

If you don't know, transition will create a tweening effect when the elements' property has changed.
And here is the trick: By using ~ selecting the siblings in CSS and the transform property:
.card.active .desc {
  transform: translateX(0);
}

.card.active ~.card {
  transform: translateX(66.666vw);
}

There are several upsides on using CSS in this case:

*

*You can simplify your JS. The JS became:
$(function(){
    $(".card").eq(0).click(function(){
    $(this).toggleClass("active");
  })
})

*You can improve webpage performance

*You can have more choices on (simple) easing functions in CSS (jQuery only offers "swing" by default). Check this out: http://easings.net You can do something like this:
transition: all 600ms cubic-bezier(0.77, 0, 0.175, 1);

Hope this can help. But the lesson here is: Use CSS rather than JS when you can!

P.S. 66.666vw means 2/3 the width of the viewport width.


text:
Q: Save image in the device gallery using Cordova Hello I should save images on the device when the user clicks the download button.
I'm using the cordova file transfer plugin, but I can not save images in the device gallery.
$("#downloadFile").click(function()
{
    var fileTransfer = new FileTransfer();
    var uri = encodeURI("www.mysite.com/image.jpg");
    var fileURL =  cordova.file.????;

    fileTransfer.download(

    uri, fileURL, function(entry)
    {
        alert("download complete: " + entry.toURL());
    },
    function(error)
    {
        alert("download error source " + error.source);
        alert("download error target " + error.target);
        alert("download error code" + error.code);
    },
    false,
    {
        headers:
        {
            "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
        }
    });
});

Are there any other ways to save an image using cordova?
Thanks, ciao

A: https://www.npmjs.com/package/cordova-plugin-save-image
You should use this plugin
function(entry){
window.cordova.plugins.imagesaver.saveImageToGallery(uri, function(success){}, function(error){});
}

nativePathToJpegImage is uri.


text:
Q: Using custom commands in preamble I have a the following command in a resume.cls file
\newcommand{\name}[1][]{\newcommand{\@name}{#1}}

I try to use it in my tex file with
\documentclass{resume}
\name{My Name}
% use \@name in fancyhdr
\begin{document}
% body
\end{document}

But I get
LaTeX Error: Missing \begin{document}

l.5 \name{M
            y Name}

Can you not issue custom commands in the preamble?

A: \newcommand{\name}[1][]{\newcommand{\@name}{#1}}

defines \name to have an optional argument so the syntax for use is
\name[My Name]

with square brackets.


text:
Q: Tsung setdynvars not substituting value I have the following script and for some reason the value is not being substituted with the value 1.
<sessions>
<session probability="100" name="connect_chat" type="ts_websocket">
<setdynvars sourcetype="eval" code="fun({Pid,DynVars}) ->
                  1 end.">
        <var name="cun" />
    </setdynvars>
 <request subst="true">
    <websocket type="connect" path="/uname=SampleUser%%_cun%%"/>
  </request>
</session>

In fact the request to the uname at the server side is being received as follows:
SampleUser%_cun%
Any ideas of what can be the source of the problem?

A: There seem to be some bug in the path substitution process. This have solved my problem.
http://lists.process-one.net/pipermail/tsung-users/2013-July/002532.html