Q:

npm audit Arbitrary File Overwrite

I recently updated my version of angular using ng update
and when running npm audit it found 1 high severity vulnerability but offered no suggestions on how to resolve it. It usually suggests to upgrade a package from package.json like: "angular-devkit/build-angular" but I am already using their latest version.
                   === npm audit security report ===

                             Manual Review
         Some vulnerabilities require your attention to resolve

      Visit https://go.npm.me/audit-guide for additional guidance

High            Arbitrary File Overwrite

Package         tar

Patched in      >=4.4.2

Dependency of   @angular-devkit/build-angular [dev]

Path            @angular-devkit/build-angular > node-sass > node-gyp > tar

More info       https://npmjs.com/advisories/803

found 1 high severity vulnerability in 29707 scanned packages
1 vulnerability requires manual review. See the full report for details.

I thought of installing npm i tar but I am not sure.

A:

angular-cli relies on node-gyp, who have an open issue for this: https://github.com/nodejs/node-gyp/issues/1714
To work around, you can patch node-gyp and then patch angular to use your patched node-gyp. Or wait and hope that they will fix it soon.

A:

The following worked for me:
Go to node_modules > node_gyp > package.json, then locate tar under dependencies and replace 2.0.0 with 4.4.8.
Then run:

npm i
npm audit
npm audit fix
npm audit

you should see 0 vulnerabilities.
I've updated a few angular projects and each project had the same issue. Doing the above worked all the time.


Q:

Gulp reloads same file many times

I am using gulp to run both client and server in my project. In the terminal, seems like the same files are reloaded many times. What could be the reason and how to fix this?
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/_runMainLayout.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/_runMainLayout.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/_runMainLayout.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/_runMainLayout.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/_runMainLayout.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/_runMainLayout.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/getData.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/getData.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/getData.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/getData.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/getData.js reloaded.
[12:00:03] /Users/verinasutd/Dev/Projects/metaBranch1/app/js/getData.js reloaded.
At the same time also nodemon, notify, live-reload. It does feel excessive however this was the way somehow that could work the last time the project was developed. Below is the gulpfile.
// gulpfile.js
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');

