Q:

Python CountVectorizer: presence of term in documents

I am doing LDA analysis with Python.
Is there an out of the box way of getting how many texts of my corpus (which is a list of text strings) a word (Edit: a term of n words) is present?
The answer here by @titipata gives the word frequency: How to extract word frequency from document-term matrix?
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
texts = ['hey you', 'you ah ah ah']
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
freq = np.ravel(X.sum(axis=0))

import operator
# get vocabulary keys, sorted by value
vocab = [v[0] for v in sorted(vectorizer.vocabulary_.items(),     key=operator.itemgetter(1))]
fdist = dict(zip(vocab, freq)) # return same format as nltk

The word frequency is here:
fdist
{u'ah': 3, u'you': 2, u'hey': 1}

but I want
presence
{u'ah': 1, u'you': 2, u'hey': 1}

Edit: this should also work for terms of N-words, which you can define
I can calculate what I want as below, but is there a faster way from CountVectorizer?
presence={}
for w in vocab:
    pres=0
    for t in texts:
        pres+=w in set(t.split())
    presence[w]=pres

Edit: what I just wrote for presence does not work for terms of N words. This works but is slow:
counter = Counter()
for t in texts:
    for term in vectorizer.get_feature_names():
        counter.update({term: term in t})

A:

If your corpus is not too large, this should work nicely and quite fast. Also, it relies on python in-builts. See the documentation for Counter.
from collections import Counter

corpus = ['hey you', 'you ah ah ah']
sents = []

for sent in corpus:
    sents.extend(list(set(sent.split())))   # Use set et to ensure single count

Counter(sents)

Returns:
Counter({'ah': 1, 'hey': 1, 'you': 2})


Q:

How do I declare namespace functions correctly

I thought I followed the logic of the other threads on this, but
namespace Geometry {

class Vector2D {
    public:
        Vector2D(float x_, float y_) : x(x_), y(y_) {}
        float x;
        float y;
}

Vector2D operator+(const Vector2D &lhs, const Vector2D &rhs) {
    return Vector2D(lhs.x + rhs.x, lhs.y + rhs.y);
}

}