var notify = require('gulp-notify');
var livereload = require('gulp-livereload');
var webpack = require('webpack-stream’);

gulp.task('js', function () {
   gulp.src('./app/js/*.js')
    .pipe(livereload());
});

gulp.task('watch', function () {
   livereload.listen();
   gulp.watch(['./app/js/*.*'], ['js']); //update
});

gulp.task('server', function(){
   // listen for changes
   livereload.listen();
   // configure nodemon
   nodemon({
     // the script to run the app
     script: 'run.js',
     ext: 'js'
   }).on('restart', function(){
   // when the app has restarted, run livereload.
     gulp.src('run.js')
       .pipe(livereload());
   })
 });

 gulp.task('client', function(){

 gulp.src('./app/js/es6/main.js') //'src/entry.js'
   .pipe(webpack( require('./webpack.config.js') ))
   .pipe(gulp.dest(__dirname + '/app/js'))
   .pipe(livereload());

 });

 gulp.task('default', function() {
 });

 gulp.task('default', ['server','client','watch']);

A:

The server task:
There is no real reason to start a livereload server, which is mean to notify the client if any front-end components have updated, from a task that is supposed to only start the back-end server.
Also, from gulp-livereload's npm page:

livereload.listen([options])
  Starts a livereload server. It takes an optional options parameter that is the same as the one noted above. Also you dont need to worry with multiple instances as this function will end immidiately if the server is already runing.

So basically either this server, or the one you start in the watch task, are killed on start, so why even bother starting both?
Also on the nodemon section of this task you're loading your server's entry point and piping it to the livereload server.

livereload([options])
  Creates a stream which notifies the livereload server on what changed.

What you're doing is telling the livereload server to notify the client that the server script has updated, while this script is not even present in the client bundle (why would it?).
If your intent whas to reload the page when the server script updates, you should have used instead the livereload.reload() method:

livereload.reload([file])
  You can also tell the browser to refresh the entire page. This assumes the page is called index.html, you can change it by providing an optional file path or change it globally with the options reloadPage.

The client task:
Nice thing about webpack-stream is that if you set watch: true in it's config, he will automatically watch for changes and pipe the recompiled bundle every time.
In short you don't need all the gulp.watch(...) stuff.
Reordering the tasks:
We are at the point where the js task is completely pointless, and the watch task only runs the livereload server.
Also the client task only compiles the javascript, which doesn't make much sense.
IMHO it would be wise to rename the client task to js, then create a js:watch task that also watches for changes.
Then working a bit on task dependencies we could say that we want a client task that runs all the tasks that prepare our client files (html, styles, scripts,... ), and we can define it as follows:
gulp.task('client', ['js']);

Then we know that the watch task depends on the client files, as it's role is to monitor them for changes. So we write:
gulp.task('watch', ['client', 'js:watch'], function () {
    livereload.listen();
}

Then, thanks to the new established dependency system, we can define the default task as follows:
gulp.task('default', ['server', 'watch']);

Conclusion
You can see a full revision of your build script on pastie.
This is not meant to be a final/optimal/perfect solution, it just makes everything a bit more clear on how it works and how it interacts with other tasks/components.
I'd like to add that gulp's build script is a simple js file interpreted by node, so you could use the es6 features natively implemented by the v8 engine (const/let, arrow functions and much more).


Q:

Is it better to avoid OR clauses in database queries?

Assume I have a database set up and a table named MyTable which contains a large number of records (tens of thousands). Assume a query as follows...
select * from MyTable where ColumnX = 'X'

... returns just a handful of records (< 10). Let's say I wanted to filter this result set further to only those records where ColumnY matches 'Y1' or 'Y2'. Is it better from a speed and memory perspective to simply modify to the above query as follows...
select * from MyTable where ColumnX = 'X' and (ColumnY = 'Y1' or ColumnY = 'Y2')

... Or is it better to iterate over the (small) result set in code and filter out only those records where ColumnY matches 'Y1' or 'Y2'? The reason I ask is because I have been told that OR clauses are bad in database queries from a performance perspective (when dealing with large tables) and better avoided where possible.

Note: The scenario in which this applies for me is an Android application with a local SQLite database but I guess the question is a bit more generic than that.

A:

SQLite's documentation describes multiple optimizations that can be done on queries with OR, and says:

For any given query, the fact that the OR-clause optimization described here can be used does not guarantee that it will be used. SQLite uses a cost-based query planner that estimates the CPU and disk I/O costs of various competing query plans and chooses the plan that it thinks will be the fastest. If there are many OR terms in the WHERE clause or if some of the indices on individual OR-clause subterms are not very selective, then SQLite might decide that it is faster to use a different query algorithm, or even a full-table scan. Application developers can use the EXPLAIN QUERY PLAN prefix on a statement to get a high-level overview of the chosen query strategy.

In any case, implementing the OR by hand in your code is very likely to be slower than letting the database do it, because the database has to read and return all rows that match on ColumnX, even those that will not match on ColumnY.
Furthermore, the database already has code to do this filtering; implementing it again just increases the complexity of your code and the chances of errors.
The statement that "OR clauses are bad in database queries from a performance perspective (when dealing with large tables) and better avoided where possible" is not quite true; if you need the OR, all alternatives are worse.


Q:

Variable page height with wkhtmltopdf

I'm trying to print various receipts using wkhtmltopdf (using the webkit reporting tool in openERP).
I have a receipt printer that has a continuous roll of paper. The printer automatically cuts the paper on a page break. This works great on receipts where the height of the "page" is always the same, but I can't figure out how to set the height dynamically on individual pages.
Ideally I want to put a page-break-after:always css command after every receipt and for wkhtmltopdf to set the height of the page to match the height of the content.
I'm guessing the only way is to hack the source code on https://github.com/antialize/wkhtmltopdf but hoping someone has already solved this problem.

A:

I would suggest taking a look at: https://github.com/AAverin/JSUtils/tree/master/wkhtmltopdfTableSplitHack
From what I understand, you would only need to define a specific class to your HTML table element, and the JS script would do the rest.
Also, you might want to look at theses (which eventually lead me to the first link)

https://gist.github.com/niflostancu/3683510
https://gist.github.com/bluntelk/5573089


Q:

Java generics and typecasting

I have a badly created container object that holds together values of different java types(String, Boolean etc ..)
public class BadlyCreatedClass {
    public Object get(String property) {
        ...;
    }
};

And we extract values from it in this way
String myStr = (String) badlyCreatedObj.get("abc");
Date myDate = (Date) badlyCreatedObj.get("def");

I am forced to write some new code using this object and I am trying to see if there is clean way to do this. More specifically which method from the below is preferred ?
Explicit Cast
String myStr = (String) badlyCreatedObj.get("abc")
Date myDate = (Date) badlyCreatedObj.get("def");

Using generic cast
public <X> X genericGet(String property) {

}

public String getString(String property) {
return genericGet(property);
}

public Date getDate(String property) {
return genericGet(property);
}

Using Class.cast
<T> T get(String property, Class<T> cls) {
    ;
}

I have gone through several related questions on SO Java generic function: how to return Generic type , Java generic return type all of them seem to say the such typecasting is dangerous, ALthough I dont see much difference between the three, given this which method would you prefer ?
Thanks

A:

To give a quick answer, without going in deep about good-programming-practice...
I would use:
private <X> X genericGet(String property) {

}

public String getString(String property) {
//... checks on property (String specific)...
Object obj = genericGet(property);
//... checks if obj is what is expected and if good return it
return obj;
}

public Date getDate(String property) {
//... checks on property (Date specific)...
Object obj = genericGet(property);
//... checks if obj is what is expected and if good return it
return obj
}

make notice to the private genericGet.
This way I can check if the get property is what I m waiting to receive and handle it in a correct way.
I could add checks in the getString depends on the property to make sure that the answer will be a String object.
I could do other checks for getDate in property to make sure it will be a date as will be returned.
Etc...

A:

Personally, keeping lots of different objects in a single place and then checking what you want to return seems a bit wrong. May be you can store Holders in that BadlyCreatedClass.
Something like:
class Holder {
    private long id;
    private String name;
    private Date dateofBirth;

    //getters and setters
}

Then retrieve based on id, no casting thus required.
You could also tell us what you are trying to do.

A:

The generic cast approach causes the compiler to emit an unchecked warning. An unchecked warning indicates that the cast is question is not (fully) checked at runtime, i.e. it may succeed, even if the value is not of the proper type. This can cause a variable to hold a value not compatible with its declared type, a situation the Java Language Specification calls heap pollution.
The following program demonstrates this:
class Holder {
    Object value;

    Holder(Object value) {
        this.value = value;
    }

    <T> T get() {
        return (T) value;
    }
}

class C<T> {
    T value;

    C(Holder h) {
        value = h.get();
    }
}

public class Test {
    public static void main(String [] args) throws IOException {
        Holder holder = new Holder("Hello");
        C<Integer> c = new C<Integer>(holder);
        System.out.println("I just put a String into a variable of type Integer");

        // much later, possibly in a different part of your program
        c.value.longValue(); // throws ClassCastException
    }
}

Therefore, I strongly recommend using a checked cast. Both the ordinary cast (your first approach), and the reflective cast (your third approach) are checked. However, the reflective cast will not work with parametrized types (List<String>.class doesn't compile ...).
The simplest and most flexible safe solution therefore is the ordinary cast.


Q:

Get second smallest number(s) in sql column

I currently have the code below and it works for getting me the 2 smallest number, but I want to get all of the 2nd smallest numbers and link them to their name as opposed to just one of them. lets say the numbers in the tables was made up of this:
Name| number
----|------
w     2
a     8
s     2
e     2
z     3

I would want to get
w 2
s 2
e 2

and now I am just getting w 2
SELECT MAX(col) FROM table WHERE col NOT IN (SELECT MAX(col) FROM table);

A:

If this code gets you the second smallest number (what you want):
SELECT MAX(col) FROM table WHERE col NOT IN (SELECT MAX(col) FROM table);

Then simply do:
select *
from table
where col = (SELECT MAX(col) FROM table WHERE col NOT IN (SELECT MAX(col) FROM table));


Q:

What's the "java" way of converting chars (digits) to ints

Given the following code:
    char x = '5';
    int a0 = x - '0'; // 0
    int a1 = Integer.parseInt(x + ""); // 1
    int a2 = Integer.parseInt(Character.toString(x)); // 2
    int a3 = Character.digit(x, 10); // 3
    int a4 = Character.getNumericValue(x); // 4
    System.out.printf("%d %d %d %d %d", a0, a1, a2, a3, a4);

(version 4 credited to: casablanca)
What do you consider to be the "best-way" to convert a char into an int ? ("best-way" ~= idiomatic way)
We are not converting the actual numerical value of the char, but the value of the representation.
Eg.:
convert('1') -> 1
convert('2') -> 2
....

A:

How about Character.getNumericValue?

A:

I'd strongly prefer Character.digit.

A:

The first method.  It's the most lightweight and direct, and maps to what you might do in other (lower-level) languages.  Of course, its error handling leaves something to be desired.


Q:

Is water calcification bad for your health?

I have a friend, who adamantly believes that water calcification causes a number of problems, including poor health. He also said it made the water taste disgusting. He had recently installed a demagnetiser (or whatever it is - some kind of quack device) which is supposed to filter out the calcium by magnetically attracting it. Ignoring for now the fact that calcium isn't magnetic, of course, and magnets wouldn't have any effect. Let's presume the magic device does actually filter out calcium.
I didn't want to tell him he had been take for a ride (he paid about £200 for the unit), but I did agree to a taste test. I couldn't taste a difference between the uncalcified and calcified water. I've always drunk straight from the tap, with no ill effects so far.
What evidence is there that this water calcification, a) contributes to poor health, and/or b) makes tap water taste bad (apparently.)

A:

What makes water hard is calcium carbonate (limescale).
Not only it is not unhealthy, but it is also prescribed as an antacid.
The myth that hard water favours kidney stones has been disproved by a study, which has actually found that the opposite is true: a calcium-carbonate-poor diet increases the risk of kidney stones:

A slightly lower dietary calcium intake (683 versus 711 mg/day, P = 0.04) was noted in case subjects versus control subjects, but interpretation was confounded by the study of prevalent rather than incident cases. Supplemental calcium intake >500 mg/day was inversely associated with stone occurrence.

A:

No. Calcification of water is (slightly) good for you.
If you ignore the effects of limescale on your pipes, boilers, taste (hard water makes worse tea) and any indirect effects these may have on your health there is evidence that hard water leads to slightly lower rates of cardiovascular disease. The  result comes from a BMJ paper in 1980 which sought explanatory factors for the different rates of heart disease in different parts of the UK. The paper is here.
The summary conclusion relevant to this question states:

After adjustment
  for other factors cardiovascular mortality in areas with
  very soft water, around 0 25 mmol/l (calcium carbonate
  equivalent 25 mg/l), was estimated to be 10-15% higher
  than that in areas with medium-hard water, around
  1-7 mmol/l (170 mg/l), while any further increase in
  hardness beyond 1-7 mmol/l did not additionally lower
  cardiovascular mortality.

So it might be more accurate to say the absence of hardness has a small influence on stroke and heart disease rates. And the effect isn't large, especially when compared to other known influences on these diseases. As the authors say:

...the potential risks from smoking, hypertension, hypercholesterolaemia,
  and physical inactivity are far greater than the
  apparent risk from drinking soft water;

Another effect of water hardness that is almost certainly no longer relevant is that hard water prevents the accumulation of lead in water compared to soft water which tends to be acidic and leaches small amounts of lead from lead piping (which was relatively common in some countries until the 1960s). An older BMJ paper from 1973 summarizes this evidence like this:

The present findings suggest that people living in soft water areas
  have higher concentrations of lead in their bones than those living
  in hard water areas...
  the present findings indicate
  a more generally distributed cause; the ingestion of small doses
  of lead from drinking water over a long period of time is a
  possible explanation.

And they further elaborate:

... a concentration of lead which may be
  harmless in a hard water may not be so in a soft water; in fact,
  hard water is protective against both the pick-up of lead from
  pipes and its absorption by the body.

Since lead piping has mostly been eliminated, this effects is no longer likley to have any significance.
So the direct evidence seems to suggest that hard water is (very slightly) good for you.
I have not yet found more recent research results on the topic so it would be interesting to see whether similar studies from other countries or more recent studies show the same effect.


Q:

In context of CQRS and DDD how would you handle slightly varying use cases?

I could have a command for each variation or I could have one command and handle variations within it.
To illustrate, I have three use cases (or more), "CommentOnPhoto", "CommentOnWall", "CommentOnArticle". All of them internally use the same commenting system. The difference between three is:

Different policy needs to be checked (CommentOnPhotoPolicy, CommentOnWallPolicy, CommentOnArticlePolicy)
Different aggregate has to be pulled from repository so that we could call, photo.attachComment(comment), article.attachComment(comment), etc.

If going the route of one command for each variation then should each command inherit from some base CommentOnSomething command since they are all very similar?
If going the route of one mother command for all use cases then we will have to make use of Service Locator to pull needed Policies and Repositories on demand (we don't want to inject 10+ dependencies for each use case only to use one). Is this acceptable if we make use of abstract factories and such to hide away service locator use? Meaning we have CommentPolicyFactory and CommentableFactory which use Service Locator internally to deliver the right policy and the right aggregate.

A:

One command per variation.
I would first focus on creating a very generic "commenting" component (as its own project, decoupled from your core domain). Once you have it, then your commands CommentOnPhoto, CommentsOnWall and others will become very simple with just a few lines of code.


Q:

Is it possible to support add-swap-drop of DB tables in Android ContentProvider?

I am being asked to provide a dual-cache scheme for syncing cloud DB with device DB.  The requirement is to create a set of tables and then at some point in time, the sync will occur to a mirror of the same set of tables.  When done, the ContentProvider is expected to swap one set for the other without the application noticing.
Is this possible?
Can I add-swap-drop tables safely?
Can I add-swap-drop several tables safely - some activities may be displaying joins?
Comments and ideas are welcome, but it is not an option to "merge sync" the existing tables.
My concern is that there can be outstanding cursors in Activities or Services that are operating on the table-set and no way to assure that they have closed the cursor before the table that it may be accessing is dropped.

A:

Yes it is possible (Even though your two-table requirement from your customer sounds like a really ugly hack.)
Your ContentProvider is expected to serve up a cursor, in response to a specific Content URI.  How that URI gets mapped to a table in the database is completely up to you.
So do this:
Create 2 tables, "data1" and "data2" with an identical database schema.  Fill data1 with your data like normally.  When an app queries your URI, respond with a cursor filled with data out of data1.
Later, fill up data2.  When the command comes and it's time to switch tables, call notifyChange() with the (one) URI you use for that data.  All the cursors that are listening (Your display apps are using RegisterContentObserver() aren't they?) will be notified that the data at your URI has changed.  When they get that notify, they'll re-query.  This time, your ContentProvider will answer with data out of table2 instead of table1...  The cursor doesn't know what table it's filled from, just what URI.  So to the applications using the data, the change is completely transparent (as long as the two tables have the same schema.)
I've glossed over commanding the switch and saving which table is active.  That's obviously kind of application specific to you, but you should be able to find a good way to persist that information already.
As for table JOINs...  The trick of course is to ensure that the logic to do the JOIN itself happens inside the ContentProvider, not inside the app.  Then, you just switch several sets of tables at once, and do JOIN out of the right sets.
Finally, as for stale Cursors, the Cursor contains a copy of table data, not any reference to the table itself.  So if the table goes away, the Cursor data would be stale, at worst.  It won't hold the table open or the like.  The Cursor keeps a back-reference to the Content URI it came from, not the table.  So, again, when it requeries, it'll work just like above.


Q:

What is the function of using php for site links?

I am working on a site and the builders have used a mix of php and html for links. For example:

Variable Speed Drives

Corrosion Resistant Baseplates

and

<a href="<?php echo $external_video_link?>MP_PUMP.html" target="_blank">MP Repair

<a href="<?php echo $external_video_link?>MTA_PUMP.html" target="_blank">MTA Repair

The php is referenced in another file in this way:
<?php
$pdf_link = "../pdf/";
$external_pdf_link = "../../pdf/";
$video_link = "../video/";
$external_video_link = "../../video/";
?>

My concern is not knowing the function of the php, other than it being a placeholder, and given that the links work both ways, I don't want to break something because I am clueless to its purpose.
In doing my due diligence researching, I ran across this post, which is close, but still no cigar, Add php variable inside echo statement as href link address?. All of the research seems to be about how rather than why. This is the site, and they only used it for the "Downloads" links: http://magnatexpumps.com/
Thank you...
B

A:

There is no right way. They are just different.
Let's forget the PHP for a while. If you have this link in a page:
About

What will happen? The browser will change the URL of the document. If you are at the root of the site like: "www.example.com", will redirect to "www.example.com/about.html". If you are in a URL like "www.example.com/news/index.html" will redirect you to "www.example.com/new/about". That's why sometimes it is useful to have a variable before, to force a full path URL.
Another case of URL variable interpolation is when you have different systems running in the same url. In this case, you will have to append the system name in order to get to where you want. If you don't know where your application will run if it will run on the doc root, or in a subfolder, use a variable to indicate the base path.


Q:

Through vagrant running mvn command

I am working on writing vagrantfile for automation of local setup.
Through vagrant, i am creating docker image for my app and running it inside vm. Everything is under one command i.e. vagrant up
But one thing i have to do manual i.e. creating jar file for my app by using mvn clean package.
I am wondering is there any way to run mvn command from vagrantfile, so that when i issue vagrant up, it should build the JAR and do the rest of the work.

A:

as @Patrick mentions, the shell provisioning is a good fit - I personally use for gradle but the same can be done for maven. Here is how I call my script
config.vm.provision "shell", path: "script/run-test.sh", privileged: false, run: 'always'

path : is the path for my shell script from the project directory
privileged : if not set, root will run the script, if maven is installed for your vagrant user, make sure to set it to false else you will see issue
run: 'always' : this is my use-case (up to you to choose if it makes sense for you), the script will always run when I run vagrant up

the shell script will be something like
#!/bin/bash

if [ -d "/home/vagrant/test" ];then
    cd /home/vagrant/test && git pull
    cd /home/vagrant/test && maven compile
    cd /home/vagrant/test && maven deploy
    .....

else
    git clone <your project> /home/vagrant/test
fi

This is an example, basically first time I create the instance it will clone a git repo - then it will pull from git latest files and run your maven command.
Again this is a simple example, use it for your own need


Q:

RAVE: Pasting images from the clipboard directly into SE

I don't have much to say other than I love the new ability to "paste" binary pictures directly into the SE editor.  This is such a time saver and is the first of it's kind I've seen.
Great programming work StackExchange folks!!
I normally don't (and have never posted) something of this nature but I wanted people to notice and or try this feature out.  It is very cool.
If slightly nagged I will quickly delete this....

A:

A couple of notes and more info
This feature is implemented using the Clipboard API and File API. Currently, standard and semi-standard implementations only work in Chrome and IE9+. This feature does not work in Firefox (at least not with SE code).
Other services got it working in Firefox. The Firefox workaround has also been posted on Stackoverflow.


Q:

Scraping a reactjs website using Java and Selenium

I have everything set up to run a headless browser using Selenium in Java. I cant figure out now what I need to do to extract elements from this ReactJS website (the site contains either ReactJS or Javascript I'm not sure).
I feel like I may be approaching this wrong and/or missing some libraries that would help me along the way.
Any help greatly appreciated.

A:

If you do Web Interface tests or scraping with Java + Selenium, I advise you to use the NoraUi Open Source Framework.


Q:

How to add a new keyboard layout (Custom keyboard layout definition)

I want to copy a keyboard layout in /usr/share/X11/xkb/symbols/ and change it and then produce a new layout from it.
How can I add a new keyboard layout (named e.g. "mylayout")?
Update #1:
Files I changed to add a new layout:

/usr/share/X11/xkb/symbols/irwinxp (originally the same as ir):
// Iranian keyboard layout

////////////////////////////////////////
// Persian layout,
// based on
// Information Technology – Layout of Persian Letters and Symbols on Computer Keyboards
// ISIRI 9147 – 1st Edition
// Institute of Standards and Industrial Research of Iran
// http://www.isiri.org/UserStd/DownloadStd.aspx?id=9147
// http://behnam.esfahbod.info/standards/isiri-keyboard-9147.pdf
//
// Author: Behnam Esfahbod <behnam@esfahbod.info>
//

default  partial alphanumeric_keys
xkb_symbols "pes" {
    name[Group1]= "Persian";

    include "ir(pes_part_basic)"
    include "ir(pes_part_ext)"

    include "nbsp(zwnj2nb3nnb4)"
    include "level3(ralt_switch)"
};

partial alphanumeric_keys
xkb_symbols "pes_keypad" {
    name[Group1]= "Persian (with Persian Keypad)";

    include "ir(pes_part_basic)"
    include "ir(pes_part_keypad)"

    include "nbsp(zwnj2nb3nnb4)"
    include "level3(ralt_switch)"
};

partial hidden alphanumeric_keys
xkb_symbols "pes_part_basic" {

    // Persian digits
    key <AE01> { [ Farsi_1, exclam,     grave           ] };
    key <AE02> { [ Farsi_2, 0x100066c,  at          ] };
    key <AE03> { [ Farsi_3, 0x100066b,  numbersign      ] };
    key <AE04> { [ Farsi_4, 0x100fdfc,  dollar          ] };
    key <AE05> { [ Farsi_5, 0x100066a,  percent         ] };
    key <AE06> { [ Farsi_6, multiply,   asciicircum     ] };
    key <AE07> { [ Farsi_7, Arabic_comma,   ampersand       ] };
    key <AE08> { [ Farsi_8, asterisk,   enfilledcircbullet  ] };
    key <AE09> { [ Farsi_9, parenright, 0x100200e       ] };
    key <AE10> { [ Farsi_0, parenleft,  0x100200f       ] };

    // Persian letters and symbols
    key <AD01> { [ Arabic_dad,      Arabic_fathatan,    degree      ] }; // 2: Arabic_sukun
    key <AD02> { [ Arabic_sad,      Arabic_dammatan,    VoidSymbol  ] }; // 2: Arabic_dammatan
    key <AD03> { [ Arabic_theh,     Arabic_kasratan,    0x13a4      ] }; // 2: Arabic_kasratan
    key <AD04> { [ Arabic_qaf,      Arabic_fathatan,    VoidSymbol  ] };
    key <AD05> { [ Arabic_feh,      Arabic_comma,       VoidSymbol  ] }; // 2: Arabic_damma
    key <AD06> { [ Arabic_ghain,    Arabic_semicolon,   VoidSymbol  ] }; // 2: Arabic_kasra
    key <AD07> { [ Arabic_ain,      Arabic_fatha,       VoidSymbol  ] };
    key <AD08> { [ Arabic_heh,      Arabic_hamza_above, 0x100202d   ] }; // 2: Arabic_shadda
    key <AD09> { [ Arabic_khah,     bracketright,       0x100202e   ] };
    key <AD10> { [ Arabic_hah,      bracketleft,        0x100202c   ] };
    key <AD11> { [ Arabic_jeem,     braceright,     0x100202a   ] };
    key <AD12> { [ Arabic_tcheh,    braceleft,      0x100202b   ] };

    key <AC01> { [ Arabic_sheen,    Arabic_fatha,       VoidSymbol  ] }; // 2: Arabic_hamzaonwaw
    key <AC02> { [ Arabic_seen,     Arabic_damma,       VoidSymbol  ] }; // 2: Arabic_hamzaonyeh
    key <AC03> { [ Farsi_yeh,       Arabic_kasra,       Arabic_alefmaksura ] }; // 2: Arabic_yeh
    key <AC04> { [ Arabic_beh,      Arabic_shadda,  VoidSymbol  ] }; // 1: Arabic_hamzaunderalef
    key <AC05> { [ Arabic_lam,      0x10006c0,  VoidSymbol  ] };// 2: Arabic_hamzaonalef
    key <AC06> { [ Arabic_alef,     Arabic_maddaonalef, 0x1000671   ] };
    key <AC07> { [ Arabic_teh,      Arabic_tehmarbuta,  VoidSymbol  ] };
    key <AC08> { [ Arabic_noon,     guillemotright,     0x100fd3e   ] };
    key <AC09> { [ Arabic_meem,     guillemotleft,      0x100fd3f   ] };
    key <AC10> { [ Arabic_keheh,    colon,          semicolon   ] };
    key <AC11> { [ Arabic_gaf,      quotedbl,       quotedbl    ] }; // 2: Arabic_semicolon

    key <AB01> { [ Arabic_zah,      Arabic_kaf,     VoidSymbol  ] };
    key <AB02> { [ Arabic_tah,      0x1000653,      VoidSymbol  ] };
    key <AB03> { [ Arabic_zain,     Arabic_jeh,     VoidSymbol  ] };
    key <AB04> { [ Arabic_ra,       Arabic_hamzaonwaw   ,0x1000656  ] }; // 2: Arabic_superscript_alef ٰ
    key <AB05> { [ Arabic_thal,     0x100200c,      0x100200d   ] };
    key <AB06> { [ Arabic_dal,      Arabic_hamza_above, Arabic_hamza_below  ] };
    key <AB07> { [ Arabic_hamzaonyeh,   Arabic_hamza,       ellipsis    ] }; // 1: Arabic_peh
    key <AB08> { [ Arabic_waw,      greater,        comma       ] };
    key <AB09> { [ period,      less,           apostrophe  ] };
    key <AB10> { [ slash,       Arabic_question_mark,   question    ] };

    key <TLDE> { [ 0x100200d,       division,       asciitilde  ] };
    key <AE11> { [ minus,       Arabic_tatweel,     underscore  ] };
    key <AE12> { [ equal,       plus,           0x1002212   ] };
    key <BKSL> { [ Arabic_peh,      bar,            0x1002010   ] }; // 1: backslash
};

partial hidden alphanumeric_keys
xkb_symbols "pes_part_ext" {

    // Persian and ASCII digits
    key <AE01> { [ 0x10006f1,   exclam,     grave,          1   ] };
    key <AE02> { [ 0x10006f2,   0x100066c,  at,         2   ] };
    key <AE03> { [ 0x10006f3,   0x100066b,  numbersign,     3   ] };
    key <AE04> { [ 0x10006f4,   0x100fdfc,  dollar,         4   ] };
    key <AE05> { [ 0x10006f5,   0x100066a,  percent,        5   ] };
    key <AE06> { [ 0x10006f6,   multiply,   asciicircum,        6   ] };
    key <AE07> { [ 0x10006f7,   Arabic_comma,   ampersand,      7   ] };
    key <AE08> { [ 0x10006f8,   asterisk,   enfilledcircbullet, 8   ] };
    key <AE09> { [ 0x10006f9,   parenright, 0x100200e,      9   ] };
    key <AE10> { [ 0x10006f0,   parenleft,  0x100200f,      0   ] };
};

partial hidden alphanumeric_keys
xkb_symbols "pes_part_keypad" {

    // Persian digits and Mathematical operators
    key <KPDV> { [ division,    XF86_Ungrab ] };
    key <KPMU> { [ multiply,    XF86_ClearGrab  ] };
    key <KPSU> { [ 0x1002212,   XF86_Prev_VMode ] };
    key <KPAD> { [ plus,    XF86_Next_VMode ] };

    key <KPEN> { [ KP_Enter ] };
    key <KPEQ> { [ equal    ] };

    key <KP7>  { [ KP_Home, 0x10006f7   ] };
    key <KP8>  { [ KP_Up,   0x10006f8   ] };
    key <KP9>  { [ KP_Prior,    0x10006f9   ] };

    key <KP4>  { [ KP_Left, 0x10006f4   ] };
    key <KP5>  { [ KP_Begin,    0x10006f5   ] };
    key <KP6>  { [ KP_Right,    0x10006f6   ] };

    key <KP1>  { [ KP_End,  0x10006f1   ] };
    key <KP2>  { [ KP_Down, 0x10006f2   ] };
    key <KP3>  { [ KP_Next, 0x10006f3   ] };

    key <KP0>  { [ KP_Insert,   0x10006f0   ] };
    key <KPDL> { [ KP_Delete,   0x100066b   ] };
};

////////////////////////////////////////
// Kurdish Layout

partial alphanumeric_keys
xkb_symbols "ku" {
    include "tr(ku)"
    name[Group1]= "Kurdish (Iran, Latin Q)";
};

partial alphanumeric_keys
xkb_symbols "ku_f" {
    include "tr(ku_f)"
    name[Group1]= "Kurdish (Iran, F)";
};

partial alphanumeric_keys
xkb_symbols "ku_alt" {
    include "tr(ku_alt)"
    name[Group1]= "Kurdish (Iran, Latin Alt-Q)";
};

////////////////////////////////////////
// Kurdish Soranî Bahdînî (Arabic) keyboard layout,
// based on the Kurdî Soranî Bahdînî keyboard from KurdITGroup
// which is based on National Iranian Keyboard Standard (ISIRI 2901:1994),
// with additions.
//
// Copyright (C) 2006 Erdal Ronahî, published under the GPL v2
//
// Special copyright note: author explicitly permitted to license this
// layout under MIT/X11 license, for details see
// https://bugs.freedesktop.org/show_bug.cgi?id=9541
//
// Author: Erdal Ronahî  <erdal.ronahi@gmail.com>
//
// Kurdish Arabic-Latin Layout for Soranî

partial alphanumeric_keys
xkb_symbols "ku_ara" {
    name[Group1]= "Kurdish (Iran, Arabic-Latin)";

    // Other 3-Level symbols
    key <TLDE> { [ 0x100200d,       division,       asciitilde  ] };
    key <BKSL> { [ backslash,       bar,            ccedilla, Ccedilla  ] };

    // Digits
    key <AE01> { [ 1,   exclam,     0x10006f1,  grave       ] };
    key <AE02> { [ 2,   at,         0x10006f2,  at      ] };
    key <AE03> { [ 3,   numbersign, 0x10006f3,  0x100066b   ] };
    key <AE04> { [ 4,   dollar,     0x10006f4,  0x100fdfc   ] };
    key <AE05> { [ 5,   percent,    0x10006f5,  0x100066a   ] };
    key <AE06> { [ 6,   asciicircum,    0x10006f6,  multiply    ] };
    key <AE07> { [ 7,   ampersand,  0x10006f7,  Arabic_comma    ] };
    key <AE08> { [ 8,   asterisk,   0x10006f8,  enfilledcircbullet  ] };
    key <AE09> { [ 9,   parenright, 0x10006f9,  0x100200e   ] };
    key <AE10> { [ 0,   parenleft,  0x10006f0,  0x100200f   ] };
    key <AE11> { [ minus,       Arabic_tatweel,     underscore  ] };
    key <AE12> { [ equal,       plus,           0x1002212   ] };

    key <AD01> { [         Arabic_qaf,            X,  q,  Q ] };
    key <AD02> { [         Arabic_waw,            X,  w,  W ] };
    key <AD03> { [          0x10006d5,   Arabic_heh,  e,  E ] };
    key <AD04> { [         Arabic_ra ,    0x1000695,  r,  R ] };
    key <AD05> { [         Arabic_teh,   Arabic_tah,  t,  T ] };
    key <AD06> { [          0x10006cc,    0x10006ce,  y,  Y ] };
    key <AD07> { [  Arabic_hamzaonyeh, Arabic_hamza,  u,  U ] };
    key <AD08> { [         Arabic_hah,   Arabic_ain,  i,  I ] };
    key <AD09> { [          0x10006c6, Arabic_hamzaonwaw,  o,  O ] };
    key <AD10> { [          0x100067e,  Arabic_theh,  p,  P ] };
    key <AD11> { [ bracketright,    braceright, ucircumflex, Ucircumflex    ] };
    key <AD12> { [ bracketleft,     braceleft,  scedilla, Scedilla  ] };

    key <AC01> { [ Arabic_alef, Arabic_maddaonalef, a, A    ] };
    key <AC02> { [ Arabic_seen,     Arabic_sheen,   s, S    ] };
    key <AC03> { [  Arabic_dal,     Arabic_thal,    d, D    ] };
    key <AC04> { [  Arabic_feh, Arabic_hamzaunderalef,  f, F    ] };
    key <AC05> { [   0x10006af,     Arabic_ghain,   g, G    ] };
    key <AC06> { [  Arabic_heh,     0x100200c,  h, H    ] };
    key <AC07> { [   0x1000698, Arabic_hamzaonalef, j, J    ] };
    key <AC08> { [   0x10006a9,     Arabic_kaf, k, K    ] };
    key <AC09> { [  Arabic_lam,     0x10006b5,  l, L    ] };
    key <AC10> { [  Arabic_semicolon,   colon,      ecircumflex, Ecircumflex    ] };
    key <AC11> { [  apostrophe,     quotedbl,   icircumflex, Icircumflex    ] };

    key <AB01> { [ Arabic_zain,     Arabic_dad, z, Z    ] };
    key <AB02> { [ Arabic_khah,     Arabic_sad, x, X    ] };
    key <AB03> { [ Arabic_jeem,     0x1000686,  c, C    ] };
    key <AB04> { [   0x10006a4,     Arabic_zah, v, V    ] };
    key <AB05> { [ Arabic_beh,      0x1000649,  b, B    ] };
    key <AB06> { [ Arabic_noon, Arabic_tehmarbuta,  n, N    ] };
    key <AB07> { [ Arabic_meem, Arabic_tatweel,     m, M    ] };
    key <AB08> { [ Arabic_comma,    greater,    comma       ] };
    key <AB09> { [ period,      less,       apostrophe  ] };
    key <AB10> { [ slash,       Arabic_question_mark,   question    ] };

    include "nbsp(zwnj2nb3)"
    include "level3(ralt_switch)"
};

// EXTRAS:

/////////////////////////////////////////////////////////////////////////////////
//
// Generated keyboard layout file with the Keyboard Layout Editor.
// For more about the software, see http://code.google.com/p/keyboardlayouteditor
//
// Version 0.2, fixed AD09.
//
// Layout by Ernst Tremel, http://ubuntuforums.org/showpost.php?p=9365469&postcount=32
// Creation of this file by Simos Xenitellis.

partial alphanumeric_keys
xkb_symbols "ave"
{
    name[Group1] = "Avestan";

    key <AB01> { [ U10B30,         U10B32 ] }; //
    key <AB02> { [ U10B11,         U10B12 ] }; //
    key <AB03> { [ U10B17,          UE102 ] }; //  
    key <AB04> { [ U10B2C,         U10B13 ] }; //
    key <AB05> { [ U10B20,         U10B21 ] }; //
    key <AB06> { [ U10B25,         U10B27 ] }; //
    key <AB07> { [ U10B28,         U10B29 ] }; //
    key <AB08> { [ U10B3C,         U10B39 ] }; //
    key <AB09> { [ U10B3E,         U10B3D ] }; //
    key <AB10> { [ U10B3F, periodcentered ] }; //  ·

    key <AC01> { [ U10B00,         U10B01 ] }; //
    key <AC02> { [ U10B2F,         U10B31 ] }; //
    key <AC03> { [ U10B1B,         U10B1C ] }; //
    key <AC04> { [ U10B1F,         U10B16 ] }; //
    key <AC05> { [ U10B14,         U10B15 ] }; //
    key <AC06> { [ U10B35,          UE100 ] }; //  
    key <AC07> { [ U10B18,         U10B24 ] }; //
    key <AC08> { [ U10B10,          UE101 ] }; //  
    key <AC09> { [ U10B2E,          UE103 ] }; //  
    key <AC10> { [ U10B3B,         U10B3A ] }; //
    key <AC11> { [ U10B1D                 ] }; //

    key <AD01> { [ U10B22,         U10B23 ] }; //
    key <AD02> { [ U10B33,         U10B34 ] }; //
    key <AD03> { [ U10B08,         U10B09 ] }; //
    key <AD04> { [ U10B2D,         U10B26 ] }; //
    key <AD05> { [ U10B19,         U10B1A ] }; //
    key <AD06> { [ U10B2B,         U10B2A ] }; //
    key <AD07> { [ U10B0E,         U10B0F ] }; //
    key <AD08> { [ U10B0C,         U10B0D ] }; //
    key <AD09> { [ U10B0A,         U10B0B ] }; //
    key <AD10> { [ U10B1E                 ] }; //
    key <AD11> { [ U10B06,         U10B07 ] }; //
    key <AD12> { [ U10B02,         U10B03 ] }; //

    key <AE01> { [ U10B78                 ] }; //
    key <AE02> { [ U10B79                 ] }; //
    key <AE03> { [ U10B7A                 ] }; //
    key <AE04> { [ U10B7B                 ] }; //
    key <AE05> { [ U10B7C                 ] }; //
    key <AE06> { [ U10B7D                 ] }; //
    key <AE07> { [ U10B7E                 ] }; //
    key <AE08> { [ U10B7F                 ] }; //

    key <BKSL> { [ U10B04,         U10B05 ] }; //
    key <LSGT> { [ U10B04,         U10B05 ] }; //
};

Part of /usr/share/X11/xkb/rules/evdev.xml containing all modifications:
...
   <layout>
      <configItem>
        <name>ir</name>

        <shortDescription>fa</shortDescription>
        <description>Persian</description>
        <languageList>
          <iso639Id>per</iso639Id>
        </languageList>
      </configItem>
      <variantList>
        <variant>
          <configItem>
            <name>pes_keypad</name>
            <description>Persian (with Persian Keypad)</description>
          </configItem>
        </variant>
        <variant>
          <configItem>
            <name>ku</name>

            <shortDescription>ku</shortDescription>
            <description>Kurdish (Iran, Latin Q)</description>
            <languageList>
              <iso639Id>kur</iso639Id>
            </languageList>
          </configItem>
        </variant>
        <variant>
          <configItem>
            <name>ku_f</name>

            <shortDescription>ku</shortDescription>
            <description>Kurdish (Iran, F)</description>
            <languageList>
              <iso639Id>kur</iso639Id>
            </languageList>
          </configItem>
        </variant>
        <variant>
          <configItem>
            <name>ku_alt</name>

            <shortDescription>ku</shortDescription>
            <description>Kurdish (Iran, Latin Alt-Q)</description>
            <languageList>
              <iso639Id>kur</iso639Id>
            </languageList>
          </configItem>
        </variant>
        <variant>
          <configItem>
            <name>ku_ara</name>

            <shortDescription>ku</shortDescription>
            <description>Kurdish (Iran, Arabic-Latin)</description>
            <languageList>
              <iso639Id>kur</iso639Id>
            </languageList>
          </configItem>
        </variant>
      </variantList>
    </layout>
    <layout>
      <configItem>
        <name>irwinxp</name>

        <shortDescription>fa</shortDescription>
        <description>Persian-WinXP</description>
        <languageList>
          <iso639Id>per</iso639Id>
        </languageList>
      </configItem>
      <variantList>
        <variant>
          <configItem>
            <name>pes_keypad</name>
            <description>Persian (with Persian Keypad)</description>
          </configItem>
        </variant>
        <variant>
          <configItem>
            <name>ku</name>

            <shortDescription>ku</shortDescription>
            <description>Kurdish (Iran, Latin Q)</description>
            <languageList>
              <iso639Id>kur</iso639Id>
            </languageList>
          </configItem>
        </variant>
        <variant>
          <configItem>
            <name>ku_f</name>

            <shortDescription>ku</shortDescription>
            <description>Kurdish (Iran, F)</description>
            <languageList>
              <iso639Id>kur</iso639Id>
            </languageList>
          </configItem>
        </variant>
        <variant>
          <configItem>
            <name>ku_alt</name>

            <shortDescription>ku</shortDescription>
            <description>Kurdish (Iran, Latin Alt-Q)</description>
            <languageList>
              <iso639Id>kur</iso639Id>
            </languageList>
          </configItem>
        </variant>
        <variant>
          <configItem>
            <name>ku_ara</name>

            <shortDescription>ku</shortDescription>
            <description>Kurdish (Iran, Arabic-Latin)</description>
            <languageList>
              <iso639Id>kur</iso639Id>
            </languageList>
          </configItem>
        </variant>
      </variantList>
    </layout>
    <layout>
      <configItem>
        <name>iq</name>
...

But now, with these changes the new Persian-WinXP layout does not obey irwinxp and irwinxp is igored. Instead ir controls Persian-WinXP.
Update #2:
Unity has a problem with my new layout. The new layout icon is dark. But it works well.

Note: I use Ubuntu 14.04.

A:

Creating custom keyboard layout
For example, I'm looking to add a new modified English (international AltGr dead keys) US layout with swapped r,R & t,T. I will name it XY swapped:RT English (international AltGr dead keys).

Create new symbols file:
sudo nano /usr/share/X11/xkb/symbols/xy
default  partial alphanumeric_keys
xkb_symbols "basic" {

   name[Group1]= "XY swapped:RT English (international AltGr dead keys)";

   include "us(altgr-intl)"

// my custom changes:

   key <AD04> { [        t, T,           ediaeresis,   Ediaeresis      ] };
   key <AD05> { [        r, R,           thorn,        THORN           ] };

   include "level3(ralt_switch)"
};

include "us(altgr-intl)" means it inherits all key from that layout only key overridden here.
You may use Keyboard Layout Editor which is a GUI program that helps create or edit XKB keyboard layouts. Thanks to @Glutanimate
Add the new layout declaration to /usr/share/X11/xkb/rules/evdev.xml (copy & modify us layout section)
Reference: Make new variant keyboard layout available in Settings?
sudo gedit /usr/share/X11/xkb/rules/evdev.xml
...
<layout>
  <configItem>
    <name>xy</name>

    <shortDescription>en</shortDescription>
    <description>XY swapped:RT English (international AltGr dead keys)</description>
    <languageList>
             <iso639Id>eng</iso639Id>
             <iso639Id>fra</iso639Id>
             <iso639Id>ger</iso639Id>
    </languageList>
  </configItem>
  <variantList>
  </variantList>
</layout>
...

Delete xkb cache.
sudo rm /var/lib/xkb/*.xkm

Notes:
To load changes to the layouts menu simply close out of gnome-keyboard-preferences and reload, relaunching the windows manager should not be necessary.
There is a change in Ubuntu version (13.10) which causes the keyboard settings cache to not refresh after files in "/usr/share/X11/xkb/symbols" directory are modified. It looks like changes just don't get applied. To force the cache refreshing a one should delete *.xkm files from "/var/lib/xkb".
Reference: Howto: Custom keyboard layout definitions

or
sudo dpkg-reconfigure xkb-data

Reference: Why did 13.10 break my custom keyboard layout?

Reply to fix OP modifications

(Update #1 wrong parent layout) You have modified xkb_symbols "pes_part_basic" which is in irwinxp file: that's ok.
but xkb_symbols "pes" in irwinxp file still:
include "ir(pes_part_basic)"

which should be:
include "irwinxp(pes_part_basic)"

(Update #2 custom icon) If <shortDescription>en</shortDescription> changed to <shortDescription>xy</shortDescription>. So the new layout will distinct from En and it will appear as Xy.
Most probably there will be no icon for it in ubuntu-mono. Then the indicator will dynamically generate new one which may not follow current theme.

Copy any layout icons for dark/light mono themes:
sudo cp /usr/share/icons/ubuntu-mono-dark/status/22/indicator-keyboard-En.svg /usr/share/icons/ubuntu-mono-dark/status/22/indicator-keyboard-Xy.svg
sudo cp /usr/share/icons/ubuntu-mono-light/status/22/indicator-keyboard-En.svg /usr/share/icons/ubuntu-mono-light/status/22/indicator-keyboard-Xy.svg

SVG files are just XML. Open then for editing and change text value from En to Xy:
sudo nano /usr/share/icons/ubuntu-mono-dark/status/22/indicator-keyboard-Xy.svg
sudo nano /usr/share/icons/ubuntu-mono-light/status/22/indicator-keyboard-Xy.svg

Example:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="22" xmlns="http://www.w3.org/2000/svg" version="1.1" height="22">
 <defs>
  <mask id="m">
   <rect y="0" x="0" style="fill:#fff" height="22" width="22"/>
   <text y="15.5" x="5" style="font-size:12;font-family:Ubuntu;font-weight:500;fill:black">Xy</text>
  </mask>
 </defs>
 <rect style="fill:#dfdbd2" mask="url(#m)" rx="2" height="20" width="20" y="1" x="1"/>
</svg>

Update theme cache:
sudo update-icon-caches /usr/share/icons/ubuntu-mono-*/

Logout/login

Other Helpful References

How to modify a keyboard layout in Linux (thanks to @Rmano)
Building an XKB Keyboard (thanks to @Glutanimate)


Q:

Take PHP Debug mode off for CakePHP

I did the CakePHP tutorial, but I get this

at the top and bottom. I would like to take that away.
And I have a question, when making a brand new app, do I have to deattach any css or stuff like that?

A:

TLDR:
Remove stuff from View/Layouts/default.ctp (your default layout file)
Removing the code at the bottom:
In the View/Layouts/default.ctp (your default layout file), there is code at the bottom that shows the sql queries.  Just remove it, and you'll no longer have all that data printed at the bottom:
<?php echo $this->element('sql_dump'); ?>

(It's something that should be removed anyway if you plan on using DebugKit... which you should be planning on doing.)
Removing the style in general:
As for the style (colors...etc), if you also look in the same file, you'll see (toward the top) that it includes the generic CakePHP CSS.  Just remove this line to get rid of their generic styling:
echo $this->Html->css('cake.generic');

Removing the description of CakePHP:
Same file - just remove this:

<?php echo $this->Html->link($cakeDescription, 'http://cakephp.org'); ?>

A:

Ensure you set your debug mode to false

in your config, app.php for cakephp3.x
'debug' => filter_var(env('DEBUG', false), FILTER_VALIDATE_BOOLEAN),


Q:

C#: How to access array methods from parent object?

My ctor return an object which is multidimentional array. Depends on constructor argument, the object returned by ctor can be different rank array, but always int.
object arr = new int[2,2,2];

or
object arr = new int[2,2,2,2,2];

or
object arr = new int[0,0];

Having arr object  constructed, and knowing what it is (GetType()), I'd like to access array methods like Rank, GetLength, GetValue etc. How I can access child specific methods from the object level? For now I have only  four methods for arr object accessible: Equals, GetHashCode, GetType, and ToString

A:

Cast the object into an array, like this:
((int[])arr).Rank
((int[])arr).GetLength()

or
(arr as int[]).Rank


Q:

why i can't print my datas of object?

Here are my codes:
var express = require('express');
var app = express();
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '1',
  database : 'test'
});
connection.connect();

app.configure(function(){
    app.set('view engine', 'jade');
    app.set('views', __dirname + '/html');
});

app.get('/index/:name',function(req, res){
    data = connection.query('SELECT * FROM deneme', function(err, rows, fields){
        if(err) throw err;
        veri = rows;
        return veri;
    });

    res.render('index', {
        title: req.params.name,
        data: data
    });
});

app.listen(8080);

Shortly I want to print my datas of mysql
INSERT INTO `deneme` (`id`, `name`) VALUES
(1, 'yusuf'),
(2, 'ali');

When I call localhost:8080/index/yusuf it shows below:
[object Object]

What can i print datas?
EDIT
My index.jade file:

!!! 5 html   head
      title= title   body   p= data

A:

If you want a string representation, you could use JSON.stringify(myObject).
Edit:
res.render('index', {
    title: req.params.name,
    data: JSON.stringify(data)
});

But I'm not sure if that's what you want. You probably want to access the data's properties by referencing them:  #{data.someProperty}.
Or you could make the data object return a string representation when it's printed. Here is an example.


Q:

What's the most efficient way to keep everyone informed intergalactically?

Everyone knows that news is important and communication,l too. Let's say, we, the Milky way, and we, the Andromeda are to communicate ~real-time and be informed (news), what's the most efficient way to establish this network?
I can't see anything better than milliards of nodes or a gigantic information lane between the two galaxies, but it's too unrealistic.
How could a person from the Andromeda call his friend in the Milky way and speek to him like we do it on the telephone or skype?
It's vital to add that it's necessary that nothing influences this network and nothing breaks it easily.
Edit: The galaxy hasn't magic or alien technology. It's our world a few thousand years later. Hyperspace and powerful engines exist, speed of light is reachable.
I was also thinking about sending data some time back in time for enough time to reach the other galaxy. Like if it takes 500-600 years for information to reach Andromeda from the Milky Way, we send it 500-600 years back for it to reach Andromeda exactly 500-600 years later in the present, just at the same time it was sent from the Milky Way.

A:

Any device that can communicate faster than light will rely on non-local physics anyway, removing the need for relays since relays are a locality-based concept.
Current physics indicates that the only cases in which information correlates between non-local events is with entangled particles, and as far as I know we don't have any way to produce large numbers of mutually entangled particles, or any way to transfer information between entangled particles, so even using that as a basis you'll have to make up new ideas to make it work for an intergalactic network. We just don't have a realistic expectation of instantaneous communication at all being possible.


Q:

Magento 2: Fatal Error: 'Uncaught Error: Call to undefined method setWebsiteId()

I had created a custom API for customer registration in Magento 2.3. I am checking that the weather the customer is already registered or not with below code.
$email = $this->request->getParam('email');
$firstName = $this->request->getParam('firstname');
$lastName = $this->request->getParam('lastname');
$websiteId = $this->request->getParam('websiteId');

$customerFactory = $this->_customerFactory->getCollection();

/**
 * check whether the email address is already registered or not
 */
$customer = $customerFactory->setWebsiteId($websiteId)->loadByEmail($email);

/**
 * if email address already registered, return the error message
 * else, create new customer account
 */
if ($customer->getId()) {
    echo 'Customer with email '.$email.' is already registered.';
} else {
    // code...
}

But I am getting the api error when i run in postman. When I checked the api log report it shows below error.
"Fatal Error: 'Uncaught Error: Call to undefined method Magento\\Customer\\Model\\ResourceModel\\Customer\\Collection\\Interceptor::setWebsiteId() in \/var\/www\/html\/app\/code\/MyModule\/Customapi\/Model\/AppcustomerregistrationManagement.php:187\nStack trace:\n#0 [internal function]: MyModule\\Customapi\\Model\\AppcustomerregistrationManagement->signup()\n#1 \/var\/www\/html\/vendor\/magento\/module-webapi\/Controller\/Rest\/SynchronousRequestProcessor.php(95): call_user_func_array(Array, Array)\n#2 \/var\/www\/html\/vendor\/magento\/module-webapi\/Controller\/Rest.php(188): Magento\\Webapi\\Controller\\Rest\\SynchronousRequestProcessor->process(Object(Magento\\Framework\\Webapi\\Rest\\Request\\Proxy))\n#3 \/var\/www\/html\/vendor\/magento\/framework\/Interception\/Interceptor.php(58): Magento\\Webapi\\Controller\\Rest->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#4 \/var\/www\/html\/vendor\/magento\/framework\/Interception\/Interceptor.php(138): Magento\\Webapi\\Controller\\Rest\\Interceptor->___callParent('dispatch', Array)\n#5 \/var\/www\/html\/vendor\/magento\/framework\/Intercept' in '\/var\/www\/html\/app\/code\/MyModule\/Customapi\/Model\/AppcustomerregistrationManagement.php' on line 187"

A:

The \Magento\Customer\Model\ResourceModel\Customer\Collection class has no method setWebsiteId. If you want to filter customer collection by website id you must set website_id as a filter field:
/** @var \Magento\Customer\Model\ResourceModel\Customer\Collection $customerCollection */
$customer = $customerCollection->addFilter('website_id', $websiteId)
     ->addFilter('email', $email)
     ->getFirstItem();

Or You can use the repository for that purposes:
Add \Magento\Customer\Api\CustomerRepositoryInterface in the constructor, like this:
/**
 * @var \Magento\Customer\Api\CustomerRepositoryInterface
 */
private $customerRepository;

/**
 * ObtainCustomer constructor.
 *
 * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
 */
public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
) {
    $this->customerRepository = $customerRepository;
}