is not compiling, and I get the error
error: no matching constructor for initialization of 'class Vector2D'
Vector2D operator+(const Vector2D &lhs, const Vector2D &rhs) {

error: expected ';' after top level declarator
Vector2D operator+(const Vector2D &lhs, const Vector2D &rhs) {

so the compiler seems to think my operator overload on binary '+' is a delcaration of a variable?

A:

Ah, you're missing a semicolon!


Q:

What is an “invited submission” to a journal?

The website of the journal Philosophy and Phenomenological Research says:

This site only accepts invited submissions.

In general, what is an invited submission? Is this how special issues of journals are published? Why would a journal invite submissions? How does publishing as an invited submission look compared to a normal submission?

A:

An invited submission is as the name implies, something which the editors of the journal invited. You have probably seen this kind of invitation email - "we would like to invite you to write something on [this topic]. Are you interested?"
It may or may not be related to special issues. Special issues are entire issues formed around that single topic (or conference). If the journal is inviting for a special issue, it will say so in the invitation - "we are publishing this special issue and you're an expert on the topic, so we would like to invite you ...". However it's also possible to be invited for regular issues.
A journal invites submissions for several reasons:

If the journal can get big names to write for them, it raises the profile of the journal as well as (hopefully) generates citations. Other researchers are more likely to submit if famous researchers also submit to the journal. This is the most important reason.
The journal may lack papers. The big journals may receive more papers than they can publish, but there're also a lot of small journals that struggle to fill their issues.
The journal may want to expand. This could be its author pool (invite people who've never published in the journal before), its author country pool (invite people from countries who rarely publish in the journal), or its issue count (increase in issue count is a reason to charge higher subscription prices).

Finally, in principle, invited submissions are more prestigious than regular submissions. That's because the author can safely say that someone out there thinks they're an expert in the field. It's especially good if the invitation comes from a famous researcher. However: many poor-quality journals will also resort to invitations to solicit papers. Their aim is merely to get papers, and they don't really care who is writing or even what topic the paper is on. You will have to use your judgment. In my experience, a personalized email coming from an established researcher in your field is the best kind of invitation.


Q:

adding event listener to audio element doesn't work

i have made a simple music player and there is 2 events for it one for updating elapsed time and another for durationchange...elapsed time's function works fine but total time function doesn't...i have looked up in http://www.w3schools.com/tags/ref_av_dom.asp and durationchange is a standard event but i don't get it why it doesn't work. i also thought maybe the reason is that script is defined before label elements but moving scripts to the end of file didn't worked either.
here is my code:
<!DOCType HTML>

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

<form action="/" id="player">

    Imaginaerum

    Nightwish

        --:--
        /--:--
</form>

A:

In your case durationchange event fired before window.onload
        var audio;
        window.onload = function () {
         audio= document.createElement("audio");
        audio.id = "audio1"
        audio.src = "Music.mp3";
        audio.autoplay = true;
            audio.addEventListener('timeupdate', UpdateTheTime, false);
            audio.addEventListener('durationchange', SetTotal, false);

        }

        function UpdateTheTime() {
               var sec = audio.currentTime;
               var min = Math.floor(sec / 60);
               sec = Math.floor(sec % 60);
               if (sec.toString().length < 2) sec = "0" + sec;
               if (min.toString().length < 2) min = "0" + min;
               document.getElementById('Elapsed').innerHTML = min + ":" + sec;

        }

        function SetTotal() {
            var sec = audio.duration;
            var min = Math.floor(sec / 60);
            sec = Math.floor(sec % 60);
            if (sec.toString().length < 2) sec = "0" + sec;
            if (min.toString().length < 2) min = "0" + min;
            document.getElementById('Total').innerHTML = "/ " + min + " : " + sec;
        }

Example http://jsfiddle.net/rU7SU/


Q:

How can i populate a combobox depending on the selected value of a different combobox?

All I want to do is send the value of the option selected from slct1 in my cb_insumo_update.php and also populate slct1 with cb_insumo_update.php without needing to refresh the page or using a form button.
I tried ajax but I'm kind of new to it so I don´t know how to make it work.
The thing is that I'm using a database to populate the select tags and kinda got confused along the way:

        <select id="slct1" name="slct1" onchange="populate('slct1','slct2')">
          <?php  require('php/cb_categoria_update.php');  ?>
        </select>
        Categoría

        <select id="slct2" name="slct2">
         </select>
        Insumo

cb_categoria_update
<?php

require('Connect.php');

$CB_cate = mysqli_query($enlace,"SELECT * FROM vw_display_catego_insumo");

    echo "<option empty disabled selected>Elija una opción</option>";

while($row = mysqli_fetch_array($CB_cate))
{
    $idcat = $row['fn_idCategoInsumo'];
    $nomcat = $row['fc_NomCategoInsumo'];

    echo "<option value='" . $idcat . "'>" . $nomcat . "</option>";

}

mysqli_close($enlace);

?>

cb_insumo_update
<?php

require('Connect.php');

 $cateinsumo=$_POST['cbidcategoria'];

    $spinsumo="call SP_INSUMOS_BY_CAT('".$_POST['cbidcategoria']."')";

    $sqlspinsumo = mysqli_query($enlace, $spinsumo);

    $sqlarray = mysqli_fetch_array($sqlspinsumo);

    echo "<option disabled selected>Elija una opción</option>";

while($row = mysqli_fetch_array($sqlspinsumo))
{
    $idinsumo = $row['fn_IdInsumo'];
    $nominsumo= $row['fc_NomInsumo'];

    echo "<option value='" . $idinsumo . "'>" . $nominsumo . "</option>";

}

mysqli_close($enlace);

?>

A:

I will use jQuery as an example, it's just easier to throw together than vanilla JavaScript, so you would need the jQuery library in your header (or at the bottom of your page):

        <select id="slct1" name="slct1">

          <?php require('php/cb_categoria_update.php');  ?>
        </select>
        Categoría

        <select id="slct2" name="slct2">
         </select>
        Insumo

An important note, you will want to bind parameters on this query:
$spinsumo="call SP_INSUMOS_BY_CAT('".$_POST['cbidcategoria']."')";

This is not a secure way to run SQL queries.
Alternately, you can do the "Shorthand" methods for the ajax found on this page.


Q:

Legend and colours missing when using plotly from ggplot2

I have made a boxplot using ggplot2 which appears beautifully coloured in R, with the corresponding legend. When I export this to plotly, the boxplots are all red, and the legend has disappeared.
I cannot post a picture of the plot on here, as it wont let me, but my code is as follows:
r <- ggplot(data=all.data, aes(factor(Year), Data))+xlab("Year")
r <- r + geom_boxplot(outlier.shape = NA, aes(fill = factor(Month)))
r <- r + scale_y_continuous(limits = c(-1, 6.5))
r <- r+ scale_fill_discrete(name = "Month")
r
gg <- ggplotly(r,kwargs=list(world_readable=FALSE))

I have included within the geom_boxplot layer the fill command which deals with colour, but I cannot understand why this is not transferring.

A:

Do you have the latest ggplot2 and plotly packages installed? I tried an easy bar chart but cannot reproduce your problem.
I have these versions installed:
packageVersion("ggplot2")
# [1] ‘1.0.1’
packageVersion("plotly")
# [1] ‘1.0.7’
packageVersion("shiny")
# [1] ‘0.12.2’

If your versions are older, you might consider upgrading to the latest greatest.
On my machine this silly example (similar to your incomplete code snippet):
library(plotly)
library(ggplot2)

all.data <- data.frame(Year = c(2000, 2000, 2005, 2005),
                       Month = c("Jan", "Jan", "Jul", "Jul"),
                       Data = c(0, 3.2, 3, 4))

r <- ggplot(data = all.data, aes(factor(Year), Data)) + xlab("Year")
r <- r + geom_boxplot(outlier.shape = NA, aes(fill = factor(Month)))
r <- r + scale_y_continuous(limits = c(-1, 6.5))
r <- r + scale_fill_discrete(name = "Month")
r

Sys.setenv("plotly_username" = "MyCoooolUsername")
Sys.setenv("plotly_api_key" = "MySeCrEtPWD")
plotly:::verify("username")
plotly:::verify("api_key")
gg <- ggplotly(r,world_readable=TRUE)
gg

produces

as expected.


Q:

What is the value in creating distinguishing terminology between the $x$, $y$, and $(x, y)$ values of a possible point of extremum?

I've been out of a math program for about four years now. My wife is starting a CS degree, and finished her first calculus course last semester.
I tutored calculus throughout my entire undergrad, and have read quite a few calculus and real analysis textbooks. When I'm referring to a candidate for an $x$-value at which a point of extremum is located, I've always called it a critical point.
But my wife's professor taught three different terms:

Critical number: the $x$-value at which the possible extremum is located
Critical value: the corresponding $y$-value of the critical number
Critical point: a pair $(\text{critical number}, \text{critical value})$.

I don't understand the pedagogical value in creating these three terms.

This doesn't look like standard terminology. I was confused at first when I was trying to help my wife learn about critical points.
"Critical values" are rarely used in what I specialize in: statistics. I care more about where the extrema are possibly located, rather than what the actual $y$-values are at these possible candidates of extrema. And I like dropping constants whenever possible when it comes to having to find points of extrema, so the $y$-value is useless.

Can someone provide some rationale for why one would want to distinguish between these three bolded terms above?

A:

The standard terminology in use among mathematicians is to call a critical point a point $p$ where the differential of a differentiable function $f:M \to \mathbb{R}$ vanishes ($M$ is a smooth manifold, for example an open subset of $\mathbb{R}$), and to call a critical value the value $r$ it assumes at such a point.
The proposed terminology, calling $p$ a critical number only works in the limited context where $M$ is an open subset of $\mathbb{R}$ or $\mathbb{C}$, so can properly be called a number. It is confusing to call the pair $(p, r)$ a critical point for another reason. The point $p$ and the value $r$ "live" in different spaces. The pair $(p, r)$ lives in $M \times \mathbb{R}$, while $p$ lives in $M$ and $r$ lives in $\mathbb{R}$. In the special case where $M$ is an open subset of $\mathbb{R}$, then $(p, r)$ can be viewed as a point in $\mathbb{R}^{2}$, but this seems to me to generate unnecessary confusion, because the roles of the two coordinates are not symmetric.
On the other hand, one certainly wants to distinguish between the point at which a function is critical and the value it assumes there. This is just formalizing the distinction between the day of the year on which the coldest temperature occurs and what that temperature is, or the distinction between the point on the earth where the elevation above sea level is highest, and what that elevation is. One needs different names for different things.

A:

One rationale for introducing terms for these three objects is to encourage students to be clear about whether they are describing the input, output or pair $(x, y)$ for a function, and giving them language to do so efficiently.
Consider the question "Where is the maximum of the function $f$ on the given domain?" I've seen this type of wording trip students up, particularly if the back of the book just says "$5$". It's totally unclear (to me) whether the directive is to find the maximum output value, the input corresponding to that maximum output, or possibly the ordered pair. Giving names to these three things avoids a wordier rephrasing such as "At what x-value is $f(x)$ maximized on the given domain?"
Now, while my immediate reaction to introducing non-standard terminology is not positive, I do respect an attempt to get students to exercise care in how they communicate their ideas -- and one good way is by giving them language to do so. However, I think even more care should be exercised when introducing any subject-specific terminology, and new or non-standard terminology should almost never be given formally to a class.
[Note: On my shelf, Hughes-Hallett, Taalman, Anton and Faires all use "critical point" for the $x$-value, while two of them mention "critical value" and "stationary point". Sherwood and Taylor (c 1942) use "critical point" for the $(x,y)$ pair and "critical value" for the $x$-coordinate.]


Q:

I couldn't get the Account Kit's delegate methods to get called in Swift

I'm following this tutorial to integrate Facebook AccountKit with Swift. Almost everything is working but delegate functions are not called and I don't know why this is no happening.
My code:
import UIKit
import AccountKit

class LoginViewController: UIViewController,AKFViewControllerDelegate {

    //
    var _accountKit: AKFAccountKit?
    var _pendingLoginViewController: AKFViewController?
    var _authorizationCode: String?

    //
    override func viewDidLoad() {
        super.viewDidLoad()
        if _accountKit == nil {
            _accountKit = AKFAccountKit(responseType: .accessToken)
        }
        _pendingLoginViewController = _accountKit!.viewControllerForLoginResume()
        _pendingLoginViewController?.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func prepareLoginViewController(loginViewController: AKFViewController) {
        loginViewController.delegate = self
    }

    @IBAction func loginWithPhone(_ sender: UIButton) {
        let inputState = NSUUID().uuidString
        let vc: AKFViewController = _accountKit!.viewControllerForPhoneLogin(with: nil, state: inputState)
        self.prepareLoginViewController(loginViewController: vc)
        self.present(vc as! UIViewController, animated: true, completion: nil)

    }

    private func viewController(viewController: UIViewController!, didCompleteLoginWithAuthorizationCode code: String!, state: String!) {
        print("1")
    }

    private func viewController(viewController: UIViewController!, didCompleteLoginWithAccessToken accessToken: AKFAccessToken!, state: String!) {
        print("2")
    }

    private func viewController(viewController: UIViewController!, didFailWithError error: Error!) {
        print("3")
    }

    private func viewControllerDidCancel(viewController: UIViewController!) {
        print("4")
    }

}

Swift version: 3.2
I belice is something to do with the swift version (I believe this tutorial is for 2.x) but i had a similar code from an example in Swift 3 and is working. So I don't know what is going wrong.

A:

You don't need to cahnge methods to private.
Change delegate methods to the following:
func viewController(_ viewController: (UIViewController & AKFViewController)!,
didCompleteLoginWith accessToken: AKFAccessToken!, state: String!) {
}

func viewController(_ viewController: (UIViewController & AKFViewController)!, didCompleteLoginWithAuthorizationCode code: String!, state: String!) {

}

func viewController(_ viewController: (UIViewController & AKFViewController)!, didFailWithError error: Error!) {

}

func viewControllerDidCancel(_ viewController: (UIViewController & AKFViewController)!) {
    print("canceled")
}


Q:

Word for testing a product on yourself

How would I say that I am going to test a product on myself?
For instance "Due to the X testing I will not need to worry about signing ethical forms" (As you might need to sign ethical forms for when testing patients).
Edit (based on a comment by the OP):
it's for an application; if I wanted to get patients to test it I would need to go past an ethics committee to make sure I'm not doing anything bad with their data. But if it's on myself I don't need to go to them.

A:

I'd go for self-experimentation. It's a little verbose but seems to convey the right meaning.
Famous last words: In order not to worry about signing ethical forms, I resorted to self-experimentation.


Q:

Jacoco Maven plugin - include test sources

I'm new in Jacoco maven plugin and trying to add coverage analysis for my test classes (I'm using TestNG with failsafe plugin).
After checking the documentation and some tutorials I made it work on classes in Sources Root (src/main), but couldn't manage to include the classes in Tests Root (src/test). My project consists of only test classes, so the coverage report is required only for these.
In IntelliJ, there is an option "Enable coverage in test folders" which does what I really want. So I think there should be a way to enable these folders in plugin configurations as well.
Thanks for any help!

A:

Achieved what I wanted by adding 0.7.6-SNAPSHOT version of jacoco, thanks to heenenee.
Cloned and built the mentioned version of jacoco, installed the jar locally (different instructions here) and added the tests in coverage data by configuration:
<configuration>
    <includeTests>true</includeTests>
</configuration>


Q:

How to add 3 sided border for an image in iOS

I want to add border for an image. I don't want to add it completely on 4 sides. I want to add border only on particular 3 sides i.e., top,left & bottom. How to do that?
[imageView.layer setBorderColor:[[UIColor clearColor] CGColor]];
This would set the border on 4 sides of the image. But I want it only on 3 sides. How to do that?

A:

You’ll need to add colored subviews on the edges that you want to have borders. See this answer—for the border on the top, follow the same pattern, but use an autoresizingMask of UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin.


Q:

NaN on ajax request returned data

on the php side of the api I have this:
$res = $db->query("SELECT count(upVote) FROM tbl_post_likers WHERE post_id='$pnum' AND upVote='true'");
$row = $res->fetchArray();
if($row[0] > 0){
    $upVotes = $row[0];
    $res = $db->query("SELECT count(downVote) FROM tbl_post_likers WHERE post_id='$pnum' AND downVote='true'");
    $row = $res->fetchArray();
    $downVotes = $row[0];

    $tot = $upVotes + $downVotes;
    $upVotesPer = ($upVotes * 100) / $tot;
    $downVotesPer = ($downVotes * 100) / $tot;
    return $upVotesPer - $downVotesPer;
}else if ($row[0] == 0){
    return 0;
}

and I've tried to return some more data as an array from the api.
and on the javascript side when I JSON.parse the returned data I get all the data correctly as below:
eg:
0: [...],
1: [...],
2: 0

the zero is the return 0; from the php side,
The problem is when I console.log the 3rd property it is undefined or when I parseInt it, it returns NaN while the 3rd property of the returned data as shown is zero.
this is the actual console.log:
0
:
"{"0":2,"id":2,"1":"0.jpg","image":"0.jpg","2":"Proj 1","title":"Proj 1","3":"some description here about the course!","desc":"some description here about the course!","4":"sinawic","teacher":"sinawic","5":0,"sell_count":0,"6":"1997.05.05","date_released":"1997.05.05","7":97,"preview":97,"8":0,"likes":0,"9":0,"post_point":0,"10":0,"post_cash":0}"
1
:
"["jquery","vue"]"
2
:
"[{"lesson_num":1,"topic_name":"pre"}]"
3
:
"{"0":"sinawic","username":"sinawic","1":"web design, React, VUE, javascript","fields_name":"web design, React, VUE, javascript","2":"this is all about me, oke? call me maybe","description":"this is all about me, oke? call me maybe","3":"85%, 53%, 36%, 74%, 17%","ranks":"85%, 53%, 36%, 74%, 17%"}"
5
:
0
and this is the data echo to the api:
{"0":"{\"0\":2,\"id\":2,\"1\":\"0.jpg\",\"image\":\"0.jpg\",\"2\":\"Proj 1\",\"title\":\"Proj 1\",\"3\":\"some description here about the course!\",\"desc\":\"some description here about the course!\",\"4\":\"sinawic\",\"teacher\":\"sinawic\",\"5\":0,\"sell_count\":0,\"6\":\"1997.05.05\",\"date_released\":\"1997.05.05\",\"7\":98,\"preview\":98,\"8\":0,\"likes\":0,\"9\":0,\"post_point\":0,\"10\":0,\"post_cash\":0}","1":"[\"jquery\",\"vue\"]","2":"[{\"lesson_num\":1,\"topic_name\":\"pre\"}]","3":"{\"0\":\"sinawic\",\"username\":\"sinawic\",\"1\":\"web design, React, VUE, javascript\",\"fields_name\":\"web design, React, VUE, javascript\",\"2\":\"this is all about me, oke? call me maybe\",\"description\":\"this is all about me, oke? call me maybe\",\"3\":\"85%, 53%, 36%, 74%, 17%\",\"ranks\":\"85%, 53%, 36%, 74%, 17%\"}","5":0}
how could I possibly solve it.

A:

Your code is trying to access the item at index 5 in the Object.keys array, which would be the 6th item. However you have a gap in the key numbering - 4 is not included.
Therefore the object with the key "5" is actually the 5th item in the list of keys, and therefore accessible at index 4 - because the array of keys is zero-based, like all JS arrays. There is no 6th item - the object only has 5 keys.
I think because the object keys are numeric you have got confused between the name of the key and its position in the list of keys.
Observe the difference between the last 2 console.logs in this (runnable) example:

var allData = { 0:{"0":2,"id":2,"1":"0.jpg","image":"0.jpg","2":"Proj 1","title":"Proj 1","3":"some description here about the course!","desc":"some description here about the course!","4":"sinawic","teacher":"sinawic","5":0,"sell_count":0,"6":"1997.05.05","date_released":"1997.05.05","7":97,"preview":97,"8":0,"likes":0,"9":0,"post_point":0,"10":0,"post_cash":0},
1:["jquery","vue"],
2:[{"lesson_num":1,"topic_name":"pre"}],
3:{"0":"sinawic","username":"sinawic","1":"web design, React, VUE, javascript","fields_name":"web design, React, VUE, javascript","2":"this is all about me, oke? call me maybe","description":"this is all about me, oke? call me maybe","3":"85%, 53%, 36%, 74%, 17%","ranks":"85%, 53%, 36%, 74%, 17%"},
5:0 };

console.log(Object.keys(allData));

console.log(allData[Object.keys(allData)[5]]);

console.log(allData[Object.keys(allData)[4]]);

However you could greatly simplify this. If you already know you want the item whose key is called "5" then you can simply access it directly:

var allData = { 0:{"0":2,"id":2,"1":"0.jpg","image":"0.jpg","2":"Proj 1","title":"Proj 1","3":"some description here about the course!","desc":"some description here about the course!","4":"sinawic","teacher":"sinawic","5":0,"sell_count":0,"6":"1997.05.05","date_released":"1997.05.05","7":97,"preview":97,"8":0,"likes":0,"9":0,"post_point":0,"10":0,"post_cash":0},
1:["jquery","vue"],
2:[{"lesson_num":1,"topic_name":"pre"}],
3:{"0":"sinawic","username":"sinawic","1":"web design, React, VUE, javascript","fields_name":"web design, React, VUE, javascript","2":"this is all about me, oke? call me maybe","description":"this is all about me, oke? call me maybe","3":"85%, 53%, 36%, 74%, 17%","ranks":"85%, 53%, 36%, 74%, 17%"},
5:0 };

console.log(allData[5]);


Q:

Locate Pattern the Letter I followed by a space then three alpha numerics followed by a space

Need to locate the following pattern:
The letter I followed by a space then three alpha numerics followed by a space
"I ALN "
"I H21 "
"I 31M "
these items are also followed by a lat/lon that is trapped by this expression:
Dim regex As New Regex("\d{6} \d{7}")
Can the expressions be combined to return a match that would look like:
"H21 ###### #######"
Thanks,
Dave

A:

/I ([0-z]{3} \d{6} \d{7})/
I don't know VB, but that regex would work with say perl.
Update:
Given the new string provided.. something like this may work (depending on responses to my questions)

/^[A-z] ([0-z]{3}) [A-z] [0-z]{3} L (\d{6} \d{7})/

Matches would then be joined (match 1 containing the AAA, match 2 containing the Lat/Long).
Update #2:
From OP: No on the pattern. The only pattern is I AAA then on the same line the 4000931 0892006. Can you add an OR statement to an expression
You can add an OR, sort of, but I'm uncertain that this is really what you want?
This new regex will match I, followed by a space, followed by 3 alpha numeric characters, and then "anything", and the lat/long. Note tho that if there's data in the file or whatever you're parsing that matches a line like that (in that it's "other" data, but follows a similar pattern), you'll probably catch that too.

/^I ([0-z]{3}) .* (\d{6} \d{7})/


Q:

Matching anything but "[[2,3],[2,3],[3,7]]"

I'm using the RegExp.prototype.test() method in JS to find out if I have anything but an array in the form:
"[[2,3],[2,3],[3,7]]"
// or
"[[2,3],[3,7]]"
// there could be any amount of children arrays

So I'd like to match anything but an array like "[[2,3],[2,3],[3,7]]".
For example these should match:
[2,3,4]
// or
{test: true}
// or
[2,4][[2,3],[2,3],[3,7]]

I've tried:
/.*(?!\[(?:\[[0-9]+,[0-9]+\])(?:,\[[0-9]+,[0-9]+\])*\])/

but this, of course, matches everything, even the array which should not match. How do I solve this? I'd be very grateful for any help!

A:

This method (using !) passes your tests. If that's not what you want, please provide more valid/invalid inputs so that we can help you better:

function isNotATwoDimensionalArrayOfIntegers(s) {
  const regex = /^\[(\[-?\d+,-?\d+\],)*\[-?\d+,-?\d+\]\]$/;
  return !regex.test(s);
}

const demo = s => { const res = isNotATwoDimensionalArrayOfIntegers(s); result.innerHTML += `<span style="color: ${res ? 'green' : 'red'}">${s}  // ${res}</span>\n` } ;

demo("[[2,3],[2,3],[3,7]]");
demo("[[2,3],[3,7]]");
demo("[2,3,4]");
demo("{test: true}");
demo("[2,4][[2,3],[2,3],[3,7]]");

View regex explanation on Regex101


Q:

std::string and std::map operations on Unicode string

I would like to understand how regular std::string and std::map operations deal with Unicode code units should they be present in the string.
Sample code:
    include <iostream>
    #include "sys/types.h"

    using namespace std;

    int main()
    {

        std::basic_string<u_int16_t> ustr1(std::basic_string<u_int16_t>((u_int16_t*)"ยฤขฃ", 4));
        std::basic_string<u_int16_t> ustr2(std::basic_string<u_int16_t>((u_int16_t*)"abcd", 4));

        for (int i = 0; i < ustr1.length(); i++)
            cout << "Char: " << ustr1[i] << endl;

        for (int i = 0; i < ustr2.length(); i++)
            cout << "Char: " << ustr2[i] << endl;

        if (ustr1 == ustr2)
            cout << "Strings are equal" << endl;

        cout << "string length: " << ustr1.length() << "\t" << ustr2.length() << endl;
        return 0;
    }

The strings contain Thai characters and ascii characters, and the intent behind using basic_string<u_int16_t> is to facilitate storage of characters which cannot be accommodated within a single byte. The code was run on a Linux box, whose encoding type is en_US.UTF-8. The output is:
$ ./a.out
Char: 47328
Char: 57506
Char: 42168
Char: 47328
Char: 25185
Char: 25699
Char: 17152
Char: 24936
string length: 4        4

A few questions:

Do the character values in the output correspond to en_US.UTF-8 code points? If not, what are they?
Would the std::string operators like ==, !=, < etc., be able to work with Unicode code points? If so, would it be a mere comparison of each code points in the corresponding locations? Would std::map work on similar lines?
Would changing the locale to UTF-16 result in the strings getting stored as UTF-16 code points?

Thanks!

A:

I would like to understand how regular std::string and std::map operations deal with Unicode code units should they be present in the string.

They don't.
std::string is a sequence of chars or bytes. It is not a "high-level" string taking any encoding into account. You must do that yourself, e.g. by using a library dedicated to that purpose such as ICU.
Switching from std::string (i.e. std::basic_string<char>) to std::basic_char<u_int16_t> doesn't change that; it just means you have a sequence of "wide" characters instead.
And std::map has nothing to do with this at all.
Further reading:

https://stackoverflow.com/a/17106065/560648
https://www.reddit.com/r/cpp/comments/1y3n33/why_does_c_seem_to_pretend_unicode_doesnt_exist/


Q:

Oracle - connection Pooling with spring framework

We are trying to implement Oracle connection pooling with the help of Spring Framework. We are using DBCP connection pooling method. However the integration between DBCP and spring doesn't go down that well.
Problem that we face is that DBCP returns PoolableConnections Object while Oracle expects OracleConnection Objects. (Throws ClassCastException)
It seems that this problem has been handled in Oracle 11g. However I am curious as to how others have implemented Oracle connection pooling using spring framework for Oracle 10g (Using TOMCAT).
We use Ibatis as ORM framework.
I am sure there is a way. any help is appreciated.

A:

I would use Oracles supplied solution, which in included in their ojdbc jars.  The older way was with the class OracleConnectionPoolDataSource but now you can set a parameter on a regular OracleDataSource and get connection pooling.
Here is how to do it in Spring:
<bean id="datasource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
   <property name="connectionCachingEnabled" value="true" />
   <property name="URL" value="${jdbc.url}" />
   ...all your connection properties
   <property name="connectionCacheProperties">
      <props merge="default">
         <prop key="MinLimit>3</prop>
         <prop key="MaxLimit">20</prop>
      </props>
   </property>
</bean>

A:

I use C3PO to establish the connection. It has also the advantage to do connection pooling for you. Just define a datasource bean of type e.g. com.mchange.v2.c3p0.ComboPooledDataSource (or similar) through your spring config files. Before I run into troubles with connection pooling, I even used one of spring (DriverManagerDataSource) that is not advised for production use, because it is not actually doing the connection pooling.
Here is an example spring configuration.
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:XE"/>
    <property name="user" value="username"/>
    <property name="password" value="secret"/>
    <property name="minPoolSize" value="5"/>
    <property name="maxPoolSize" value="20"/>
    <property name="acquireIncrement" value="1"/>
    <property name="idleConnectionTestPeriod" value="100"/>
    <property name="maxStatements" value="0"/>
    <property name="checkoutTimeout" value="60000"/>

Spring then injects the dataSource bean into Hibernate and all is well. You will also need to have the c3pO jar file on your classpath...

A:

You should not implementing your own pooling, if that's what you're using. Tomcat already does that for you, instead, define a data source in Tomcat, and have your ORM framework use it (when you define your Tomcat data source, you can specify the pool configurations there).
If you could post some code snippets, specifically, the relevant Spring context configurations, I can help provide you with how you'd do this.
Here's Tomcat documentation that shows you exactly how you do that:

http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html

Incidentally, Tomcat uses DBCP also, and it's better to rely on JNDI, as it makes your code more portable (from one environment to another - e.g., dev to staging to production, or even across application servers - e.g., to WebSphere, WebLogic etc).


Q:

Replace all values in a column of one dataframe using values in a row of another dataframe (matching by row name and column name)

I have a dataframe which is a presence absence matrix of species found in different locations (1 indicates presence, 0 absence) like so:
df1<-data.frame(replicate(5,sample(0:1,5,rep=TRUE)))
row.names(df1)<-c("location.1","location.2","location.3","location.4","location.5")
names(df1)<-c("species.1","species.2","species.3","species.4","species.5")

           species.1 species.2 species.3 species.4 species.5
location.1         0         1         0         1         1
location.2         1         0         0         1         0
location.3         0         0         1         0         0
location.4         1         0         1         0         1
location.5         0         0         1         0         0

I have a second dataframe which has values for each species, like so:
df2<-c(2,4,6,8,10)
df2<-as.matrix(df2)
row.names(df2)<-c("species.1","species.2","species.3","species.4","species.5")

          [,1]
species.1    2
species.2    4
species.3    6
species.4    8
species.5   10

I would like to replace all 1s in the first dataframe, on a column by column basis, with the matching value in the second dataframe, based on the species names. Producing this:
           species.1 species.2 species.3 species.4 species.5
location.1         0         4         0         8        10
location.2         2         0         0         8         0
location.3         0         0         6         0         0
location.4         2         0         6         0        10
location.5         0         0         6         0         0

I have no idea how I'd go about doing this though, and can't find any similar examples online.
Does anyone have any advice?

A:

We can do this by one of the options below
 df1*df2[,1][col(df1)]

Here, we multiply the first dataset with the first column of 'df2' replicated to make the lengths same

Or another option is sweep which has the MARGIN, STATS and FUN argument to apply the function on corresponding elements of column (MARGIN = 1 does on rows)
 sweep(df1, 2, df2[,1], "*")

Or we can use mapply to loop over the columns and multiply by the corresponding elements of the vector 'df2[,1]`
 mapply("*", df1, df2[,1])


Q:

usage of WorksheetFunction.Year in excel vba For loop

I have a series of dates in my sheet DailyData A column. I need to find out whether its leap year (in A Column) and depends upon that performing a calculation in F Column.( for leap year, I need to use 366 else 365)
Found that using below formula, I can check its leap year or not.
b = 4
a=Year to check
If a - (b * (a \ b)) = 0, then its leap year

Now, I am using below code to perform the calculation, but its giving me error "Object doesn't support this property or method" on line   a = WorksheetFunction.Year("A", J)
What will be correct method of check it ?
Sub DayTest()
    Dim MaxGain As Workbook
    Dim Main As Worksheet
    Dim DailyData As Worksheet
    Dim n As Long
    Dim J As Long
    Dim a As String, b As Integer

    Set MaxGain = Excel.Workbooks("MaxGain.xlsm")
    Set DailyData = MaxGain.Worksheets("DailyData")
    Set Main = MaxGain.Worksheets("Main")
    DailyData.Activate

    n = DailyData.Cells(Rows.Count, "A").End(xlUp).Row

    J = 1
    b = 4

    For J = 2 To n

    a = WorksheetFunction.Year("A", J)

    If a - (b * (a \ b)) = 0 Then

    DailyData.Range("F" & J).Value = Main.Range("B2").Value / 366

    Else

    DailyData.Range("F" & J).Value = Main.Range("B2").Value / 365

    End If

    Next

End Sub

UPDATE:
I have figured it. Changed the line
a = WorksheetFunction.Year("A", J)

to
a = Year(DailyData.Range("A" & J))

A:

I have figured it.Changed below line
a = WorksheetFunction.Year("A", J)

to
a = Year(DailyData.Range("A" & J))


Q:

Ubuntu unattended upgrades to run at a certain time

I'm trying to work out the best way to run unattended upgrades every Thursday at 3am but can only see a way to run this weekly but not a given time.
I thought of one way would be to have a script that is called by cron on Thursday at 3am
The below script would work just for security updates
#!/bin/sh
sh -c 'grep precise-security /etc/apt/sources.list > /etc/apt/secsrc.list'
sh -c 'apt-get -o Dir::Etc::sourcelist="secsrc.list" \
-o Dir::Etc::sourceparts="-" update && \
apt-get --assume-yes upgrade'

Any thoughts on another way?

A:

What wrong with doing it this way? If you just add a cron rule 0 3 * * Thu USERNAME SCRIPT  it should work fine.


Q:

FIlling rectangle with boxes using CSS

I am trying to create a rectangle filled with boxes with colours
The following is my code:

I want something similar to this:

However, I am unable to acquire boxes. What am I doing wrong?

A:

You need to close your div tags properly using
 and not just />.
To get the height of each box to fill the entire div, you can give each child div a height in percentage. In your case you would have 14.28%(No. of elements / 100).


Q:

P vs NP and OWFS

It is known (simple HW exercise) that:
If P = NP, that OWFs (one way functions) can not exist.
It is also known that there is a Universal OWF:
  namely, there is a function f:
    s.t. if any OWF exists, then f is a OWF.
  [This is a standard result of concatenating many functions.]
Question:
  Is the following question open:
    (P != NP) => (OWFs exist) ?
[And what is known about this question?]
Thanks

A:

P != NP does not imply anything about the existence of one-way functions. From Goldwasser and Bellare's "Lecture Notes on Cryptography":

However, the above mentioned necessary condition (e.g.: P != NP) is not a sufficient one. P != NP only implies that the encryption scheme is hard to break in the worst case. It does not rule-out the possibility that the encryption scheme is easy to break in almost all cases. In fact, one can easily construct "encryption schemes" for which the breaking problem is NP-complete and yet there exist an efficient breaking algorithm that succeeds on 99% of the cases. Hence, worse-case hardness is a poor measure of security.

Also, two of Impagliazzo's worlds where P != NP, Heuristica and Pessiland, have no one-way functions while two others, Minicrypt and Cryptomania, do.


Q:

Get the non unique values from 2 columns using formula

I need in getting the non unique values (no duplicates) between Column A and B and reflect it on Column C. I need this in a formula coz it will be used for a google sheet and macros don't translate well to it.
What I'm doing is checking if Column B has any duplicates in Column A and if it has, it will not be reflected in column C.
I've tried using =iferror(vlookup(B2,A2:A50,1,0),B2) but it will also reflect the non error values.
Is there a way to do this?

A:

Easy to Do with VBA using an UDF. However, just with native Excel functions the best I can come up with is using a helper column (which you can of course hide afterwards).

On column C use this only show the values from column B that are not in column A.
=IF(ISERROR(MATCH(B2;$A$2:$A$50;0));IF(B2<>"";B2;"");"")
Then on column D use this to only show the unique values for column C.
=IFERROR(INDEX($C:$C;SMALL(INDEX((($C$2:$C$50)<>"")*ROW($C$2:$C$50);0);ROW(C1)+COUNTBLANK($C$2:$C$50)));"")
(Not my original work, don't know who came up with it first though.)
Remember to replace ; with , in the formulas.
Basically all this does is shows the results of column C without blanks. If someone manages to merge these functions that would be awesome.


Q:

How can I suppress the "...this does not map back..." message when using SSH?

I am writing a script that attaches to several of our machines via SSH to check some usage stats.
Each time I do:
ssh -i ~/.ssh/ourkeyfile.pem user@host

I get the typical message:
Address X.X.X.X maps to somedomain.com, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!

Is there a commandline switch for ssh that lets me suppress this message from appearing in the output of my script?

A:

Based on what Danila suggested:
To suppress only the warnings and errors you would do this...
2>/dev/null


Q:

Multiple Row Auto Calculation and CheckBox? How to reduce it?

What will I add if everytime user is unchecking the checkbox, the ammount will be reduced ? Thanks

I have a code below :
echo '<INPUT TYPE="text" NAME="eg_payamt_[]" Value="' . $amount_dueArr[$record_count] . '" size="10">
';//display ammountDue (AmmountDue)

echo '<INPUT TYPE="text" NAME="eg_payamt_[]" Value="' . $TotalArr[$record_count] . '" size="10">
';//display outstanding (Total)

<input type="checkbox" name="pay[]" value="" />

My question is, how to calculate the total amount inside the textbox everytime user click the checkbox ?
Thanks
can you do like this :

<INPUT TYPE="text" NAME="eg_payamt_[]" Value="" size="10">

<input type="checkbox" name="pay[]" value="" onclick="return calculateSum();" />

<INPUT TYPE="text" NAME="eg_payamt_[]" Value="" size="10">

<input type="checkbox" name="pay[]" value="" onclick="return calculateSum();" />

<INPUT TYPE="text" NAME="answer" id="answer" Value="" size="10">

can you do like this ? is it working ? i m trying now...
complete code :

     <form name="payform" method="POST" action="payment.php">

Pay Invoices

               Date
               Invoice
               Ammount
               Outstanding
               Pay

            <?php
                  echo '<INPUT TYPE="hidden" NAME="record" Value="'.$record.'">';
              $amountDueTotal = 0;
           for($record_count=0;$record_count<$record;$record_count++)
                { //loop for record count
                        ?>

                    <?php
                        $strDate = $node_date->nodeValue; //display the date of invoice (Date)
                        echo substr($strDate, -2) . '-' . substr($strDate, -4, 2) . '-' . substr($strDate, 0, 4);
                        //echo $node_date->nodeValue; //display the date of invoice (Date)
                    ?>

                   <?php
                       //echo $node_inv_no->nodeValue; //display the invoice number (DocumentID)
                       echo '<INPUT TYPE="text" NAME="eg_description_[]" Value="' . $invoiceArr[$record_count] . '" size="20">
';  //display the invoice number (DocumentID)
                    ?>

                    <?php
                       echo '<INPUT TYPE="text" NAME="eg_payamt_[]" Value="' . $amount_dueArr[$record_count] . '" size="10">
';//display ammountDue (AmmountDue)
                       //echo $node_amount_due->nodeValue; //display ammountDue (AmmountDue)
                    ?>

                    <?php
                       echo '<INPUT TYPE="text" NAME="eg_payamt_[]" Value="' . $TotalArr[$record_count] . '" size="10">
';//display outstanding (Total)
                       //echo $node_total->nodeValue; //display outstanding (Total)
                    ?>

               <input type="checkbox" name="pay[]" value="" onClick="calculateSum()"/>

               <?php
                     $amountDueTotal += $amount_dueArr[$record_count]; //calculate the total ammount due
                       //Hidden fields
                      echo '<INPUT TYPE="hidden" NAME="eg_invoice_[]" Value="'.$invoiceNoArr[$record_count].'">';
                      echo '<INPUT TYPE="hidden" NAME="p_invage_[]" Value="'.$DateArr[$record_count].'">';
                }//end of the record count loop

                ?>

               Pay Ammount Not Listed Above
               <input type="text" name="UnknownDocumentID" value="Invoice_unknown_docID_data" />

               <input type="text" name="eg_payamt_[]" value="amount" size="10"/>

               <input type="checkbox" name="pay[]" value="" onClick="calculateSum()"/>

               Total ammount to pay

                    <input type="text" name="totalNS" id="answer" value="" />
                    <INPUT TYPE="text" NAME="answer" id="answer" Value="" size="10">

Payment after click, no result :

Am I writing the right code ?
<INPUT TYPE="text" name="answer" id="answer" Value="" size="10">

because when I put
document.write(sum);

****Got the answer :****

<form name="listForm">
<input type="checkbox" name="choice" value="2" onchange="checkTotal()"/>2

<input type="checkbox" name="choice" value="5" onchange="checkTotal()"/>5

<input type="checkbox" name="choice" value="10" onchange="checkTotal()"/>10

<input type="checkbox" name="choice" value="20" onchange="checkTotal()"/>20

Total: <input type="text" size="2" name="total" value="0"/>
</form>

A:

Let's work out on this below code..

<INPUT TYPE="text" NAME="eg_payamt_[]" Value="" size="10">

<INPUT TYPE="text" NAME="eg_payamt_[]" Value="" size="10">

<INPUT TYPE="text" NAME="answer" id="answer" Value="" size="10">

<input type="checkbox" name="pay[]" value="" onclick="return calculateSum();" />

This working fine for me..Check it out.
Thanks.


Q:

How do I refresh a tab on Xamarin.Forms app

My app is running very smoothly, a major issue I'm having is that I have a save button, once clicked it saves an instance of the values entered by the user in a SQLite database locally. When I change to my other tab, it doesn't save... but if I shut the app down then reopen it its there as if there is no on click refresh through the app. also when I hit save I would like all the entry boxes the user fills in to go blank after the save button is clicked.
 void SaveButton_Clicked(object sender, System.EventArgs e)
        {
            MainWindowViewModel APR = new MainWindowViewModel()
            {
                ProductName = proName.Text,
                TotalAPR = totAPR.Text,
                Total = tot.Text,
                Monthly = mon.Text
            };

            using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
            {
                conn.CreateTable<MainWindowViewModel>();
                int rowsAdded = conn.Insert(APR);
            }

        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
            {
                conn.CreateTable<MainWindowViewModel>();
                var APRS = conn.Table<MainWindowViewModel>().ToList();

                APRListView.ItemsSource = APRS;
            }
        }

Above is my code for save button & appearing. Below is the xaml for save button (not sure if needed)
 <Button Text="Save"
                TextColor="#FFA600"
                BackgroundColor="#2B333F"
                Clicked="SaveButton_Clicked"
                FontSize="16"
                Padding="10"
                Grid.Column="1"
                Grid.ColumnSpan="3"
                Grid.Row="14"
                Grid.RowSpan="2"
                VerticalOptions="Center"
                HorizontalOptions="Center"
                Margin="0,0,0,-20"/>

A:

Missing code in the SaveButton_Clicked Routine
BindingContext = new MainWindowViewModel();

        OnAppearing();

Full code should be
void SaveButton_Clicked(object sender, System.EventArgs e)
    {
        MainWindowViewModel APR = new MainWindowViewModel()
        {
            ProductName = proName.Text,
            TotalAPR = totAPR.Text,
            Total = tot.Text,
            Monthly = mon.Text
        };

        using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.CreateTable<MainWindowViewModel>();
            int rowsAdded = conn.Insert(APR);
        }

        DisplayAlert("Saved!", "Your APR has been saved!", "OK");

        BindingContext = new MainWindowViewModel();

        OnAppearing();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.CreateTable<MainWindowViewModel>();
            var APRS = conn.Table<MainWindowViewModel>().ToList();

            APRListView.ItemsSource = APRS;

        }
    }


Q:

Camcorder vs. GoPro mounted on bike

I am using a GoPro mounted to a bike to capture crews rowing in a boat next to a (gravel) bike path. I am mostly happy with what the GoPro offers except that I need a less wide-angled view. For better quality and having access to zoom lenses, I am considering using a camcorder instead. However, I am worried that mechanical vibrations are going to break the camcorder which I would expect containing moving parts whereas a GoPro has none. Any recommendations from people taking videos by mounting them to vehicles (rather than holding them)?
Example: https://vimeo.com/338228818

A:

The primal problem will be the stabilization. GoPro's Cameras offer a decent image-stabilization and are wide-angled. This allows shakes and bumps to have less of an impact. If you now go for a camcorder with, say, a lens of 50mm, you will experience an extreme increase in shakiness.
In other words: When you worry about your camera to break due to shakes and bumps, the footage will most likely not be great.
There are some options you have, which one to choose is on you.
First, you could try to buy a GoPro that can record in 4k (maybe you already own one). That way, you can hit two birds with one stone. On the one hand side, you will be able to zoom in digitally in post without losing any image quality, assuming you want to render in full HD (1920x1080). This fixes the issue of the wide-angle lens. On the other hand side, there will be plenty of material around the visible area, so a warp-stabilizer in After-Effects should easily help stabilize the footage, giving you a much more smooth result than opting to put a camcorder on your bike.
The other options would be to use a camcorder indeed, or even a tv-production or cinema-camera if you like, but staying off that bike. Either, you can rent or buy a Steady-Cam or Gimble (the ones from Ronin are very good) and run along. The Gimble or Steady-Cam will stabilize your Camera and will give you probably the best results (assuming you know how to properly use a Gimble / Steady-Cam).
This is also the priciest option though, I fear.
The other is to use the camcorder or higher-tier camera again, but stay still entirely. You can try to find a Spot on the path where the water flows around you a small bit, like in any curve of the river. Position yourself on the extended piece of land and just pan with the Subject, instead of moving at all. This would be the easiest and probably cheapest option, though it only really works well for short, preferably fast pace sequences, so you don't catch that the camera is stationary. Many people use this method to capture people running in forests: The actors simply run in a circle around the camera and the operator pans with them, which results in footage looking like they follow the subject horizontally.
I hope my answer was helpful, good luck with your project!


Q:

How to show names of attachments from a list item in a column?

I have an announcements list and some announcements have multiple attachments. The view is set to show the attachments, but it just shows this paperclip icon which probably means the list item has attachments.
What I need to achieve, is to show the name of the attachments of the list items in an extra column (if possible, on a multiline text field). How would I achieve this?
I found this site that has an answer but it is for SP2010, I am working in SP2013 and I can't use this. :( Anything that can be done with SP Designer 2013 would be awesome.

A:

You have 2 ways to do it.
One is create a hidden field in the list named Attachments, and with the help of event receiver, set it when attachment added, updated, deleted. So, now you have the attachment names (if needed add them as links, for this the column must be of type multi line text box (rich text field)).
Second and easiest way is the modifications using SharePoint Designer. Just follow this steps mentioned at: http://amitphule.blogspot.in/2012/04/display-item-attachments-in-sharepoint.html
Let me know if you need any additional help.


Q:

Writing files efficiently — Collect or write immediately

Is there a performance difference for file I/O between the following two approaches?

Use a queue that is filled by producers and start a task writing to disk after all data has arrived
Have a task writing to disk in parallel to producers

The data is written to different files and multiple directories.
A separate task for the I/O and Parallel.ForEach would be used in both cases.
I would assume that the second version would perform better, theoretically the producers and the I/O are really concurrent. Since I/O causes interrupts to the calling process I was wondering if there would be a down-side. This might cause overhead that outweighs the benefits of parallelism.
Are there situations were I should favor the first solution over the second?

A:

I would assume that the second version would perform better

If the multiple directories are still on the same physical drive you will likely get worse performance with the 2nd option.
There are some edge cases where writing in parallel (and limiting yourself to only 2 or 3 threads) can be faster. For example writing 1000's of 1kb files would perform better in a slightly parallel fasion due to the overhead costs of creating a file outweighing the IO costs of writing to the file. But if you where writing 1000's of 1mb files then having a single thread doing the writing would likely be faster.
A easy way to implement this is use TPL Dataflow, you can have a highly parallel TransformBlock but then have that connected to a 1 or 2 threaded ActionBlock which performs the writes. You then limit the input buffer of the ActionBlock when you set up the link and the TransformBlock will block producers if the pipeline is full without taking up a lot of memory.


Q:

PHP Array_$POST to SQL

I am trying to get the current PHP code and insert into the database. Currently I am able to save the first name, last name, and email but unable to get the rest of my form data "gender", and "console" to be saved. Here is the code
<!Doctype html public>

fill out the following form:

 Devices owned Survey

<form action="submit_answer.php" method = "POST">
First Name:
 <input type="text" name="first" />

Last Name:
 <input type="text" name="last" />

Email:
 <input type="text" name="email" />

Gender:

<input type="radio" name="gender" value="male" /> Male

<input type="radio" name="gender" value="female" /> Female

I Have The Following:

<input type="checkbox" name="console" value="Playstation3" /> Playstation 3

<input type="checkbox" name="console" value="Xbox360" />  Xbox 360

<input type="checkbox" name="console" value="Wii" />  Wii

<input type="checkbox" name="console" value="Iphone" />  Iphone

<input type="checkbox" name="console" value="MacBook" />  MacBook

<input type="submit"/>
</form>

 PHP //SUMBMIT FORM
<?php

define('DB_NAME', 'survey');
define('DB_USER', 'root');
define('DB_PASSWORD', 'XXXX');
define('DB_HOST', 'localhost');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

 if (!$link)
{
die('Could NOT Connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);

if (!$db_selected)
{
die ('Cant\'t use' . DB_NAME. ':' . mysql_error());
}
echo 'Connected Sucessfully';

$first = $_POST["first"]; // Since method=”post” in the form
$last = $_POST["last"];
$email = $_POST["email"];
$gender = $_POST["gender"];
$console = $_POST["console"];

$sql = "INSERT INTO survey (first, last, email) VALUES
( '$_POST[first]','$_POST[last]','$_POST[email]','$_POST[gender]','$_POST[console]')";
$result = mysql_query($sql);

$result = mysql_query($sql) or die ("could not save record");

mysql_close();
?>
//Also trying to validate the form so each question is answered

A:

The method you're using to save data to your DB is extremely risky.  You're open to SQL injection attacks.  That being said, you should read up on SQL injection attacks with mysql_query.
I'm not going to rewrite your code completely to fix the SQL injection vulnerabilities, but to fix the problem you're currently having...
In your code you have:
$sql = "INSERT INTO survey (first, last, email) VALUES
( '$_POST[first]','$_POST[last]','$_POST[email]','$_POST[gender]','$_POST[console]')";

You're specifying 3 columns, but passing in 5 columns.  You need to add the other 2 columns
$sql = "INSERT INTO survey (first, last, email, gender, console) VALUES
( '$_POST[first]','$_POST[last]','$_POST[email]','$_POST[gender]','$_POST[console]')";

But seriously, change your code!
EDIT:
If you want to take an array of $_POST['console'] and turn it into a string that has comma separated values, try this:
Add array brackets to your name attribute:
<input type="checkbox" name="console[]" value="Playstation3" /> Playstation 3

<input type="checkbox" name="console[]" value="Xbox360" />  Xbox 360

<input type="checkbox" name="console[]" value="Wii" />  Wii

<input type="checkbox" name="console[]" value="Iphone" />  Iphone

<input type="checkbox" name="console[]" value="MacBook" />  MacBook

Iterate array and append values to a string:
<?PHP
$consoleArray = $_POST['console'];
$consoleCommaString = "";
if ($consoleArray != null && is_array($consoleArray)) {
    foreach ($consoleArray as $consoleValue) {
        $consoleCommaString .= $consoleValue .", ";
    }
}

$sql = "INSERT INTO survey (first, last, email, gender, console) VALUES ('$_POST[first]','$_POST[last]','$_POST[email]','$_POST[gender]','$consoleCommaString')";
?>


Q:

Return from a javascript function when using NEW

I've came a cross an interesting situation in java script that I just can't wrap my head around :
Consider the following function :
T = function(){
this.help = 'foo';

var n = function(){};
return 'test';
}

When writing t = new T(); , t is an instance object and the return parameter is ignored.
however, when writing
T = function(){
this.help = 'foo';

var n = function(){};
return n;
}

writing t = new T(); will result in t being a function, and not an object. so the return value is NOT ignored and the this section is ignored instead(assigning local variables)
So my two questions :

Why?
Are there any other occasions where this happens?

A:

When you return an object from a "construction function" (any function you invoke with new), that object becomes the return value. Any other return value is ignored and the newly constructed object is returned.
A literal string is not an object, but a function is.

A:

From Mozilla JavaScript Reference:

The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)

In simpler words, this is how constructor calling works in JavaScript, i.e. if you return nothing or a primitive type (like plain string or numbers) or this, then they will be ignored and this will eventually be returned. However if you return an object or function from the constructor, that object will be returned with new.
I borrowed the following code from this blog post, which may be helpful here.
// Undefined return value.
function A() {
    return;
  }
  // Reference to instance.

function B() {
    return (this);
  }
  // String return value.

function C() {
    return ("string");
  }
  // Number retun value.

function D() {
    return (123);
  }
  // New object return value.

function E() {
    return ({
      foo: "bar"
    });
  }
  // New array return value.

function F() {
    return (["foo", "bar"]);
  }
  // New instantiation return value.

function G() {
    return (new A());
  }
  // Native "object" return value -- this one would be the same
  // for Number, Boolean, and String.

function H() {
    return (new Number(123));
  }
  // -------------------------------------------------- //
  // -------------------------------------------------- //
  // See what reference we have as a result of instantiation.

console.log(new A());
console.log(new B());
console.log(new C());
console.log(new D());
console.log(new E());
console.log(new F());
console.log(new G());
console.log(new H());

this returns
A {}
B {}
C {}
D {}
Object { foo="bar"}
["foo", "bar"]
A {}
Number {}


Q:

GetColumn Information and Width on Resize - Slick Grid

Am working on slick grid where am trying to  get the column information like id,name and the new width of column after resize.
I wrote an event which will be triggered when  user resizes the column.
grid.onColumnsResized.subscribe(function (e, args) {
           //To Do
        });

grid.getColumns()  will help but how do i identify which column user has resized. is there a way I can get the column index of the resized column?
some start up code from here will save lot of my time
Thanks

A:

The onColumnsResized event triggered by SlickGrid doesn't include any references to the columns which changed.
It's important to note that the width of multiple columns may have changed when this event triggers. Examples of this are:

Using the grid option forceFitColumns: true to force the columns to fit in the width of the grid
Resizing a column so small it affects the columns to its left

Two possible options for implementing this are:
Check columns after change
SlickGrid stores the previous column widths in the property named previousWidth on each column. You can compare the prevoiusWidth and width values to determine which columns changed.
grid.onColumnsResized.subscribe(function (e, args) {
  //Loop through columns
  for(var i = 0, totI = grid.getColumns().length; i < totI; i++){
    var column = grid.getColumns()[i];
    //Check if column width has changed
    if (column.width != column.previousWidth){
      //Found a changed column - there may be multiple so all columns must be checked
      console.log('Changed column index : ' + i);
      console.log(column);
    }
  }
});

SlickGrid resets the previousWidth values for all columns whenever a column starts being resized.
You can view an example of this approach at http://plnkr.co/edit/W42pBa2ktWKGtqNtQzii?p=preview.
Modifying SlickGrid
If you are hosting SlickGrid and are comfortable maintaining your own version then you could modify it to include column information in the args of the onColumnsResized event.
In slick.grid.js at line 860 amend the code where the event is triggered to include an array containing the indexes of changed columns. You can also include the index of the column which the user resized if this is useful. The below adds properties named changedColumnIndexes and triggeredByColumnIndex which are passed in the args of the triggered event. I've wrapped the changes for this in comments prefixed //MODIFICATION.
.bind("dragend", function (e, dd) {
  var newWidth;

  //MODIFICATION - Add array to capture changed column indexes and variable to capture
  //               the index of the column which triggered the change
  var changedColumnIndexes = [];
  var triggeredByColumnIndex = getColumnIndex($(this).parent()[0].id.replace(uid, ""));
  //MODIFICATION END

  $(this).parent().removeClass("slick-header-column-active");
  for (j = 0; j < columnElements.length; j++) {
    c = columns[j];
    newWidth = $(columnElements[j]).outerWidth();

    //MODIFICATION - Add column index to array if changed
    if (c.previousWidth !== newWidth) {
      changedColumnIndexes.push(j);
    }
    //MODIFICATION END

    if (c.previousWidth !== newWidth && c.rerenderOnResize) {
      invalidateAllRows();
    }
  }
  updateCanvasWidth(true);
  render();

  //MODIFICATION - Amend trigger for event to include array and triggeredBy column
  trigger(self.onColumnsResized, {changedColumnIndexes: changedColumnIndexes, triggeredByColumnIndex: triggeredByColumnIndex});
  //MODIFICATION END

});

In your own code subscribe to the onColumnsResized event and pickup the changed column index from the args of the event.
grid.onColumnsResized.subscribe(function(e, args) {
  //Triggered by column is passed in args.triggeredByColumnIndex
  console.log('Change triggered by column in index : ' + args.triggeredByColumnIndex);
  console.log(grid.getColumns()[args.triggeredByColumnIndex]);

  //Column array is passed in args.changedColumnIndexes
  console.log('Changed columns are...');
  console.log(args.changedColumnIndexes);

  //Loop through changed columns if necessary
  for (var i = 0, totI = args.changedColumnIndexes.length; i < totI; i++){
    console.log(grid.getColumns()[args.changedColumnIndexes[i]]);
  }
});

You can view an example of this approach at http://plnkr.co/edit/4K6wRtTqSo12SE6WdKFk?p=preview.


Q:

Does "I've worked for Google" imply I still work for them?

If I say "I've worked at Google" do you understand I still work at Google, I don't work anymore or you cant tell solely based on that sentence?

A:

By itself, "I've worked at Google," does not imply whether or not you still work there.  It is up to the inference of the listener, because you are leaving out the part that would clarify.  If you want to clarify, you can say, "I've worked at Google, and I still do," or "I've worked at Google in the past, but no longer."  Without some such explicit clarification, it remains unclear.
On the other hand, if you specify a unit of time, you are implying whether or not you still work there.
"I have worked at Google for four years," implies you still work there.
"I did work at Google for four years," implies you no longer work there.


Q:

Remove Action & Controller from url - EXT:news & RealURL

I'm having trouble removing /news/story/ from my URL's when using ext:news and real url.
What I'd like is:
www.mysite.com/en/news/this-is-my-story-title
And not:
www.mysite.com/en/news/story/this-is-my-story-title
Current page structure:
-root(1)
--Home (2)
--News (3)
---Story (4)

This is my manual realurl conf:
<?php

$GLOBALS['TYPO3_CONF_VARS']['FE']['addRootLineFields'] .= ',tx_realurl_pathsegment';

$domain = 'mysite.com';
$rootPageUid = 1;
$rssFeedPageType = 9818; // pageType of your RSS feed page

$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'][$domain] = [
    'pagePath' => [
        'type' => 'user',
        'userFunc' => 'EXT:realurl/class.tx_realurl_advanced.php:&tx_realurl_advanced->main',
        'spaceCharacter' => '-',
        'languageGetVar' => 'L',
        'expireDays' => '3',
        'rootpage_id' => $rootPageUid,
        'firstHitPathCache' => 1
    ],
    'init' => [
        'enableCHashCache' => true,
        'respectSimulateStaticURLs' => 0,
        'appendMissingSlash' => 'ifNotFile,redirect',
        'adminJumpToBackend' => true,
        'enableUrlDecodeCache' => true,
        'enableUrlEncodeCache' => true,
        'emptyUrlReturnValue' => '/',
    ],
    'fileName' => [
        'defaultToHTMLsuffixOnPrev' => 0,
        'acceptHTMLsuffix' => 1,
        'index' => [
            'feed.rss' => [
                'keyValues' => [
                    'type' => $rssFeedPageType,
                ]
            ]
        ]
    ],

    'preVars' => array(
        0 => array(
            'GETvar' => 'L',
            'valueMap' => array(
                'en' => 0,
                'cy' => 1,
            ),
            'noMatch' => 'bypass',
        ),
    ),

    'fixedPostVars' => array(
        'newsDetailConfiguration' => array(
            array(
                'GETvar' => 'tx_news_pi1[action]',
                'valueMap' => array(
                    'story' => '',
                ),
                'noMatch' => 'bypass'
            ),
            array(
                'GETvar' => 'tx_news_pi1[controller]',
                'valueMap' => array(
                    'news' => '',
                ),
                'noMatch' => 'bypass'
            ),
            array(
                'GETvar' => 'tx_news_pi1[news]',
                'lookUpTable' => array(
                    'table' => 'tx_news_domain_model_news',
                    'id_field' => 'uid',
                    'alias_field' => 'title',
                    'addWhereClause' => ' AND NOT deleted',
                    'useUniqueCache' => 1,
                    'useUniqueCache_conf' => array(
                        'strtolower' => 1,
                        'spaceCharacter' => '-'
                    ),
                    'languageGetVar' => 'L',
                    'languageExceptionUids' => '',
                    'languageField' => 'sys_language_uid',
                    'transOrigPointerField' => 'l10n_parent',
                    'autoUpdate' => 1,
                    'expireDays' => 180,
                )
            )
        ),
        'newsCategoryConfiguration' => array(
            array(
                'GETvar' => 'tx_news_pi1[overwriteDemand][categories]',
                'lookUpTable' => array(
                    'table' => 'sys_category',
                    'id_field' => 'uid',
                    'alias_field' => 'title',
                    'addWhereClause' => ' AND NOT deleted',
                    'useUniqueCache' => 1,
                    'useUniqueCache_conf' => array(
                        'strtolower' => 1,
                        'spaceCharacter' => '-'
                    )
                )
            )
        ),
        'newsTagConfiguration' => array(
            array(
                'GETvar' => 'tx_news_pi1[overwriteDemand][tags]',
                'lookUpTable' => array(
                    'table' => 'tx_news_domain_model_tag',
                    'id_field' => 'uid',
                    'alias_field' => 'title',
                    'addWhereClause' => ' AND NOT deleted',
                    'useUniqueCache' => 1,
                    'useUniqueCache_conf' => array(
                        'strtolower' => 1,
                        'spaceCharacter' => '-'
                    )
                )
            )
        ),

        '4' => 'newsDetailConfiguration', // ID of the page with the news plugin detail view

    ),

    'postVarSets' => [
        '_DEFAULT' => [
            'controller' => [
                [
                    'GETvar' => 'tx_news_pi1[action]',
                    'noMatch' => 'bypass'
                ],
                [
                    'GETvar' => 'tx_news_pi1[controller]',
                    'noMatch' => 'bypass'
                ]
            ],

            'dateFilter' => [
                [
                    'GETvar' => 'tx_news_pi1[overwriteDemand][year]',
                ],
                [
                    'GETvar' => 'tx_news_pi1[overwriteDemand][month]',
                ],
            ],
            'page' => [
                [
                    'GETvar' => 'tx_news_pi1[@widget_0][currentPage]',
                ],
            ],
        ],
    ],

];

Using TYPO3 v8.7.15,RealURL 2.3 and News v7.0.4
RealUrl is set to use my manual conf file also.
Thanks again T3 community

A:

realUrl Provide pretty nice option to exclude a page from URL segment. For that go to Page-> property->General. You will find an option Exclude from speaking URL check this Screenshot.
In your case go to story page and exclude this from URL
-root(1)
--Home (2)
--News (3)
---Story (4) // Exclude from realUrl

That's it, this what you're actually looking for!
Greetings!


Q:

What tag is suitable for this question?

I asked a question on English SE and a user said that it is more suitable here. However, I am unable to post the question on Math SE because I don't know what tag to use.

A:

The tag terminology seems most appropriate to your question; the tag-wiki says

Questions on the usage and meaning of words in mathematics, the names for mathematical entities, and other such questions.


Q:

Getopts option processing, Is it possible to add a non hyphenated [FILE]?

I'm using getopts for all of my scripts that require advanced option parsing, and It's worked great with dash.  I'm familiar with the standard basic getopts usage, consisting of [-x] and [-x OPTION].
Is it possible to parse options like this?
 dash_script.sh FILE -x -z -o OPTION
 ## Or the inverse?
 dash_script.sh -x -z -o OPTION FILE

A:

Script arguments usually come after options. Take a look at any other commands such as cp or ls and you will see that this is the case.
So, to handle:
dash_script.sh -x -z -o OPTION FILE

you can use getopts as shown below:
while getopts xzo: option
do
    case "$option" in
        x) echo "x";;
        z) echo "z";;
        o) echo "o=$OPTARG";;
    esac