Use that code inside your method:
try {
    $customerEntity = $this->customerRepository->get(
        $email,
        $websiteId
    );
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
    // no customer
} catch (\Magento\Framework\Exception\LocalizedException $e) {
    // no customer
}


Q:

LDAP authentication fail log

why the log say pam_unix(sshd:auth): authentication failure but the login works fine? or can anyone tell me how can I fix this.
Jun 27 09:46:31 [localhost] sshd[16341]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.56.1  user=ope_fptsoft01
Jun 27 09:46:31 [localhost] sshd[16341]: Accepted password for ope_fptsoft01 from 192.168.56.1 port 55087 ssh2
Jun 27 09:46:31 [localhost] sshd[16341]: pam_unix(sshd:session): session opened for user ope_fptsoft01 by (uid=0)

My system-auth:
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        required      pam_faildelay.so delay=2000000
auth        sufficient    pam_unix.so
auth        sufficient    pam_ldap.so minimum_uid=1000 use_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     [default=bad success=ok user_unknown=ignore] pam_ldap.so
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok use_authtok
password    sufficient    pam_ldap.so minimum_uid=1000 try_first_pass
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session     optional      pam_systemd.so
session     optional      pam_mkhomedir.so umask=0077
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_ldap.so minimum_uid=1000

A:

My solution is:
auth sufficient pam_unix.so try_first_pass
auth sufficient pam_ldap.so


Q:

Regex for matching a word within a sentence

I am looking for a C# regex to match a complete word within a sentence.
my sentence and pattern looks like this below.
 string mySentence = "There is no gain in this world without pain";

 string mypattern = string.Format(@"(?:(?<=^|\s)(?=\S)|(?<=\S|^)(?=\s)){0} (?:(?<=\S)(?=\s|$)|(?<=\s)(?=\S|$))", "pain");

 MatchCollection matches = Regex.Matches(mySentence, mypattern);

I do not get any match using the above pattern.
But if I use this pattern I get a match.
string mypattern = string.Format(@"\b{0}\b", "patient");

But the problem is it matches hyphen separated word like in-pain as well, where as I am looking for a complete word.
Any help appreciated, thanks

A:

Scenario #1 (word(s) not preceded/followed with hyphen)
Use negative lookarounds (?<!-) (no - before the search phrase) and (?!-) (no - after the search phrase) together with \b:
var mypattern = string.Format(@"(?<!-)\b{0}\b(?!-)", Regex.Escape(search));

Scenario #2 (word(s) enclosed with whitespaces)

I am looking to match a word, which can be followed or preceded by newline or whitespace.

You need to use lookarounds like this:
var mypattern = string.Format(@"(?<!\S){0}(?!\S)", Regex.Escape(search));