done
shift $(($OPTIND-1))
FILE="$1"

After processing the options, getopts sets $OPTIND to the index of the first non-option argument which in this case is FILE.


Q:

Pad a C++ structure to a power of two

I'm working on some C++ code for an embedded system.  The I/O interface the code uses requires that the size of each message (in bytes) is a power of two.  Right now, the code does something like this (in several places):
#pragma pack(1)
struct Message
{
   struct internal_
   {
      unsigned long member1;
      unsigned long member2;
      unsigned long member3;
      /* more members */
   } internal;
   char pad[64-sizeof(internal_)];
};
#pragma pack()

I'm trying to compile the code on a 64-bit Fedora for the first time, where long is 64-bits.  In this case, sizeof(internal_) is greater than 64, the array size expression underflows, and the compiler complains that the array is too large.
Ideally, I'd like to be able to write a macro that will take the size of the structure and evaluate at compile time the required size of the padding array in order to round the size of the structure out to a power of two.
I've looked at the Bit Twiddling Hacks page, but I don't know if any of the techniques there can really be implemented in a macro to be evaluated at compile time.
Any other solutions to this problem?  Or should I perpetuate the problem and just change the magical 64 to a magical 128?

A:

Use a template metaprogram. (Edited in response to comment).
#include <iostream>
#include <ostream>
using namespace std;