The (?<!\S) lookaround (equal to (?<=\s|^)) requires a whitespace or start of string before the search word. The (?!\S) negative lookahead will require a whitespace symbol after the search word.
The Regex.Escape is a pre-caution step to make sure all special chars inside the search word are treated as  literal characters.
A note: if your "words" never contain a whitespace, you do not need a regex. Use
var search = "this";
var sentence = "There is no gain in this world without pain";
var isPresent = sentence.Split().Contains(search);
Console.Write(isPresent); // = > True


Q:

LINQ OrderBy not ordering .. changing nothing .. why?

Any idea why the LINQ OrderBy is not working in following code, (have no errors but method does not sort ...)
First my own type
public class IQLinksView
    {
        public int id { get; set; }
        public int catid { get; set; }
        public int? viewed {get;set;}
        public string name {get;set;}
        public string desc {get;set;}
        public string url {get;set;}
        public string pic {get;set;}
        public string cat {get;set;}
    }

then query :
IQueryable<IQLinksView> newView =
              from links in this.emContext.tbl_otherlinks
              select new IQLinksView { id = links.pklinkid, catid =
              links.tbl_catgeory.pkcategoryid, viewed = links.linkviewed, name = links.linkname,
              desc = links.linkdesc, pic = links.linkpicture,   url = links.linkurl, cat =
              links.tbl_catgeory.categoryname };

Untill here all fine :-), but then
newView.OrderBy(x => x.viewed);

just changes nothing,... Page is loading results showing ... but no ordering ... sniff
i have Try with (creating a comparer object ... ):
newView.OrderBy(x => (Int32)x.viewed, new CompareIntegers());

same result, no ordering ...
I do have workarounds but just wondering what is missing ....
Any suggestions will be appreciated thanks a lot :-)

A:

Don't throw away the return value. The OrderBy extension method is does not mutate the input. Try:
newView = newView.OrderBy(x => x.viewed);

There is no reason why that won't work, assuming the viewed value is correct. Also, make sure that OrderBy is after any operations (e.g. Distinct) which will ruin ordering.
Happy coding!


Q:

Не компилируется программа со считыванием строки

Работаю в самой последней версии Visual Studio. Ещё при самом написании кода функция gets "подчеркнулась" волнистой линией. Вроде бы всё в самом коде нормально. Может это специфика самой среды или сама функция устарела... Подскажите, пожалуйста.
#include "stdafx.h"
#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    char a[80];

    cout << "Vvedite stroku: ";
    gets(a);

    cout << "Vasha stroka: ";
    cout << a;

    system("pause");
    return 0;
}

A:

Попробуйте cin.get(a, 80); или cin.getline(a, 80); вместо gets(a);
Синтаксис:
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

где s - указатель на массив char'ов, в который вы будете писать, n - максимальное количество символов, которые вы хотите записать (включая последний нулевой символ), delim - символ, нахождение которого прекращает ввод. Подробнее, но на английском тут.
В VS использовать gets не выйдет:

Эти функции устарели. Начиная с Visual Studio 2015 они недоступны в
  CRT. Безопасные версии этих функций, gets_s и _getws_s, по-прежнему
  доступны. Сведения об этих альтернативных функциях см. в статье
  gets_s, _getws_s.

Подробнее по ссылке на msdn.


Q:

How do I get a webcam working with AngularJS?

Previously I've put working webcam code into my application, but now it's not working when I updated to AngularJS v1.5.0. I am using webcam-directive which was working perfectly with v1.3.0.
Here is my code:
<webcam placeholder="selfiePlaceHolder"
  on-stream="onStream(stream)"
  on-access-denied="onError(err)" on-streaming="onSuccess(video)">
</webcam>

But now it's giving following error with AngularJS v1.5.0:
Uncaught Error: [$parse:isecdom] Referencing DOM nodes in Angular expressions is disallowed! Expression: onSuccess(video)
http://errors.angularjs.org/1.5.0/$parse/isecdom?p0=onSuccess(video)

I also tried to use a different solution with AngularJS ng-Camera but even its demo page is not working for me.
Note: I know the issue is that we can't access the DOM from the newer version of AngularJS, but the same code works with the older version. I need to know how to pass the "Video" DOM object to the controller.

A:

I've found the solution to the problem. Two things need to be done:
First In HTML:
<webcam channel="channel"
        on-streaming="onSuccess()"
        on-error="onError(err)"
        on-stream="onStream(stream)"></webcam>

Secondly, in the controller, you can access the DOM video with the following code:
 $scope.onSuccess = function () {
        // The video element contains the captured camera data
        _video = $scope.channel.video;
        $scope.$apply(function() {
            $scope.patOpts.w = _video.width;
            $scope.patOpts.h = _video.height;
            //$scope.showDemos = true;
        });
    };

Here is a working example.

A:

It is a potential error generally occurs when an expression tries to access a DOM node since it is restricted accessing to DOM nodes via expressions by AngularJS because it might cause to execute arbitrary Javascript code.
The $parse:isecdom error is related to an invoke to a function by event handler when an event handler which returns a DOM node, like below:
<button ng-click="myFunction()">Click</button>
$scope.myFunction = function() {
  return DOM;
}

To fix this issue, avoid access to DOM nodes and avoid returning DOM nodes from event handlers. (Reference: https://docs.angularjs.org/error/$parse/isecdom)
Adding an explicit return might solve this issue as detailed here: CoffeeScript - Referencing DOM nodes in Angular expressions is disallowed


Q:

How do I specify URIs in nginx conf file?

I am trying to understand the following nginx conf file (from here). What should I replace @example_app with?
server {
  listen 80;
  server_name example.com;
  rewrite ^(.+?)/?$ http://www.example.com$1 permanent;
}

server {
  listen 80;
  server_name www.example.com;
  root /var/www/example.com/public_html;

  location / {
    try_files $uri @example_app;
  }

  location @example_app {
    proxy_pass http://localhost:5000;
  }

}

EDIT
I changed my config file to this. Is this better? I adapted it from this answer. I also added my domain and ip address to /etc/hosts
 upstream ring {
        server 127.0.0.1:8080 fail_timeout=0;
}

server {
        root /usr/share/nginx/html;

        server_name localhost;

        location / {
                try_files $uri $uri/ @ring;
        }

        location @ring {
                proxy_redirect off;
                proxy_buffering off;
                proxy_set_header Host $http_host;
                proxy_pass http://ring;
        }

        location ~ ^/(assets|images|javascripts/stylesheets|swfs|system)/ {
        expires     max;
        add_header  Cache-Control public;
        }

A:

You dont need to replace @example_app with anything if you don't want. It is simply just a named location and could easily be changed to @whatever. You just need to make sure that if you reference a named location with try_files that you need define the same location in your config file.
The comments on Reddit explain the config fairly well but to reiterate:
1) The first server block redirects any requests from example.com to www.example.com
2) The second server block catches requests to www.example.com
3) The location / block catches all requests within this server block and try the list of options from try_files - first trying to load any matching files at that path otherwise using the named location @example_app
4) The location @example_app block is a named location and proxy passes the request to port 5000 on the same server.


Q:

Collocation: Rates are large/small or high/low?

What is the proper adjective for rates?
"..the learning rate is low/high.."
or
"..the learning rate is small/large.."
It seems that there are different opinions:

Numbers can be described using the metaphor of size (large vs small) or height (high vs low).
Answer to What's the difference between “large share” and “high share”?

“Large” and “small” are generally used to express variations or changes in size, dimensions, or mass. “High” and “low” are usually used to express levels or numerical values. “Large” and “small” are often mistakenly used where “high” and “low” would be better.
Springer.com: Large/small/high/low

A:

The Oxford Collocations Dictionary suggests high/low for the 'speed/frequency' aspect of rate (the other aspect there is 'amount of money'). And also the adjectives are suggested: constant, expected, regular, steady, slow, fast, rapid, alarming, phenomenal, ever-increasing, rocketing, etc. In no aspect large or small are suggested (I guess those words are more typical for pure numbers of something).
An example of using high/low with learning rate.
https://towardsdatascience.com/understanding-learning-rates-and-how-it-improves-performance-in-deep-learning-d0d4059c1c10
A picture of a graph from that page with definitions of different learning rates (high/low/good):
https://cdn-images-1.medium.com/max/1600/0*uIa_Dz3czXO5iWyI.


Q:

Android push notifications not working (Corona sdk)

Can anyone please help me with the sample code for google push notifications. I am getting an error in json message.
Here is the code:
local googleApiKey = "**********************"
local googleRegistrationId = nil

-- Called when a sent notification has succeeded or failed.
local function onSendNotification(event)
local errorMessage = nil

-- Determine if we have successfully sent the notification to Google's server.
if event.isError then
    -- Failed to connect to the server.
    -- This typically happens due to lack of Internet access.
    errorMessage = "Failed to connect to the server."

elseif event.status == 200 then
    -- A status code of 200 means that the notification was sent succcessfully.
    print("Notification was sent successfully.")

elseif event.status == 400 then
    -- There was an error in the sent notification's JSON data.
    errorMessage = event.response

elseif event.status == 401 then
    -- There was a user authentication error.
    errorMessage = "Failed to authenticate the sender's Google Play account."

elseif (event.status >= 500) and (event.status <= 599) then
    -- The Google Cloud Messaging server failed to process the given notification.
    -- This indicates an internal error on the server side or the server is temporarily unavailable.
    -- In this case, we are supposed to silently fail and try again later.
    errorMessage = "Server failed to process the request. Please try again later."
end

-- Display an error message if there was a failure.
if errorMessage then
    native.showAlert("Notification Error", errorMessage, { "OK" })
end
end
    -- Sends the given JSON message to the Google Cloud Messaging server to be pushed to Android devices.
local function sendNotification(jsonMessage)
-- Do not continue if a Google API Key was not provided.
if not googleApiKey then
    return
end

-- Print the JSON message to the log.
print("--- Sending Notification ----")
print(jsonMessage)

-- Send the push notification to this app.
local url = "**************************"
local parameters =
{
    headers =
    {
        ["Authorization"] = "key=" .. googleApiKey,
        ["Content-Type"] = "application/json",
    },
    body = jsonMessage,
}
network.request(url, "POST", onSendNotification, parameters)
end
-- Sends a push notification when the screen has been tapped.
local function onTap(event)
-- Do not continue if this app has not been registered for push notifications yet.
if not googleRegistrationId then
    return
end

-- Set up a JSON message to send a push notification to this app.
-- The "registration_ids" tells Google to whom this push notification should be delivered to.
-- The "alert" field sets the message to be displayed when the notification has been received.
-- The "sound" field is optional and will play a sound file in the app's ResourceDirectory.
-- The "custom" field is optional and will be delivered by the notification event's "event.custom" property.
local jsonMessage =
[[
{
"registration_ids": ["]] .. tostring(googleRegistrationId) .. [["],
"data":
{
    "alert": "Hello World!",
    "sound": "notification.wav",
    "custom":
    {
        "boolean": true,
        "number": 123.456,
        "string": "Custom data test.",
        "array": [ true, false, 0, 1, "", "This is a test." ],
        "table": { "x": 1, "y": 2 }
    }
}
}
]]
sendNotification(jsonMessage)
end
Runtime:addEventListener("tap", onTap)
-- Prints all contents of a Lua table to the log.
local function printTable(table, stringPrefix)
if not stringPrefix then
    stringPrefix = "### "