template <int N>
struct P
{
    enum { val = P<N/2>::val * 2 };
};

template <>
struct P<0>
{
    enum { val = 1 };
};

template <class T>
struct PadSize
{
    enum { val = P<sizeof (T) - 1>::val - sizeof (T) };
};

template <class T, int N>
struct PossiblyPadded
{
    T       payload;
    char    pad[N];
};

template <class T>
struct PossiblyPadded<T, 0>
{
    T       payload;
};

template <class T>
struct Holder : public PossiblyPadded<T, PadSize<T>::val>
{
};

int main()
{
    typedef char Arr[6];

    Holder<Arr> holder;
    cout << sizeof holder.payload << endl;

    // Next line fails to compile if sizeof (Arr) is a power of 2
    // but holder.payload always exists
    cout << sizeof holder.pad << endl;
}

A:

Probably the most obvious way would be to just use the ternary operator:
#define LOG2_CONST(n) ((n) <= 1 ? 0 :
                      ((n) <= 2 ? 1 :
                      ((n) <= 4 ? 2 :
                      /* ... */
                      ))))))))))))))))))))))))))))))
#define PADDED_STRUCT(ResultName, BaseName) \
  typedef union { BaseName data; char pad[1 << LOG2_CONST(sizeof(BaseName))]; } ResultName