end
if type(table) == "table" then
    for key, value in pairs(table) do
        if type(value) == "table" then
            print(stringPrefix .. tostring(key))
            print(stringPrefix .. "{")
            printTable(value, stringPrefix .. "   ")
            print(stringPrefix .. "}")
        else
            print(stringPrefix .. tostring(key) .. ": " .. tostring(value))
        end
    end
end
end
-- Called when a notification event has been received.
local function onNotification(event)
if event.type == "remoteRegistration" then
    -- This device has just been registered for Google Cloud Messaging (GCM) push notifications.
    -- Store the Registration ID that was assigned to this application by Google.
    googleRegistrationId = event.token

    -- Display a message indicating that registration was successful.
    local message = "This app has successfully registered for Google push notifications."
    native.showAlert("Information", message, { "OK" })

    -- Print the registration event to the log.
    print("### --- Registration Event ---")
    printTable(event)

else
    -- A push notification has just been received. Print it to the log.
    print("### --- Notification Event ---")
    printTable(event)
end
end

-- Set up a notification listener.
Runtime:addEventListener("notification", onNotification)

-- Print this app's launch arguments to the log.
-- This allows you to view what these arguments provide when this app is started by tapping a notification.
local launchArgs = ...
print("### --- Launch Arguments ---")
printTable(launchArgs)

Whenever this code is called and Error 400 notification appears. Is there a way to send custom push notifications to android device using corona?

A:

Json is completely fine. There might be the problem of url you set up and for triangle notification problem you can go through the following link:
http://jsonlint.com/#


Q:

Xsl sum()  of  with the same name

I'm beginner in xsl.
I need to calculate sum traffic of users with same name (name NOT "name" + "last name"), for example calculate sum of traffic of all users with name "Jonh". And xsl version should be only 1.0.

I found a topic with the same problem

http://social.msdn.microsoft.com/Forums/eu/xmlandnetfx/thread/c9f09ba6-1c79-43df-bbc2-3966710fff23

I was try to use that:
Total: <xsl:value-of select="sum(//user[contains(name,'Jonh')]../traffic)" />

or
Total: <xsl:value-of select="sum(//user[contains(name,'Jonh')]/traffic)" />

but there is no effect. It does not calculate the sum.
Can anyone help me to find a solution.
XML FILE
<?xml version='1.0' encoding='UTF-8'?>
<?xml-stylesheet type='text/xsl' href='traffic.xsl'?>
<root>
   <user>
       <name>Jonh Connor</name>
       <traffic>800</traffic>
   </user>
   <user>
       <name>John Kennedy</name>
       <traffic>200</traffic>
   </user>
   <user>
       <name>Jack London</name>
       <traffic>100</traffic>
   </user>
   <user>
       <name>Sema Schlumberger</name>
       <traffic>300</traffic>
   </user>
   <user>
       <name>Jack Vorobey</name>
       <traffic>700</traffic>
   </user>
   <user>
       <name>John Lennon</name>
       <traffic>500</traffic>
   </user>
   <user>
       <name>John Romero</name>
       <traffic>4003</traffic>
   </user>
</root>

A:

Your second expression works ...
 <xsl:value-of select="sum(//user[contains(name,'Jonh')]/traffic)" />

I tested this and it works. Please note apparent typo in names: 'Jonh' and 'John' .
Note, although your expression is correct, if you can rely on the structure implied by your sample input, when the context node is the document root, then you may prefer a more efficient solution:
 <xsl:value-of select="sum(root/user/name[contains(.,'Jonh')]/../traffic)" />

Caveat
This form of expression does not distinguish between names and parts of names. So if you sum on 'Rom', you will get 4003 due to the fact that the last name 'John Romero' includes 'Rom'. If this is not a desired result, then you need to clarify the rules for matching.


Q:

rails index.js.erb not loading

I am attempting to do some ajax for pagination but I canno get index.js.erb to load or be recognized in any way. I'm following railscast 240:https://github.com/ryanb/railscasts-episodes/blob/master/episode-240/store/app/views/products/_products.html.erb
I am using the code below:
index.js.erb
$("#products").html("<%= escape_javascript(render("products")) %>");
The request seems to go through properly, but the HTML isn't loading. Nothing changes (no errors though)

A:

It was because I had format |do| in my controller without format.js. Sorry guys!


Q:

NHibernate Linq // FirstOrDefault with children objects // Possible?

I have an Employee.
Employee has a single (parent) Department. 1:N, Department to Employee.
Employee has N EmployeeToJobTitleMatchLink(s).
Employee has N number of ParkingArea(s).
When using NHibernate and Linq, and "FirstOrDefault"..
            EmployeeNHEntity firstOrDefaultEmp = session.Query<EmployeeNHEntity>()
                .Fetch(e => e.MyEmployeeToJobTitleMatchLinks)
                .Fetch(e => e.ParentDepartment)
                .Fetch(e => e.MyParkingAreas)
                .Where(e => e.EmployeeUUID == employeeUuid)
                .FirstOrDefault();

I get this sql.  (the most important part is the "Top 1".
exec sp_executesql N'select TOP (1)  employeenh0_.EmployeeUUID as Employee1_1_0_, myemployee1_.LinkSurrogateUUID as LinkSurr1_3_1_, department2_.DepartmentUUID as Departme1_0_2_, parkingare4_.ParkingAreaUUID as ParkingA1_5_3_, employeenh0_.MyVersionColumn as MyVersio2_1_0_, employeenh0_.SSN as SSN1_0_, employeenh0_.LastName as LastName1_0_, employeenh0_.FirstName as FirstName1_0_, employeenh0_.CreateDate as CreateDate1_0_, employeenh0_.HireDate as HireDate1_0_, employeenh0_.ParentDepartmentUUID as ParentDe8_1_0_, myemployee1_.PriorityRank as Priority2_3_1_, myemployee1_.JobStartedOnDate as JobStart3_3_1_, myemployee1_.TheEmployeeUUID as TheEmplo4_3_1_, myemployee1_.TheJobTitleUUID as TheJobTi5_3_1_, myemployee1_.TheEmployeeUUID as TheEmplo4_0__, myemployee1_.LinkSurrogateUUID as LinkSurr1_0__, department2_.MyVersionColumn as MyVersio2_0_2_, department2_.DepartmentName as Departme3_0_2_, department2_.CreateDate as CreateDate0_2_, parkingare4_.ParkingAreaName as ParkingA2_5_3_, parkingare4_.CreateDate as CreateDate5_3_, myparkinga3_.AbcEmployeeUUID as AbcEmplo1_1__, myparkinga3_.AbcParkingAreaUUID as AbcParki2_1__ from dbo.Employee employeenh0_ left outer join dbo.EmployeeToJobTitleMatchLink myemployee1_ on employeenh0_.EmployeeUUID=myemployee1_.TheEmployeeUUID left outer join dbo.Department department2_ on employeenh0_.ParentDepartmentUUID=department2_.DepartmentUUID left outer join EmployeeToParkingAreaLink myparkinga3_ on employeenh0_.EmployeeUUID=myparkinga3_.AbcEmployeeUUID left outer join dbo.ParkingArea parkingare4_ on myparkinga3_.AbcParkingAreaUUID=parkingare4_.ParkingAreaUUID where employeenh0_.EmployeeUUID=@p0',N'@p0 uniqueidentifier',@p0='64409648-15C5-4B67-BCE2-A265012E0926'

The issue is that I get 1 row (top 1).  While I have 1 Employee, I (should) have many rows in the resultset.
Now, if I use the below, I get the desired result. (A single employee with the children objects populated)....if there is a match on the surrogate-key (EmployeeUUID), there is one item in the collection.
            IList<EmployeeNHEntity> emps = session.Query<EmployeeNHEntity>()
                .Fetch(e => e.MyEmployeeToJobTitleMatchLinks)
                .Fetch(e => e.ParentDepartment)
                .Fetch(e => e.MyParkingAreas)
                .Where(e => e.EmployeeUUID == employeeUuid)
                .ToList();

            EmployeeNHEntity emp = null;
            if(null!=emps)
            {
                if (emps.Count > 0)
                {
                    emp = emps[0];
                }
            }

which generates this sql
exec sp_executesql N'select employeenh0_.EmployeeUUID as Employee1_1_0_, myemployee1_.LinkSurrogateUUID as LinkSurr1_3_1_, department2_.DepartmentUUID as Departme1_0_2_, parkingare4_.ParkingAreaUUID as ParkingA1_5_3_, employeenh0_.MyVersionColumn as MyVersio2_1_0_, employeenh0_.SSN as SSN1_0_, employeenh0_.LastName as LastName1_0_, employeenh0_.FirstName as FirstName1_0_, employeenh0_.CreateDate as CreateDate1_0_, employeenh0_.HireDate as HireDate1_0_, employeenh0_.ParentDepartmentUUID as ParentDe8_1_0_, myemployee1_.PriorityRank as Priority2_3_1_, myemployee1_.JobStartedOnDate as JobStart3_3_1_, myemployee1_.TheEmployeeUUID as TheEmplo4_3_1_, myemployee1_.TheJobTitleUUID as TheJobTi5_3_1_, myemployee1_.TheEmployeeUUID as TheEmplo4_0__, myemployee1_.LinkSurrogateUUID as LinkSurr1_0__, department2_.MyVersionColumn as MyVersio2_0_2_, department2_.DepartmentName as Departme3_0_2_, department2_.CreateDate as CreateDate0_2_, parkingare4_.ParkingAreaName as ParkingA2_5_3_, parkingare4_.CreateDate as CreateDate5_3_, myparkinga3_.AbcEmployeeUUID as AbcEmplo1_1__, myparkinga3_.AbcParkingAreaUUID as AbcParki2_1__ from dbo.Employee employeenh0_ left outer join dbo.EmployeeToJobTitleMatchLink myemployee1_ on employeenh0_.EmployeeUUID=myemployee1_.TheEmployeeUUID left outer join dbo.Department department2_ on employeenh0_.ParentDepartmentUUID=department2_.DepartmentUUID left outer join EmployeeToParkingAreaLink myparkinga3_ on employeenh0_.EmployeeUUID=myparkinga3_.AbcEmployeeUUID left outer join dbo.ParkingArea parkingare4_ on myparkinga3_.AbcParkingAreaUUID=parkingare4_.ParkingAreaUUID where employeenh0_.EmployeeUUID=@p0',N'@p0 uniqueidentifier',@p0='64409648-15C5-4B67-BCE2-A265012E0926'

The [0] indexer trick is ok.  But just isn't as clean as I'd like my Linq code to be.
Any suggestions now LINQ syntax to get Top 1 Employee, but with all the children objects?

A:

EmployeeNHEntity firstOrDefaultEmp = session.Query<EmployeeNHEntity>()
    .Fetch(e => e.MyEmployeeToJobTitleMatchLinks)
    .Fetch(e => e.ParentDepartment)
    .Fetch(e => e.MyParkingAreas)
    .Where(e => e.EmployeeUUID == employeeUuid)
    .AsEnumerable()    <-- note this line
    .FirstOrDefault();


Q:

Server triggers client event twice

hi I'm trying to develop simple chat app using socket.io and express.
My issue is: when user send message emit event to server and server broadcast to the rest clients- it happens twice
That is all what I can't figured out: why
socket.broadcast.emit('setMessage' fires twice in the browser setMessage
https://github.com/ntorbev/chat
any help will be appreciate

A:

The problem is that in layout.jade, you're including chat.js twice
doctype html
html
    block head
        title= title
        link(rel='stylesheet', href='/css/site.css')
        script(type="text/javascript" src="/lib/jquery/dist/jquery.js")
        script(type='text/javascript', src='/socket.io/socket.io.js')
        script(type='text/javascript', src='/javascripts/chat.js')
        script(type='text/javascript', src='/javascripts/chat.js')
    body
        header#banner
        //h1 Awesome Chat
        block content
        //footer Hope you enjoy your stay here


Q:

Erlang: Who supervises the supervisor?

In all Erlang supervisor examples I have seen yet, there usually is a "master" supervisor who supervises the whole tree (or at least is the root node in the supervisor tree). What if the "master"-supervisor breaks? How should the "master"-supervisor be supervised?? any typical pattern?

A:

The top supervisor is started in your application start/2 callback using start_link, this means that it links with the application process. If the application process receives an exit signal from the top supervisor dying it does one of two things:

If the application is started as an permanent application the entire node i terminated (and maybe restarted using HEART).
If the application is started as temporary the application stops running, no restart attempts will be made.

A:

Typically Supervisor is set to "only" supervise other processes. Which mens there is no user written code which is executed by Supervisor - so it very unlikely to crash.
Of course, this cannot be enforced ... So typical pattern is to not have any application specific logic in Supervisor ... It should only Supervise - and do nothing else.

A:

Good question. I have to concur that all of the examples and tutorials mostly ignore the issue - even if occasionally someone mentions the issue (without providing an example solution):
If you want reliability, use at least two computers, and then make them supervise each other. How to actually implement that with OTP is (with the current state of documentation and tutorials), however, appears to be somewhere between well hidden and secret.


Q:

Flat observable array

Everywhere I see that Knockout observableArray contains dictionary like:
var people = ko.observableArray([
    {
        name: 'john',
        age: 27
    }
]);

But can we have just a flat array like ko.observableArray([1, 2, 3]);? And if yes then how can we iterate over it in template?

A:

Use $data to iterate through a flat array in a template:

        The current item is:

Refer to the docs, section Note 1: Referring to each array entry using $data.


Q:

Can $\mathbb{Z}/n\mathbb{Z}$ (not $(\mathbb{Z}/n\mathbb{Z})^{\times}$) be a group under multiplication?

I was wondering why we usually say $\mathbb{Z}/n\mathbb{Z}$ is a group under addition and invent notation like $(\mathbb{Z}/n\mathbb{Z})^\times$ specifically for the multiplicative group modulo $n$. Can $\mathbb{Z}/n\mathbb{Z}$ (not $(\mathbb{Z}/n\mathbb{Z})^\times$) be a group under multiplication?

A:

We often refer to an abelian group operation as $+$, probably in part because many common abelian groups ($\mathbb{Z}, \mathbb{Q}, \mathbb{R}, \mathbb{C}, \mathbb{Z} / n \mathbb{Z}, \mathbb{F}[x]$, etc.) are underlying groups (under addition) of common ring structures. This becomes slightly peculiar when (as we often do) we use "multiplication" as a synonym for the group operation of a general group.

A:

Presuming that $1 \not\equiv 0 \mod n$, i.e., $n>1$, what could the multiplicative inverse of $0$ be?
The existence of an inverse for each element is the only axiom of a group that is failed by $(\mathbb Z/n\mathbb Z, \cdot)$. Accordingly, in order to form a group, $(\mathbb Z/n\mathbb Z)^\times$ consists of precisely those elements of $\mathbb Z/n\mathbb Z$ which have a multiplicative inverse.


Q:

Signed measure, a sort of integral triangle inequality?

Let $\nu$ be a signed measure. Define$$\int f\,d\nu = \int f\,d\nu^+ - \int f\,d\nu^-.$$Do we necessarily have that$$\left| \int f\,d\nu\right| \le \int |f|\,d|\nu|?$$

A:

\begin{align}
\left|\int f\ \mathsf d\nu\right| &= \left|\int f\ \mathsf d\nu^+ - \int f\ \mathsf d\nu^-\right|\\
&\leqslant \left|\int f\ \mathsf d\nu^+\right| + \left|\int f\ \mathsf d\nu^-\right|\\
&\leqslant \int |f|\ \mathsf d\nu^+ + \int |f|\ \mathsf d\nu^-\\
&= \int |f|\ \mathsf d|\nu|.
\end{align}


Q:

Is there anything like value labels of PSPP in Execl?

I wonder if Excel 2013 has something that will represent number inputs as pre-set labels.
like input 1 in cell A1 but shows as "Computer Science" in the same cell, input 2 shows as "Computer Engineering"
, something like that.
Sorry if my question is unclear, I don't good at english and maybe that's why I can't find my solution on google.
Someone familiar with pspp might easier to understand what i am talking about

A:

Say we want to enter a number between 1 and 92 in cell A1 and have the corresponding element be displayed in the cell.  Enter the following event macro in the worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
   If Intersect(Range("A1"), Target) Is Nothing Then Exit Sub
   Dim I As Long, DQ As String
   DQ = Chr(34)
   I = Range("A1").Value - 1

   ary = Array("Hydrogen", "Helium", "Lithium", "Beryllium", "Boron", "Carbon", _
      "Nitrogen", "Oxygen", "Fluorine", "Neon", "Sodium", "Magnesium", "Aluminium", _
      "Silicon", "Phosphorus", "Sulfur", "Chlorine", "Argon", "Potassium", "Calcium", _
      "Scandium", "Titanium", "Vanadium", "Chromium", "Manganese", "Iron", "Cobalt", "Nickel", _
      "Copper", "Zinc", "Gallium", "Germanium", "Arsenic", "Selenium", "Bromine", _
      "Krypton", "Rubidium", "Strontium", "Yttrium", "Zirconium", "Niobium", "Molybdenum", _
      "Technetium", "Ruthenium", "Rhodium", "Palladium", "Silver", "Cadmium", "Indium", "Tin", _
      "Antimony", "Tellurium", "Iodine", "Xenon", "Caesium", "Barium", "Lanthanum", "Cerium", _
      "Praseodymium", "Neodymium", "Promethium", "Samarium", "Europium", "Gadolinium", _
      "Terbium", "Dysprosium", "Holmium", "Erbium", "Thulium", "Ytterbium", "Lutetium", "Hafnium", _
      "Tantalum", "Tungsten", "Rhenium", "Osmium", "Iridium", "Platinum", "Gold", "Mercury", _
      "Thallium", "Lead", "Bismuth", "Polonium", "Astatine", "Radon", "Francium", "Radium", _
      "Actinium", "Thorium", "Protactinium", "Uranium")

   Range("A1").NumberFormat = DQ & ary(I) & DQ & ";;;"
End Sub

 The value in A1 has not changed, only the display.
Because it is worksheet code, it is very easy to install and automatic to use:

right-click the tab name near the bottom of the Excel window
select View Code - this brings up a VBE window
paste the stuff in and close the VBE window

If you have any concerns, first try it on a trial worksheet.
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:

bring up the VBE windows as above
clear the code out
close the VBE window

To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
To learn more about Event Macros (worksheet code), see:
http://www.mvps.org/dmcritchie/excel/event.htm
Macros must be enabled for this to work!


Q:

  displays a tiny line

when I make   in my site, it displays a tiny line, which can be hidden on some elements because I'm usually using them on CSS buttons, but I have an if statement that says if this show the result if not show a non breaking space.
How do you reset the   to display nothing?

A:

Is this tiny line an outline? Try this in css:
outline:none;

Is this tiny line an underline? Try this in css:
text-decoration:none;

Is that something else, elaborate your question.


Q:

Erro "falha de segmentação" ao executar programa em C no shell linux

Tenho o seguinte programa na linguagem C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char *argv[]){
    FILE *p;
    char str[30], frase[]="Nome do arquivo :", resposta [80];
    int i;
    printf("Informe o nome do arquivo :\n");
    fgets(str ,20,p);
    for(i=0; str[i];i++)
    if(str[i]== ’\n’)
    str[i]=0;
    if (!(p=fopen(str ,"w"))){
      printf("Erro! Não é possível abrir o arquivo. \n");
      exit (1);
    }
    fputs(frase ,p);
    fputs(str ,p);
    fclose(p);
    p = fopen(str ,"r");
    fgets(resposta,atoi (argv[1]) ,p);
    printf("%s \n", resposta );
    fclose(p);
    return (0);
}

Estou compilando através do gcc do linux.
Já fiz várias alterações, aumentei o tamanho das listas de char e mesmo assim o erro "falha de segmentação" persiste logo no início da execução.
Alguém poderia me ajudar?

A:

Não tem sentido você passar a variável p que vem do FILE *p para o fgets() se o intuito for pegar o input "digitado pelo usuário", o erro ocorre justamente porque a variável p não esta "manipulando" nada ainda, logo fgets() não entende o que "você quer fazer".
Se o intuito é pegar o "input" o certo seria ler o stdin, algo como:
printf("Informe o nome do arquivo :\n");
fgets(str ,20, stdin);

Mas creio que este não seja o seu único problema teu for(i=0; str[i];i++) está sem as chavetas {...}, creio que ele até executa a terceira linha de:
for(i=0; str[i];i++)
if(str[i]== ’\n’)
str[i]=0;

Mas qualquer erro ou mudança teu código vai quebrar e outra coisa, que pode ser do seu editor de textos, os apóstrofos parecem estar errados, se estiverem mesmo errados provavelmente vai receber:
error: non-ASCII characters are not allowed outside of literals and identifiers
if (str[i] == ’\n’)
              ^


Q:

SQL Query DBMS Actually Executes When View Query Uses an Aliased Aggregate Function

I'm working on a 3-step homework problem and I'm stumped on the last step. For the last step to make sense, I'll post the entire problem including my solutions for the first two steps:
The Problem and My Solutions for the First Two Steps
Create a view named TRIP_INVENTORY. It consists of the state and the total number of trips for each state. Use UNITS as the column name for the total number of trips for each state. Group and order the rows by state.
a. Write and execute the CREATE VIEW command to create the TRIP_INVENTORY view.
CREATE VIEW TRIP_INVENTORY AS
SELECT STATE, COUNT(TRIP_ID) AS UNITS
FROM TOURS_TRIP
GROUP BY STATE

b. Write and execute the command to retreive the state and units for each state having more than 10 trips.
SELECT STATE, UNITS
FROM TRIP_INVENTORY
WHERE UNITS > 10

The Step that has Me Stumped
c. Write and execute the query that the DBMS actually executes.
This was the unsuccessful query I came up with:
SELECT STATE, COUNT(TRIP_ID) AS UNITS
FROM TOURS_TRIP
WHERE UNITS > 10
GROUP BY STATE

The problem is that the UNITS column alias can't be referenced in the WHERE clause. I can't use an aggregate function in the WHERE clause either. I'm pretty sure I need to use a subquery, but I can't figure out how to structure the constraints so that they will remove the unnecessary states using the results of the nested query.
Can anyone offer any insight?

A:

Depends on the implementation but
b)
SELECT STATE, COUNT(TRIP_ID) AS UNITS
FROM TOURS_TRIP
GROUP BY STATE
having COUNT(TRIP_ID) > 10

c)
Select state, units from (
  SELECT STATE, COUNT(TRIP_ID) AS UNITS
  FROM TOURS_TRIP
  GROUP BY STATE
) temp (state,units)
where units > 10


Q:

Android application to show the battery charging rate (e.g. in mA)

I am looking for an Android application that can show the battery charging rate (e.g. in mA).
Free is better, but paid OK too.

A:

Battery Monitor will show that.
It has the ability to show it as a widget as well as in-app. It's also free (with ads)
It's pretty simple to use. I only used it for a short while but it does what you need.
The feature to show charging rate is a free feature.

Click image for larger version

A:

CurrentWidget also provides the charging information as a widget, and is also free.
CurrentWidget can also stay in your notifications bar to provide information, as well as provide alerts when the phone is using above a certain amount of power which I liked. Didn't really have any cons about them when I was using them.