A:

Why not use a union?
union Message
{
    struct internal_
    {
        unsigned long member1;
        /* more members */
    };
    char[64];
};

or better yet use anonymous structs
union Message
{
    struct
    {
        unsigned long member1;
        /* more members */
    };
    char[64];
};

So you can access members like this: Message.member1;
Edit: obviously this doesn't solve your greater than 64 problem, but provides a cleaner way of padding.


Q:

help synthesizing cicadas

https://soundcloud.com/eduardopolitzer/cigarra-premix
Hi audio-people
I've been trying to create from scratch some cicada sounds, maybe someone here can help me in this crazy idea.
the link above is an idea of how far I've gone so far.
I've done that in Reason and protools using only subtractive synthesis and HP filtering.
So... any ideas?

A:

What analysis have you done of real cicadas? if you pitch/slow them down you can hear the rhythm of their individual stridulations, so that would a good starting point... Your version sounds very smeared, rather than percussive....
http://www.musicofsound.co.nz/blog/cicadas-meet-pitch-shift
Of course it also depends exactly what cicada you are trying to create - their sound varies hugely depending on species ie cicadas in NZ sound nothing like cicadas in Japan


Q:

Ruby on rails get mac address

I want to get mac address from user in a form, but I don't know is there a simple way to get it, or I have to get with using 6 text field.
Update:

Jquery

$(document).on('ready page:load', function() {
   $('.field-id').mask('00:00:00:00:00:00', {'translation': {0: {pattern: /[a-z0-9]/}}});

});

Form view

<%= f.text_field :comp_id, class: "field-id" %>

I don't understand why it is not working

A:

You can use jQuery for client-side input mask. Here is the jQuery plugin just for this: http://igorescobar.github.io/jQuery-Mask-Plugin/
In case of MAC address, the field masking might look like this:
$('#field-id').mask('00:00:00:00:00:00', {'translation': {0: {pattern: /[a-z0-9]/}}});


Q:

Custom PDO Class Fails Quietly

For some reason, this custom PDO class fails to write to the database.  It simply quietly fails - no error message thrown.  A very similar custom PDO class (ReadPDO) works wonderfully for reading from the database.  The SQL statement generated works fine when it's queried to the DB through PHPMyAdmin.  I've double-checked the user permissions, and everything seems in order.
I suspect I'm misunderstanding how something works.  Any ideas?
// Creates a write-only PDO, using config settings from inc_default.php
class WritePDO extends PDO{

    public function __construct(){
        //Pull global DB settings
        global $db;
        global $write_host;
        global $write_username;
        global $write_password;

        try{
            parent::__construct("mysql:dbname={$db};host={$write_host}", $write_username, $write_password);
        } catch (PDOException $e){
            echo 'Connection failed: ' . $e->getMessage();
        }
    }
}

private function updatePlayer(){
    $conn = new WritePDO();
    $sql = "UPDATE {$this->hvz_db}
        SET
        hvz_bitten      ='{$this->hvz_bitten}',
        hvz_died        ='{$this->hvz_died}',
        hvz_feedCode    ='{$this->hvz_feedCode}',
        hvz_status      ='{$this->hvz_status}',
        hvz_feeds       ='{$this->hvz_feeds}',
        hvz_lastFed     ='{$this->hvz_lastFed}',
        hvz_ozOpt       ='{$this->hvz_ozOpt}',
        hvz_parent      ='{$this->hvz_parent}'
        WHERE users_id  ={$this->id}";
    $query = $conn->exec($sql);
}

The SQL it spits out is as follows:
UPDATE hvz_2011_spring SET hvz_bitten ='', hvz_died ='', hvz_feedCode ='NOMNOM', hvz_status ='Human', hvz_feeds ='0', hvz_lastFed ='', hvz_ozOpt ='0', hvz_parent ='' WHERE users_id =1

A:

are you sure the sql is correct?
The exec doesn't send any error message.
Try doing var_dump($conn->errorInfo()); after $conn->exec($sql);
/Emil


Q:

Table Pivot in SQL Server

I have a table of phone numbers connected to persons, and the numbers are already partitioned by the person ID:
person_id   number      row_count
1           5556667777  1
1           5435346523  2
1           7645634344  3
2           5556667777  1
2           5435346523  2
3           7645634344  1

The amount of numbers per person can reach up to twenty, but I already have them sequenced by priority, and want to make five columns of the first five numbers per person, leave null the empty colums and ignore numbers past the fifth column:
person_id   num_1       num_2       num_3       num_4       num_5
1           5556667777  5435346523  7645634344  null        null
2           5556667777  5435346523  null        null        null
3           7645634344  null        null        null        null

I have been looking around and it looks like pivot is the right command, but I can't wrap my head around a similar enough example to fully understand it.

A:

PIVOT takes some time to get comfortable with, but luckily your case is a pretty straightforward example:
SELECT person_id, [1] Num_1,[2] Num_2,[3] Num_3,[4] Num_4,[5] Num_5
FROM Table1
PIVOT(MAX(number) FOR row_count IN ([1],[2],[3],[4],[5]))pvt

Demo: SQL Fiddle
Since you're only using 5 numbers and ignoring the rest, it's easy enough to hard-code in the 5 values used, but this can also be done dynamically.


Q:

Resultant motion

if a body/a ball is travelling in a straight line with a constant velocity and I suddenly apply a finite force on it, perpendicular to its direction of motion, then it acquires a resultant motion and follows a diagonal path. I am new to physics and I am finding it quite hard to visualise how its happening. My real question is that in the very small moment when the force is applied, what is happening to the ball that makes it follow the diagonal path?

A:

A practical example of the deflection that you describe is that of an electron in a uniform electric field.
On entering the region in which the electric field acts the electron is subjected to a constant force and hence a constant acceleration.
The trajectory of the electron in the electric field is parabolic and when the electron leaves the region in which the electric field acts the elecron moves in a straight line.
Here is a demonstration of the effect.
That region over which the electric field acts can be as large or as small as you like.

An analysis of the motion can be found here with the motion in the electric field being a constant velocity perpendicular to the electric field so the displacement is proportional to the time of travel and constant acceleration along the direction of the electric field so the displacement is proportional to the time of travel squared.
This combination of the two perpendicular motions produces a parabolic path.
This is the same trajectory as that of a projectile in a uniform gravitational field.


Q:

Largest subset with no pair summing to power of two

For positive integer $n$, define the set $A_n=\{0,1,\ldots,n\}$. What is the size of the largest subset of $A_n$ such that the sum of any two (not necessarily distinct) elements in it is not a power of $2$?
So, a power of $2$ can never be chosen. For $n=3,4,5$, the set $\{0,3\}$ is the best possible, and for $n=6,7$ we can choose $\{0,3,6\}$ and $\{0,3,6,7\}$, respectively.

A:

This is a partial solution. Nevertheless, I hope it helps somehow.
Consider the same problem, but now $A_n=\{1,\ldots,n\}$. We always can add $0$ at the end.
I have a solution when $n$ is itself a power of two, say $n=2^k$. A set in this case is
$$2^{k-1}+1,2^{k-1}+2,\ldots,2^k-1$$
The sum of two of these numbers is $\ge2(2^{k-1}+1)=2^k+2>2^k$ and $\le 2(2^k-1)=2^{k+1}-2<2^{k+1}$. So never is a power of two. But in this set there are
$$2^{k-1}-1$$
numbers. Let's show that this is the greatest possible size.
If there is a set with $2^{k.-1}$ elements, then at least one of them, say $a_1$, is lesser than $2^{k-1}$. But then, $2^k-a_1$ can not be in the set. Therefore, there must be another element $a_2$ lesser than $2^{k-1}$, etc.
We conclude that every element is lesser than $2^{k-1}$, a contradiction.
Now we can add the number $0$, so the solution is $2^{k-1}$.


Q:

WPF treeview with heirarchical databinding using multiple data sources

I have this wpf structure:
 <TreeView x:Name="tree" ItemsSource="{Binding MainDirectory}">
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding _directory}">
                        <TreeViewItem Header="{Binding _name}" >
                        </TreeViewItem>
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>

 </TreeView>

My directories display great but my _directory property also have a _file property that I want to display inside the treeview. Whenever I try to add another treeviewitem though WPF tells me that the visual tree is set more than once. Is there any way I can achieve this. Thank you

A:

Here you go:
<TreeView x:Name="tree" ItemsSource="{Binding MainDirectory}">
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding _directory}">
                         <HierarchicalDataTemplate.ItemTemplate>
                              <HierarchicalDataTemplate ItemsSource="{Binding _file}">
                                   <TreeViewItem Header="{Binding _name}" />
                              </HierarchicalDataTemplate>
                         </HierarchicalDataTemplate.ItemTemplate>
                        <TreeViewItem Header="{Binding _name}" >
                        </TreeViewItem>
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>

 </TreeView>


Q:

access viewModel properties

Is it possible to access viewModel properties at any time in any script on the page? In the model below I want to use currModel as a place to store a certain flag, can I do this without binding it to something in DOM? Thx for any help.
function viewModel(result,currentTheme) {
    var self = this;
    self.isBlankForm = !(result.payload.isBlankForm);
    self.snapEdit = result.payload.emailText;
    self.snapEditSuccess = result.payload.successBody;
    self.isMeNotified = result.payload.isMeNotified;
    self.isEmailSentToUser = result.payload.isEmailSentToUser;
    self.fromEmailBox = result.payload.fromUserEmail;
    self.subjectEmailBox = result.payload.emailSubject;
    self.themeNames = ko.observableArray(result.payload.themeList);
    self.themeChoice = ko.observable(self.themeNames.find("id", currentTheme));
    self.bgColor = result.payload.bgColor;
    self.frmColor = result.payload.frmColor;
    self.txtColor = result.payload.txtColor;
    self.btnColor = result.payload.btnColor;
    self.btnTxtColor = result.payload.btnTxtColor;
    self.currModel = ko.observable();
}

A:

Sure, just store your VM in a variable.
For example:
var myVM = new viewModel();
ko.applyBindings(myVM);

Now you can access myVM.currModel() whenever you need it.


Q:

MySQL claims that a built-in function "does not exist."

Tell me what's wrong in these two queries?
SELECT * FROM `product_description` WHERE CHAR_LENGTH (description) > 250
SELECT * FROM `product_description` WHERE LENGTH (description) > 250

They return these error
Function table.name CHAR_LENGTH does not exist
Function table.name LENGTH does not exist

both functions seems not to work... what is going on ?

A:

Maybe it is this which causes the issue
By default there must be no whitespace between a function name and the parenthesis following it. This helps the MySQL parser distinguish between function calls and references to tables or columns that happen to have the same name as a function. However, spaces around function arguments are permitted.


Q:

Using SSB to send and receive more than one message in a conversation

There are occasions that I need to group some of my messages together so that they can be processed in order by my worker processes.
But every single example that I find shows only how to do one message per conversation.
What I am looking for is an example that sends more than one message in a conversation AND a an example that shows how to process them too.  (I may be sending them both, but I only seem to be able to get one back out.)

A:

A conversation provides the boundary within which messages are processed in order - so you need to SEND all the messages in the group with the same ConversationId. The way I do this is with a utility table that stores the ConversationId when created so that each time a message is sent, it looks up the appropriate conversationid to send it on.
SELECT @conversationHandle = ConversationHandle FROM Qproc.SessionConversation
WHERE
FromService = @fromService
AND ToService = @toService
AND OnContract = @onContract
AND Terminated IS NULL

IF @conversationHandle IS NULL
BEGIN
    BEGIN DIALOG CONVERSATION @conversationHandle
        FROM SERVICE @fromService
        TO SERVICE @toService
        ON CONTRACT @onContract
        WITH ENCRYPTION = OFF; --, LIFETIME = 60*60*24*100;

    -- Store the ongoing conversation for further use
    INSERT INTO QProc.SessionConversation ( FromService, ToService, OnContract,ConversationHandle)
    VALUES(     @fromService,   @toService, @onContract,    @conversationHandle )
END

    -- Create the dialog timer, timeout is seconds; this will notify the ClientQueue if nothing has happened on the conversation
    --in the timeout period
    BEGIN CONVERSATION TIMER (@conversationHandle) TIMEOUT = 60*8;
    SEND ON CONVERSATION @conversationHandle
    MESSAGE TYPE [http://COMPANYNAME/AsyncTriggerRequestMesssage]
        (@messageBody);

The reason you only see one message at the other end is to do with conversation group locking - you should read up on this to understand what is going on, but basically once a message processing procedure has seen a message, its view on the message queue is restricted to a single conversation. This won't be an issue once you reuse the same conversationID. Here is an example receive:
DECLARE @RecvReqDlgHandle UNIQUEIDENTIFIER;
DECLARE @RecvReqMsg VARCHAR(8000);
DECLARE @RecvReqMsgName sysname;

WHILE (1=1)
    BEGIN
        BEGIN TRANSACTION;

        WAITFOR
        ( RECEIVE TOP(1)
            @RecvReqDlgHandle = conversation_handle,
            @RecvReqMsg = message_body,
            @RecvReqMsgName = message_type_name
          FROM  QProc.AsyncTaskServiceQueue
        ), TIMEOUT 500;

        IF @@ROWCOUNT=0
        BEGIN
            ROLLBACK TRANSACTION;
            BREAK
        END

        IF @RecvReqMsgName = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'
            BEGIN
            END CONVERSATION @RecvReqDlgHandle;
            END

        IF @RecvReqMsgName='http://COMPANYNAME/AsyncTriggerRequestMesssage'
            BEGIN
                DECLARE @BodyDoc XML;
                SET @BodyDoc=CONVERT(XML, @RecvReqMsg)  ;
                EXEC QProc.AsyncTaskRunTask @BodyDoc;

            END

        COMMIT TRANSACTION;

    END

FInally, you'll need to clean those conversations up once they're no longer used, something like this:
DECLARE @conversationHandle UNIQUEIDENTIFIER;
DECLARE @messageTypeName SYSNAME;

BEGIN TRANSACTION;

RECEIVE TOP(1)
    @conversationHandle = conversation_handle,
    @messageTypeName = message_type_name
FROM QProc.AsyncTaskClientQueue;

IF @conversationHandle IS NOT NULL
BEGIN
    --If the DialogTimer message arrives, then there has been no activity on this conversation for a while (see timeout setting in [QProc].[DispatchAsyncTaskMessage])
    --so we terminate gracefully and go home.

    IF @messageTypeName = 'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer'
    OR @messageTypeName = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'
    BEGIN
        END CONVERSATION @conversationHandle;
        UPDATE Qproc.SessionConversation SET TERMINATED = getUtcDate() WHERE ConversationHandle = @conversationHandle;

    END
    END

COMMIT TRANSACTION;


Q:

ios NSDateFormatter in restkit

I'm dealing with times formats in Restkit, I have a web service that returns to me objects in JSON format, I have no problem parse the objects I receive in exception on the date that comes in this format:
"date_expiration":"2012-04-22T11:33:28+0200"

I read some posts about it and I have understand that rest kit don't have this format to parse the date so I have to add a new format. So I do it with this code:
    [RKManagedObjectMapping addDefaultDateFormatterForString:@"yyyy-MM-ddTHH:mm:ssT" inTimeZone:nil];

But it don't works. I have read a very useful web page about time formatters:

http://waracle.net/mobile/iphone-nsdateformatter-date-formatting-table/

Hear it shows how to format a date but it's two things I don't know how to do: How I jump the character T before the hours? For this time zone T is the correct code? Thanks for your help

A:

The T in the date is a separator. It has to be put in ' '
The specifier for the timezone is Z
 @"yyyy-MM-dd'T'HH:mm:ssZ"


Q:

PHP Multidimentional Array Sort into 15 minute intervals

I am trying to sort a Multidimentional array into 15 minute increments with the following data, this is data from a Call Center Database for phone records
CallID      CallDateTime                    IsLost  IsAnswered
82650       May 10 2016 08:55:01:000AM      0       1
82666       May 10 2016 09:03:13:000AM      0       1
82677       May 10 2016 09:07:45:000AM      0       1
82688       May 10 2016 09:12:19:000AM      0       1
82689       May 10 2016 09:14:42:000AM      0       1
82702       May 10 2016 09:22:08:000AM      0       1
82708       May 10 2016 09:26:26:000AM      0       1
82737       May 10 2016 09:39:42:000AM      0       1
82739       May 10 2016 09:43:17:000AM      0       1
82748       May 10 2016 09:45:22:000AM      0       1
82786       May 10 2016 09:59:26:000AM      0       1
82789       May 10 2016 10:00:21:000AM      0       1
82820       May 10 2016 10:26:52:000AM      0       1
82842       May 10 2016 10:37:14:000AM      0       1
82846       May 10 2016 10:39:04:000AM      0       1
82859       May 10 2016 10:48:30:000AM      0       1
82865       May 10 2016 10:50:18:000AM      0       1
82880       May 10 2016 10:56:47:000AM      0       1
82911       May 10 2016 11:07:30:000AM      0       0
82925       May 10 2016 11:15:34:000AM      0       1
82926       May 10 2016 11:16:08:000AM      0       1
82927       May 10 2016 11:16:17:000AM      0       1
82943       May 10 2016 11:23:16:000AM      0       1
82944       May 10 2016 11:25:54:000AM      0       1
82947       May 10 2016 11:26:48:000AM      0       1
82966       May 10 2016 11:33:27:000AM      0       1
83048       May 10 2016 12:14:39:000PM      0       1

That I get from an MSSQL Server Database, placing data in via the following PHP Code
 $sql = "SELECT CallID, CallDateTime, IsLost, IsAnswered FROM vwCustomReportingCallsMain WHERE DDI = '2399' AND datediff(day, CallDateTime, '2016-05-10') = 0 ORDER BY CallDateTime ASC";
foreach ($dbh->query($sql) as $row)
    {
        if($row['CallID'] != $last) {
            $callDataArray[] = array("CallID" => $row['CallID'], "CallDateTime" => $row['CallDateTime'], "IsLost" => $row['IsLost'], "IsAnswered" => $row['IsAnswered']);
        }
        $last = $row['CallID'];
    }

The desired output would be like the following format somehow (data not correct)
Date/Time           IsAnswered IsLost
May 10 2016 08:30   7          0
May 10 2016 09:00   8          0
May 10 2016 09:30   14         0
May 10 2016 10:00   11         0
May 10 2016 10:30   11         0
May 10 2016 11:00   13         0
May 10 2016 11:30   12         0
May 10 2016 12:00   11         0
May 10 2016 12:30   8          0
May 10 2016 13:00   20         0
May 10 2016 13:30   9          0
May 10 2016 14:00   10         0
May 10 2016 14:30   12         0
May 10 2016 15:00   8          0
May 10 2016 15:30   14         0
May 10 2016 16:00   12         0
May 10 2016 16:30   11         0

Any ideas on how to in PHP or even MSSQL PDO ?
Any help would be awesome - Cheers

A:

You can use the following code. It may not be perfect but it will give you an idea on how to proceed further.
function roundToNearest30($timestring) {
    $minutes = date('i', $timestring);
    return sprintf("%02d", $minutes - ($minutes % 30));
}

$totalArray = array();
$lastTime = NULL;
foreach($callDataArray as $callData){
    $timeString = strtotime($callData['CallDateTime']);
    $currentHour = date('H', $timeString);
    $nearest30Minutes = roundToNearest30($timeString);
    $nearestTime = "{$currentHour}:{$nearest30Minutes}";

    //create array key based on nearest 30 minutes
    if (!isset($totalArray[$nearestTime])){
        //add the array element as it does not exist
        $totalArray[$nearestTime] = array("TotalLost" => $callData['IsLost'], "TotalAnswered" => $callData['IsAnswered']);
    }else{
        //update they array element with previous data
        $totalArray[$nearestTime]["TotalLost"] += $callData['IsLost'];
        $totalArray[$nearestTime]["TotalAnswered"] += $callData['IsAnswered'];
    }
}

foreach($totalArray as $nearest30 => $data){
    echo "{$nearest30}, Total Lost: {$data['TotalLost']}, Total Answered: {$data['TotalAnswered']}";
    echo "<br>";
}

Output:
08:30, Total Lost: 0, Total Answered: 1
09:00, Total Lost: 0, Total Answered: 6
09:30, Total Lost: 0, Total Answered: 4
10:00, Total Lost: 0, Total Answered: 2
10:30, Total Lost: 0, Total Answered: 5
11:00, Total Lost: 0, Total Answered: 6
11:30, Total Lost: 0, Total Answered: 1
12:00, Total Lost: 0, Total Answered: 1