text:
Q: Beans, methods, access and change? What is the recommened practice for handling them (i.e. in ColdFusion)? I am new to programming (6 weeks now). i am reading a lot of books, sites and blogs right now and i learn something new every day.
Right now i am using coldfusion (job). I have read many of the oop and cf related articles on the web and i am planning to get into mxunit next and after that to look at some frameworks.
One thing bothers me and i am not able to find a satisfactory answer. Beans are sometimes described as DataTransferObjects, they hold Data from one or many sources.
What is the recommended practice to handle this data?
Should i use a separate Object that reads the data, mutates it and than writes it back to the bean, so that the bean is just a storage for data (accessible through getters) or should i implement the methods to manipulate the data in the bean.
I see two options.
1. The bean is only storage, other objects have to do something with its data.
2. The bean is storage and logic, other objects tell it to do something with its data.
The second option seems to me to adhere more to encapsulation while the first seems to be the way that beans are used.
I am sure both options fit someones need and are recommended in a specific context but what is recommended in general, especially when someone does not know enough about the greater application picture and is a beginner?
Example:
I have created a bean that holds an Item from a database with the item id, a name, and an 1d-array. Every array element is a struct that holds a user with its id, its name and its amount of the item. Through a getter i output the data in a table in which i can also change the amount for each user or check a user for deletion from this item.
Where do i put the logic to handle the application users input?
Do i tell the bean to change its array according to the user input?
Or do i create an object that changes the array and writes that new array into the bean?
(All database access (CreateReadUpdateDelete) is handled through a DataAccessObject that gets the bean as an argument. The DAO also contains a gateway method to read more than one record from the database. I use this method to get a table of items, which i can click to create the bean and its data.)

A: You're observing something known as "anemic domain model". Yes, it's very common, and no, it's not good OO design. Generally, logic should be with the data it operates on.
However, there's also the matter of separation of concerns - you don't want to stuff everything into the domain model. For example, database access is often considered a technically separate layer and not something the domain models themselves should be doing - it seems you already have that separated. What exactly should and should not be part of the domain model depends on the concrete case - good design can't really be expressed in absolute rules.
Another concern is models that get transferred over the network, e.g. between an app server and a web frontend. You want these to contain only the data itself to reduce badnwidth usage and latency. But that doesn't mean they can't contain logic, since methods are not part of the serialized objects. Derived fields and caches are - but they can usually be marked as transient in some way so that they are not transferred.

A: Your bean should contain both your data and logic.
Data Transfer Objects are used to transfer objects over the network, such as from ColdFusion to a Flex application in the browser. DTOs only contain relevant fields of an object's data.
Where possible you should try to minimise exposing the internal implementation of your bean, (such as the array of user structs) to other objects. To change the array you should just call mutator functions directly on your bean, such as yourBean.addUser(user) which appends the user struct to the internal array.
No need to create a separate DAO with a composed Gateway object for your data access. Just put all of your database access methods (CRUD plus table queries) into a single Gateway object.


text:
Q: How to retrieve error code from cURL on shell I know a similar question was posted, but I can't get it to work on my machine.
I tried the 1st answer from the mentioned question, i.e. response=$(curl --write-out %{http_code} --silent --output /dev/null servername) and when I echo $response I got 000 [Not sure if that is the desired output].
However, when trying to do so with my cURL command, I get no output.
This is my command:
curl -k --silent --ftp-pasv --ftp-ssl  --user C:is_for_cookies --cert localcert_cert.pem --key certs/localcert_pkey.pem ftps://10.10.10.10:21/my_file.txt

and I use it with
x=$(curl -k --silent --ftp-pasv --ftp-ssl  --user C:is_for_cookies --cert localcert_cert.pem --key certs/localcert_pkey.pem ftps://10.10.10.10:21/my_file.txt)
but when I try to echo $x all I get is a newline...
I know the cURL is failing, because when I run the same command, without --silent, I get curl: (7) Couldn't connect to server
This Q is tagged with both sh, bash because I've tried it on both with same results

A: I found this option which kind of helps (but I still don't know how to assign it to a variable, which should be easier than this...):
   --stderr <file>
          Redirect all writes to stderr to the specified file instead. If the file name is a plain '-', it is instead written to stdout.

          If this option is used several times, the last one will be used.

When I use it like this:
curl -k --silent -S --stderr my_err_file --ftp-pasv --ftp-ssl  --user C:is_for_cookies --cert localcert_cert.pem --key certs/localcert_pkey.pem ftps://10.10.10.10:21/my_file.txt

I can see the errors (i.e. curl: (7) Couldn't connect to server) inside that file.
I used --silent to suppress all output, and -S to un-suppress the errors, and the --stderr <file> to redirect them

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to clear a window at runtime? I am just learning Python.  I have a program that will choose a random image each time you click the mouse!!  How do I clear the window so images don't stack.  I am sure I am asking this question wrong because google is no help :(
Thank you and here is the code:
from graphics import*
import random
import os

win = GraphWin("My Window", 500, 500)

for x in range(5):

    cards = ["1.gif","2.gif","3.gif"]
    rand_card = random.choice(cards)
    img = Image(Point(250, 250), rand_card)

    win.setBackground('Black')
    img.draw(win)

    win.getMouse()

A: Based on the code at http://mcsp.wartburg.edu/zelle/python/graphics.py, the Image class has an undraw function.  You can simply add image.undraw() with a check to make sure it's not None (as it would be for the first time in the loop:
img = None
win = GraphWin("My Window", 500, 500)

for x in range(5):

    cards = ["1.gif","2.gif","3.gif"]
    rand_card = random.choice(cards)
    if img:
        img.undraw()
    img = Image(Point(250, 250), rand_card)

    win.setBackground('Black')
    img.draw(win)

    win.getMouse()

(Note, change added based on cdlane's comment - initialize img to None so we don't get variable undefined.)


text:
Q: private internal maven repository I wonder whether I can setting up a private maven repository based on my svn.
The svn can be accessed via http.
If yes, then what should I do? Just uploading the architypes is enough?

A:
If yes, then what should I do? Just uploading the architypes is enough?

While subversion is not really made for that, yes, Maven can deploy through WebDAV so it is possible (a lot of people are actually doing this for their google-code projects).
If you want to set this up for an existing maven project (and have the created artifacts deployed to your SNV repository during the deploy phase), adapt the solution described in Hosting a Maven repository on Google Code.
If you just want to add a particular artifacts, use the deploy:deploy-file goal:
mvn deploy:deploy-file \
    -DrepositoryId="internal" \
    -Durl="dav:https://server/repo" \
    -Dfile="some-jar.jar" \
    -DgroupId="my.groupid" \
    -DartifactId="my-artifactid" \
    -Dversion="1.2.3" \
    -Dpackaging=jar \
    -DgeneratePom=true

Under GNU/Linux, you can paste this command as is; under Windows, run it on one line without the \.

A: The question shouldn't be can you but should you. Yes you can. No you shouldn't. Instead of using a tool designed to manage source diffs for binary storage, instead get an artifact repository manager like Nexus to manage the binaries. Repository managers have tons of features designed especially to host, share, promote, secure binaries that you don't find in a typical scm. For example an scm has no capability to appropriately deal with maven snapshots.
If you want more information about why you should use a repository manager, take a look at the documents here.


text:
Q: Add dummy layer so that layer with "soft light" blending mode is visible by itself I have a QGIS project with three raster layers:

*

*SRTM GeoTiff (blending mode: SOFT LIGHT; color ramp: Viridis)

*Google Terrain (blending mode normal)

*Google Satellite (blending mode normal)

The problem is: if I display ONLY layer 1, nothing is visible, because it has nothing below to "blend with".
So my question is: is there a way to create a "solid color" layer, so that an upper layer with blending mode different than "normal" (and particularly with "soft light") can be visible somehow?

If I hide layer 2, I have the following result:

And if I display only layers 1 and 2 (layer 3 might be one or off), this is the result:

A: I usually just make a polygon layer containing a single feature covering the whole mapped area to achieve this, and style it with a simple fill of the desired colour.


text:
Q: How to restrict python module to be installed in specific version of Python? After wasting a couple of days with this, I'm asking for help.
I'm trying to specify Python 2.7 in setup.py:
from setuptools import setup, find_packages

setup(
name = 'MyPackageName',
version = '1.0.0',
url = 'https://github.com/mypackage.git',
author = 'Author Name',
author_email = 'author@gmail.com',
description = 'Description of my package',
packages = find_packages(),
python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*',
)

My pip version is 9.0.1 (in Python 27)
My setuptools verion is 38.4.0 (in Python 27)
I have 3 Pythons installed: 2.5, 2.7, 3.6
I'm building an exe with (Python 27):

python setup.py bdist_wininst

which creates nice MyPackageName-1.0.0.win32.exe
This is what I'm trying to achieve(numpy example with Py 2.5):

This is what I have:

I would greatly appreciate any hints.

A: Use --target-version to restrict the interpreter version:
$ python setup.py bdist_wininst --target-version 2.7

will build the installer MyPackageName-1.0.0.win32-py2.7.exe. When installing, it will restrict the list of found versions to match the target one, or show an error dialog in there are none. Passing the option multiple times will generate multiple installers for each version, e.g.
$ python setup.py bdist_wininst --target-version 2.5 --target-version 2.7

will generate two installers, MyPackageName-1.0.0.win32-py2.5.exe and MyPackageName-1.0.0.win32-py2.7.exe.


text:
Q: Facebook Login Button handling I am using facebook login button in my app but when user clicks on login I have to get his current location using gps
I am able to show the alert dialog for GPS not enabled if its not enabled it should not redirect to Facebook login page, but it still goes to facbook login page
loginButton = (LoginButton) findViewById(R.id.act_reg_fb_login);
callbackManager = CallbackManager.Factory.create();
loginButton.setOnClickListener(this);

handling the login button click listner
case R.id.act_reg_fb_login:
        if(isGettingHomeEntityData)

{
    List<String> permissions = new ArrayList<>();
    permissions.add("public_profile");
    permissions.add("email");
    permissions.add("user_likes");
    permissions.add("user_location");
    permissions.add("user_actions.books");
    loginButton.setReadPermissions(permissions);
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            if (loginResult.getAccessToken() == null) {
                showSignUpLoginIssue(Constants.ErrorIssue.ERR_WHILE_LOGIN);
            } else {
                getEmailFromFaceBookAndLogin(loginResult.getAccessToken());
            }
        }

        @Override
        public void onCancel() {
            UIUtility.showSnackBar(coolMain, getString(R.string.err_facebook_cancelled));
        }

        @Override
        public void onError(FacebookException error) {
            Log.e("fb error", String.valueOf(error));
            UIUtility.showSnackBar(coolMain, error.getLocalizedMessage());
        }
    });
    break;
}

else

{
    initializeLocationVariables();
    break;
}

A: Try this in onCreate() of your Activity
 private AccessTokenTracker accessTokenTracker;

    callbackManager = CallbackManager.Factory.create();
    updateWithToken(AccessToken.getCurrentAccessToken());
    accessTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
            updateWithToken(newToken);
        }
    };
    accessTokenTracker.startTracking();

Also in onStop()
@Override
public void onStop() {
    super.onStop();
    accessTokenTracker.stopTracking();
}

in updateWithToken() method:
 private void updateWithToken(AccessToken currentAccessToken) {

    if (currentAccessToken != null) {
        LoginManager.getInstance().logOut();
    } else {
    }
}


text:
Q: MongoDB rename boundary values for output I have this query to display people in certain age groups.
db.people.aggregate([
    {
      $bucket: {
        groupBy: "$age",
        boundaries: [ 0, 10, 20,  30, Number.POSITIVE_INFINITY ],
        default: Number.NEGATIVE_INFINITY,
        output: {
          "count": { $sum: 1 }
        }
      }
    }
  ])
enter code here

which produces following output:
{ "_id" : 0, "count" : 5 }
{ "_id" : 10, "count" : 10 }
{ "_id" : 20, "count" : 6 }
{ "_id" : 30, "count" : 9 }

I want to display it as
{ "_id" : 0, "count" : 5 }
{ "_id" : 10, "count" : 10 }
{ "_id" : 20, "count" : 6 }
{ "_id" : ">30", "count" : 9 }

How can I make it? Thanks.

A: There's no hacky way this make this happen, you'll have to add a $project
stage and specify the logic you want, like so:

db.people.aggregate([
    {
        $bucket: {
            groupBy: "$age",
            boundaries: [ 0, 10, 20,  30, Number.POSITIVE_INFINITY ],
            default: Number.NEGATIVE_INFINITY,
            output: {
                "count": { $sum: 1 }
            }
        }
    },
    {
        $project: {
            _id: {
                $cond: [{$eq: ['$_id', 30]}, '>30', '$_id']
            },
            count: 1
        }
    }
])


text:
Q: Deploying Rails app with docker-compose Currently I have pretty standard env: nginx + web(Rails) + worker(Sidekiq) + Postgres + Redis + Data Containers(File storage and DB storage).
The deploy process looks pretty straightforward:
 - update source code;
 - rebuild container(s);
 - run migrations;
 - stop old and launch new containers;
For web (rails) and data (pg) containers it would be something like this:
docker-compose build && docker-compose run web rake db:migrate && docker-compose up -d.
Are there any best practices and is this solution compatible with them?
Capistrano uses releases approach (with ability to rollback) - is this approach applicable with Docker? Is it even possible to use Docker and Capistrano?
Please share your solutions or links to success stories.
Thanks!


text:
Q: How to use Node.js to build pages that are a mix between static and dynamic content? All pages on my 5 page site should be output using a Node.js server.
Most of the page content is static. At the bottom of each page, there is a bit of dynamic content.
My node.js code currently looks like:
var http = require('http');

http.createServer(function (request, response) {

    console.log('request starting...');

    response.writeHead(200, { 'Content-Type': 'text/html' });

    var html = '<!DOCTYPE html><title>My Title</title>';
    html += 'Some more static content';
    html += 'Some more static content';
    html += 'Some more static content';
    html += 'Some dynamic content';
    html += '';

    response.end(html, 'utf-8');

}).listen(38316);

I'm sure there are numerous things wrong about this example. Please enlighten me!
For example:

*

*How can I add static content to the
page without storing it in a string as a variable value with += numerous times?

*What is the best practices way to build a small site in Node.js where all pages are a mix between static and dynamic content?

A: Alternative you can just use jsDOM. This means you have a DOM object you can manipulate on the server to add your dynamic content, then you can just flush the DOM as a HTML file / string

A: These days the answer is not so straightforward.
If you don't need to be indexed by Google, consider making a single-page application using socket.io and client-side templates such as jQuery Templates. There are even emerging node.js frameworks for this type of architecture, e.g. socketstream.
If you need to be indexed by Google, do you need your dynamic content to be indexed? If yes,
consider using express and server-side templates such as ejs, jade or mustache. Another (discouraged) approach might be to generate XML from JSON on server and use an XSLT front-end.
If you need only static content to be indexed, consider using express on server, but don't generate any dynamic HTML on server. Instead, send your dynamic content in JSON format to client using AJAX or socket.io, and render it using client-side templates such as jQuery Templates.
Don't consider server-side DOM: DOM doesn't scale for complex layouts, you will sink in a sea of selectors and DOM calls. Even client-side developers understood that and implemented client-side templates. A new promising approach is weld library. It offers best of both worlds, but it is not mature yet to be used in production (e.g. simple things like conditional rendering are not supported yet).

A: One good way is to use a templating engine.  You can store the templates as separate files, and the templating engine has the ability to make the content dynamic.  Personally I use yajet (http://www.yajet.net/) which is written for the web but works fine with node, and there are numerous template engines for node on npm.

A: One of the best things I found is to use NodeJS, Express and Mustache...
You can create your HTML pages as you normally would using Mustache syntax for placeholders for your variables {{name}}...
When a user hits your site, express routs the slug to the correct template...
NodeJS get's the file...
NodeJS get's the dataset from a DB...
Run it through Mustache on the server...
Send the completed page to the client...
Here is a scaled back version I wrote on my blog.  It's simple but the idea is pretty sound.  I use it to quickly deploy pages on my site.
http://devcrapshoot.com/javascript/nodejs-expressjs-and-mustachejs-template-engine
I went this route because I didn't want to learn all of the extra syntax to write a language I already knew (html).  It makes more sense and follows more of a true MVC pattern.

A: Personally, I'd use a server that has higher level constructs. For instance, take a look at the expressjs framework - http://expressjs.com/
The constructs you'll be interested in from this package are:

*

*Truly static files (assets etc): app.use(express.static(__dirname + '/public'));

*A templating language such as jade, mustache, etc:

*

*http://expressjs.com/en/guide/using-template-engines.html

*https://github.com/visionmedia/jade/

*You'll want to look up 'locals' and 'partials' for embedding small bits of dynamic content in mostly static content

For example in jade:
!!! 5
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript')
      if (foo) {
         bar()
      }
  body
    h1 Jade - node template engine
    #container
      - if (youAreUsingJade)
        p You are amazing
      - else
        p Get on it!

Becomes:
<!DOCTYPE html>

    <title>Jade</title>

Jade - node template engine

You are amazing

If you prefer something a little less drastic I would say look at mustache or one of the other engines that looks a bit more like regular-sauce html.

A: First deliver only static HTML files from server to the client. Then use something like AJAX / server.io to serve the dynamic content. IMO Jade is really ugly for writing HTML code and its better to use a template engine.
I did some Google and found some code by this fellow, its good if you are doing it for PoC / learning.
var server = require('./server');
var controller = require("./controller");
var urlResponseHandlers = require("./urlResponseHandlers");

var handle = {};
handle["/"] = urlResponseHandlers.fetch;
handle["/fetch"] = urlResponseHandlers.fetch;
handle["/save"] = urlResponseHandlers.save;
server.start(controller.dispatch, handle);

Here is how the logic for handling URLs is displayed -
var staticHandler = require('./staticHandler');

function dispatch(handler, pathname, req, res) {
  console.log("About to dispatch a request for " + pathname);
  var content = "Hey " + pathname;
  if (typeof handler[pathname] === 'function') {
      content += handler[pathname](req);
      res.writeHead(200, {
          'Content-Type': 'text/html'
      });
      res.write(content);
      res.end();
  } else {
      console.log("No request handler found for " + pathname);
      staticHandler.handleStatic(pathname, res);
  }

}
Here is how static files can be handled -
function handleStatic(pageUrl, response) {
    var filename = path.join(process.cwd(), pageUrl);
    path.exists(filename, function (exists) {
        if (!exists) {
            console.log("not exists: " + filename);
            response.writeHead(404, {
                'Content-Type': 'text/html'
            });
            response.write('404 Not Found\n');
            response.end();
            return;
        }
        //Do not send Content type, browser will pick it up.
        response.writeHead(200);
        var fileStream = fs.createReadStream(filename);
        fileStream.on('end', function () {
            response.end();
        });
        fileStream.pipe(response);
        return;
    });
}
exports.handleStatic = handleStatic;

I liked the idea. All code copied from this link!
.

A: A solution have found to this, without using any other modules and or other script is to make the calling script into a module and include it with the function require().
With this solution I can use javascript which ever way I want
What I would do is make an ajax call to a nodejs script (www.example.com/path/script.js)
script.js would need to be built like a module with the exports.functionName=function(){...}
After that include it in your webserver function require(pathToTheScript).functionName(res,req)
You will also need to end the response in the functionName(res,req) by doing res.end();


text:
Q: Exit prompt is not working when use Navigation.PushAsync for loading a new page I am showing a prompt for the exit when a user taps the device back button on the home page.
My code:
private bool AcceptBack;
public static Action EmulateBackPressed;

protected override bool OnBackButtonPressed()
{
    bool value = true;
    var i = this.Children.IndexOf(this.CurrentPage);
    if (i == 0)
    {
        if (AcceptBack)
            return false;
        PromptForExit();
        value = true;
    }
    else
    {
        CurrentPage = Children[0];
        value = true;
    }
    return value;
}

private async void PromptForExit()
{
    if (await DisplayAlert("Confirm to Quit?", "Are you sure you want to quit?", "Yes", "No"))
    {
        AcceptBack = true;
        EmulateBackPressed();
    }
}

On MainActivity:
Pages.CarouselHomePage.EmulateBackPressed = OnBackPressed;

It was working fine when I use the Navigation.PushModalAsync to load new pages. Currently, I am using Navigation.PushAsync for loading new pages; after that, the exit prompt is not showing. When I tap the backbutton it showing the previous page. In my case the homepage is a CarouselPage having 3 children.

A: You need to move the logic of handling navigation to the method OnAppearing .As in the
constructor the page has not finished loading yet .
protected override void OnAppearing()
{
    base.OnAppearing();

    try
    {
        string login = Application.Current.Properties["islogin"].ToString();

        if (login == "true"&&isFirstLoad)
        {
            Navigation.PushAsync(new CarouselHomePage(), true);
        }
    }
    catch (Exception e)
    {
        Debug.WriteLine("IsLogin::" + e);
    }
    isFirstLoad = false;
}

public async void LoadMainPage(Object sender, EventArgs e)
{
    Application.Current.Properties["islogin"] = "true";
    await Application.Current.SavePropertiesAsync();

    App.Current.MainPage = new NavigationPage(new CarouselHomePage());
}

in CarouselHomePage
private async void PromptForExit()
{

    if (await DisplayAlert("Confirm to Quit?", "Are you sure you want to quit?", "Yes", "No"))
    {
        Application.Current.Properties["islogin"] = "false";
        await Application.Current.SavePropertiesAsync();

        AcceptBack = true;
        App.Current.MainPage = new NavigationPage(new LoginPage());
    }
}


text:
Q: Prove that the integral of a product of two functions if finite A have two functions $g(\mathbf{x})$ and $f(\mathbf{x})$, where $\mathbf{x}$ is a d-dimensional vector that belong to the $d-1$-dimensional simplex $S$.
If I know that
$$
\int_{\mathcal{S}}  g(\mathbf{x}) d \mathbf{x}< \infty,
$$
$$
\int_{\mathcal{S}}  f(\mathbf{x}) d \mathbf{x}< \infty
$$
 and  for any  $\mathbf{x}$ I have that $g(\mathbf{x})>0$ and $f(\mathbf{x})>0$.
Can I say that the
$$
\int_{\mathcal{S}}  g(\mathbf{x})f(\mathbf{x}) d \mathbf{x}< \infty? (1)
$$
How can I prove it? which are the conditions that makes (1) true?
EDIT:
I added the domain of $\mathbf{x}$ and the integration.


text:
Q: Cucumber feature file runs on the command line but not in Intellij: Can't load step definitions (undefined) The Cucumber feature file runs on the command line, but not in Intellij. I believe this means there are additional configuration steps that I'm missing.
I am using Windows 7, Intellij IDEA 13.1.3, Ruby 1.9.3, Cucumber 1.3.4
Here is my project folder structure:
\cucumber
  \projectName
    \features
     -mainFeature.feature
      \step_definitions
       -helperFeature.feature

On the command line I navigate to the cucumber folder:
E:\path\to\cucumber\folder\

Then I execute the following command:
bundle exec cucumber projectName/features/mainFeature.feature

And this command runs the cucumber test case successfully.
When I try to run the cucumber test case in Intellij, Intellij is unable to find/load the step definitions. It says that I "can implement step definitions for undefined steps with these snippets" for every single step I use in my features.
The specific error message is:
You can implement step definitions for undefined steps with these snippets:

Then(/^verify the same\-date destination airport grouping strategy$/) do
  pending # express the regexp above with the code you wish you had
end
1 scenario (1 undefined)
5 steps (5 undefined)
0m0.014s

Under "Run > Edit Configurations" I've defined the following on the configuration tab:
Feature file:          E:\path\to\cucumber\folder\projectName\features\scratchpad_grouping_strategy.feature
Runner options:        --color -r features
'cucumber' gem:        1.3.4
Working directory:     E:\path\to\cucumber\folder\
Environment variables: [environment variables]
Ruby arguments:        -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift);
Ruby SDK:              Use other SDK  -> 'cucumber' gem: ruby 1.9.3

And under the Bundler tab:
Run the script in context of the bundle (bundle exec) is checked

Suggestions?

A: I had to specify my working directory correctly. Below is my directory
My working directory: /user/jchiang/test/cucumber
My cucubmer feature files: /user/jchiang/test/cucumber/features
My cucubmer step definitions:/user/jchiang/test/cucumber/lib


text:
Q: Calculating areas of different raster classes in R? I have generated a raster as a *.tiff file in R, with four classes. I'd like to calculate the area occupied by each raster class. Each class has a value (-5, -4, -3, -2) - I expect that I could also count the number of pixels in each raster class and multiply it with the cell size (0.23, I believe).
How can I calculate the area per class?

A: Even if your raster is lat-long and therefore varying cell area, you can do this in R by adding the areas that correspond to cells with your values using the base tapply function:
First set up some dummy data:
> r = raster()
> r[] = sample(-5:-2, ncell(r), replace=TRUE)

Then do this:
> tapply(area(r), r[], sum)
       -5        -4        -3        -2
126376977 126301228 125943687 129736879

area(r) creates a raster where each cell has its area as its value. tapply then sums this over areas grouped by the value in r.

A: This can be done using dplyr with something like the following:
library(dplyr)
library(raster)

r = raster()
r[] = sample(-5:-2, ncell(r), replace=TRUE)

as.data.frame(r) %>%
  group_by(layer) %>%
  tally() %>%
  mutate(area = n * res(r)[1] * res(r)[2])

# A tibble: 4 x 3
  layer     n  area
  <int> <int> <dbl>
1    -5 16260 16260
2    -4 16285 16285
3    -3 16203 16203
4    -2 16052 16052

A: You can also just get at the cell frequencies and proportions. If in a projected coordinate system then you can get the class areas by multiplying resolution by cell counts.
library(raster)
r <- raster(matrix(round(runif(25*25, 1, 4)),25,25))
  ( f <- freq(r) )
    ( p <- data.frame(f, p=f[,2] / sum(f[,2])) )

A: Here's another option that should work. Replace -5 with the value for each class. It determines the number of pixels in each class and then multiplies that by the area of each pixel (i.e., the resolution squared).
vals <- getValues(myraster)
length(subset(vals, vals == -5)) * res(myraster)^2


text:
Q: Windows 8 Release Preview - Extremely High Idle CPU Usage Using Windows 8 RP, my computer is sustaining a 26.6% CPU usage while sitting at the desktop doing absolutely nothing. The other day it was over 50%.
The entire usage is due to a process called "System".
I would blame a faulty task manager, but the usage must be legitimate, as my CPU temperature rises substantially during these periods of use.
My CPU is a 3.6ghz quad core, so the cause cannot be an underpowered CPU.
After a fresh restart, the usage will drop back down to a normal 0-1%.
Does anyone have any idea what's going on?

A: I noticed the same weird behavior with one of my machines(only one of them). As an answer, I could tell you that Windows 8 is still on it's release preview version, and not it's final release, so bugs can still happening. Additionally, I realised that my machine had a different LAN, WAN and Card Reader adapters than the other ones(which were OK), so, probably it is happening due to the fact that all these devices don't have proprietary drivers yet, they are running with Windows 8 default ones. Just wait until Windows 8 release and install proper drivers then this problem will probably miss.


text:
Q: Regex to find directory in text How do I find a path and file name in a block of text?
Before you mark this as duplicate I know questions about file paths exist

*

*Regex for parsing directory and filename (does not match in a paragraph.)

*Regex that matches directory path excluding filepath (this one just match the file name, answer doesn't work for paragraphs, and doesn't address . or spaces)

*java regular expression to match file path (doesn't address . or spaces)

*Regex for extracting filename from path (doesn't address being in a paragraph)

For example
In file included from /some/directoy/3.33A.37.2/something else/dogs.txt,
                 from /some/directoy/something else/dogs.txt,
                 from /some/directoyr/3.33A.37.2/something else/dogs.txt,
                 from /var/log/xyz/10032008.log,
                 from /var/log/xyz/test.c:29:
Solution:
please the file something.h has to be alone without others include, it has to be present in release letter,
in order to be included in /var/log/xyz/test.c and /var/log/xyz/test.h automatically
Other Note:
The file something.c must contain the somethinge.h and not the ecpfmbsd.h because it doesn't contain C operative code.. everything good..

The following are the ideal matches:
/some/directoy/3.33A.37.2/something else/dogs.txt
/some/directoy/something else/dogs.txt
/some/directoyr/3.33A.37.2/something else/dogs.txt
/var/log/xyz/10032008.log
/var/log/xyz/test.c:29 (this is a tricky one, ok with out it)
/var/log/xyz/test.c
/var/log/xyz/test.h

Going further what if I find an answer how can I change it to work with \ instead of / directories

A: You can use a regex like this:
\/.*\.[\w:]+

Working demo

Btw, if you want to allow backslashes in the path you can have:
[\\\/].*\.[\w:]+

A: This looks to be working:
\/[^,:]*\.\w+
See demo.
You can fine-tune this if you know the exact extensions, their lengths and what characters they have. As for me, \w+ would do to match extensions.


text:
Q: javascript how to remove every 3rd element from an array how do i remove every 3rd element from an array?
var TheArray = ['h', 'e', 'z', 'l', 'l', 'l', 'o']

How do I make this say "hello" without creating a new array?

A: Another way to do this is to use the Array.prototype.filter() function. Here is how to remove every 3rd element using it:
var TheArray = ['h', 'e', 'z', 'l', 'l', 'l', 'o']
TheArray = TheArray.filter(function(d, i){ return (i+1)%3 !== 0; })

Hope it helps.

A: Try this:
for (var i = 2; i <= TheArray.length; i += 2)
    TheArray.splice(i, 1);

If you want a string in the end, just use TheArray.join("").

A: If you want a string, don't change the array.
var r = '';
for (var i=0; i<TheArray.length; i++) {
   if (i%3!=2) r += TheArray[i];
}
// now r is "hello"

A: Try this one:
var arr = ['h', 'e', 'z', 'l', 'l', 'l', 'o'];
for(var i = 2; i < arr.length; i+=2)
    arr.splice(i, 1);
console.log(arr); // outputs ['h','e','l','l','o']


text:
Q: Is a constexpr size needed for initialising an array with an explicit size? C++ Primer (5th edition)  states that when an array is initialised with a size, the size provided has to be a constexpr, like this:
int arr[10];

// or

constexpr size_t sz = 10;
int arr[sz];

However, this code compiles just fine for me:
size_t sz = 10;
int arr[sz];

So, is the constexpr really needed?

A: Compiling (g++ -pedantic --std=c++11 -o t t.cpp) in pedantic mode gives:
t.cpp:5:8: warning: variable length arrays are a C99 feature [-Wvla-extension]
int arr[sz];
       ^
1 warning generated.

You may even reject the code with -pedantic-errors.

[C++11: 8.3.4/1]: In a declaration T D where D has the form
D1 [ constant-expressionopt ] attribute-specifier-seqopt [..]

Thus any constant is acceptable, constexpr or const variables.


text:
Q: Body JSON data not received in MVC 5 wep api method In my MVC 5 Web API application, i have a method with signature
public HttpResponseMessage PostDefects(int user, string order, string mode, [FromBody]List<Defect> defects)

This API method is called from jQuery as following
$.ajax({
        type: "POST",
        url: "api/postdefects/123/456/myMode",
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(priv.DefectList),
        success: function () {
            alert('REST call OK');
        },
        error: function() {
            alert('REST call not OK')
        },
        cache: false
    });

On 5 computers this is working without any problem, except 2 computers. For 1 of these computers, the issue got auto-solved without doing anything from my side... On the other one I still have the issue left, and I don't get it solved there.
When I am calling this API from my html page, I receive a 200 (OK) response, but my json body JSON.stringify(priv.DefectList) is not received in the API method. When checking in Fiddler afterwards, I can clearly see that the POST method is receiving the 200 (OK) response, and that the body was sent to the API method. Inside my API method however, I don't receive the object.
My web browser is Google Chrome 42.0.2311.135 m.
Any help would be great!
This is my Defect class
public partial class Defect
{
    public int ID { get; set; }
    public string order { get; set; }
    public string operation { get; set; }
    public string part_nbr { get; set; }
    public string tool { get; set; }
    public string imgName { get; set; }
    public Nullable<int> imgWidth { get; set; }
    public Nullable<int> imgHeight { get; set; }
    public double xPos { get; set; }
    public double yPos { get; set; }
    public int reason { get; set; }
    public string reasonText { get; set; }
    public Nullable<System.DateTime> isRepaired { get; set; }
    public Nullable<System.DateTime> createdTS { get; set; }
    public string severity { get; set; }
    public string mode { get; set; }
    public string badge_nbr { get; set; }
}

And this is an example of the data that is passed
[
    {
        "order":"F00000021489",
        "operation":"0010",
        "part_nbr":"1741845",
        "reason":"6",
        "reasonText":"RWK06 Vosk - poškodenie",
        "xPos":417,
        "yPos":390,
        "imgWidth":880,
        "imgHeight":824,
        "imgName":"1741845_A.png",
        "createdTS":"2015-05-07T08:12:12.109Z",
        "tool":"1741845T05",
        "mode":"REWORK",
        "badge_nbr":"0180371"
    }
]


text:
Q: How can we create custom actions in new/edit/display form SharePoint ribbon? We are using SharePoint 2013 for intranet portal. Not apps.
We have a document library with documents. On clicking the document we get it opened in a modal popup.
On the ribbon of this display form I want to place a clickable item on the ribbon such that, when we click on it, then I want to redirect to an application page with this doc id.
I would also like to know the number of possible ways to do this and the best practice.

A: This can be done by creating a CustomAction.  Specify Location="CommandUI.Ribbon.DisplayForm" in order to place a button in Display form. Here is an example:
<CustomAction
    Id="ExportVersionHistory.DisplayForm"
    RegistrationType="ContentType"
    RegistrationId="0x01"
    Location="CommandUI.Ribbon.DisplayForm"
    Rights="ViewListItems">
        <CommandUIExtension>
            <CommandUIDefinitions>
                <CommandUIDefinition
                 Location="Ribbon.ListForm.Display.Manage.Controls._children">
                    <Button
                     Id="Ribbon.ListForm.Display.Manage.Controls.ExportVersionHistory"
                     Alt="Export version history of the item to Microsoft Excel."
                     LabelText="Export Version History"
                     Image16by16="/_layouts/15/images/NY.ExportVersionHistory/Excel_Small.png"
                     Image32by32="/_layouts/15/images/NY.ExportVersionHistory/Excel_32.gif"
                     Command="ExportVersionHistory"
                     Sequence="99"
                     TemplateAlias="o1"
                     ToolTipTitle="Export Version History"
                     ToolTipDescription="Export version history of the item to Microsoft Excel."/>
                </CommandUIDefinition>
            </CommandUIDefinitions>
            <CommandUIHandlers>
                <CommandUIHandler
                 Command="ExportVersionHistory"
                 CommandAction="~site/_layouts/15/NY.ExportVersionHistory/ExportVersionHistory.aspx?List={ListId}&ID={ItemId}"
                 EnabledScript="javascript:ExportVersionHistoryDisplayFormEnable();"/>
            </CommandUIHandlers>
        </CommandUIExtension>
</CustomAction>


text:
Q: How to log to GKE StackDriver using winston logger? I'm following this instructions to add winston logger to my node backend app.
It is currently running on GKE and normal console.log does show up in stackdriver.
Though, using winston logger doesn't display the logs.
I have just set up the logger like this:
export const logger = winston.createLogger({
  level,
  format: winston.format.simple(),
  transports: [
    new winston.transports.Console({
      handleExceptions: true,
    }),
    new LoggingWinston(),
  ],
  exitOnError: false,
});

I don't need it to log from my local machine, is there anything else I need to configure?

A: It seems that in the following code you've provided, you did not add the following lines such as:
(logger.error),
(logger.info).
These would essential to write the log entries which @JohnHanley had mentioned earlier. Notice that in the doc that you mentioned, those two lines were also included.


text:
Q: How do I get vibration when displaying text or clicking a button? First off, I am a very beginner to Java and coding overall.
I'm trying to make the device vibrate when a certain textbox shows or when I click on a choice button.
However, even though I tried several suggestions from other users, I haven't been able to figure out on how..
I'd appreciate it if you could explain step by step.
Thank you in advance!!
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.os.Vibrator;
import java.util.Arrays;

public class Story {

Hospital1 h1;
String c1, c2, c3, c4, t;

public Story(Hospital1 h1) {
    this.h1 = h1;
}

public void selectNext(String next) {
    switch (next) {
    //  hospital 1
        case "h11": hospital11(); break;
        case "h12": hospital12(); break;
        case "h13": hospital13(); break;
        case "h14": hospital14(); break;
        case "h15": hospital15(); break;
        case "h16": hospital16(); break;
        case "h17": hospital17(); break;
        case "h18": hospital18(); break;
        case "h19": hospital19(); break;

        case "h1s1": hospital1select1(); break;
        case "h110a": hospital110a(); break;
        case "h110b": hospital110b(); break;

        case "h1s2": hospital1select2(); break;
        case "h111a": hospital111a(); break;
        case "h111b": hospital111b(); break;

        case "h112": hospital112(); break;
        case "h113": hospital113(); break;
        .
        .
        .
}

public void showButton() {
    for (Button button : Arrays.asList(h1.choice1, h1.choice2, h1.choice3, h1.choice4)) {
        button.setVisibility(View.VISIBLE);
    }

}

public void noButton() {
    for (Button button : Arrays.asList(h1.choice1, h1.choice2, h1.choice3, h1.choice4)) {
        button.setVisibility(View.INVISIBLE);
    }
}

public void start() {
    h1.background.setImageResource(R.mipmap.hospitalbed);
    h1.character.setImageResource(R.mipmap.god);
    h1.character.setVisibility(View.INVISIBLE);
    h1.text.setText("");
    noButton();
    t = "h11";
}

public void hospital11() {
    h1.character.setVisibility(View.VISIBLE);
    h1.character.setImageResource(R.mipmap.nurse2);
    h1.text.setText("");
    t = "h12";
}

public void hospital12() {
    h1.character.setVisibility(View.INVISIBLE);
    h1.text.setText("");
    t = "h13";
}

public void hospital18() {
    h1.character.setVisibility(View.INVISIBLE);
    h1.text.setText("");
    t = "h14";
}

public void hospital14() {
    h1.character.setVisibility(View.VISIBLE);
    h1.text.setText("");
    t = "h15";

    Vibrator vibrator = (Vibrator) h1.getSystemService(Context.VIBRATOR_SERVICE);
    vibrator.vibrate(1000);
}

public void hospital15() {
    h1.character.setVisibility(View.VISIBLE);
    h1.text.setText("");
    t = "h1s1";
}

public void hospital1select1() {
    h1.character.setVisibility(View.INVISIBLE);
    h1.text.setVisibility(View.INVISIBLE);
    showButton();
    h1.choice1.setVisibility(View.INVISIBLE);
    h1.choice4.setVisibility(View.INVISIBLE);
    h1.choice2.setText("");
    h1.choice3.setText("");

    c2 = "h16a";
    c3 = "h16b";;
}

A: With the assumption that your h1 is a valid Object of Context, h1.getSystemService(Context.VIBRATOR_SERVICE) does not have any compilation error.
Your device should be able to vibrate with this piece of code:
Vibrator vibrator = (Vibrator) h1.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);

But note that the above is deprecated. An updated way to achieve the same purpose is as follow:
VibratorManager vibratorManager = (VibratorManager) h1.getSystemService(Context.VIBRATOR_MANAGER_SERVICE);
Vibrator vibrator = vibratorManager.getDefaultVibrator();
vibrator.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));

And as Vibration requires permission in Android, you need to add permission android.permission.VIBRATE in your AndroidManifest.xml:
<manifest>
    <uses-permission android:name="android.permission.VIBRATE" />

    ...
</manifest>


text:
Q: Bootstrap not loaded when publishing Core MVC site to Azure i have created a asp .net core web application using available template,i made changes to bootstrap in wwwroot and deployed to azure. the changes which i made are working fine locally but it is not reflecting in azure though i can see in the output window the bootstrap is updated while publishing . here is my reference to bootstrap file.
    <environment names="Development">
    <link rel="stylesheet" href="../lib/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="../css/site.css" />
</environment>
<environment names="Staging,Production">
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
          asp-fallback-href="../lib/bootstrap/dist/css/bootstrap.min.css"
          asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
    <link rel="stylesheet" href="../css/site.min.css" asp-append-version="true" />
    <link rel="stylesheet" href="../css/Map.css" asp-append-version="true" />

</environment>

    <environment names="Development">
    <script src="../lib/jquery/dist/jquery.js"></script>
    <script src="../lib/bootstrap/dist/js/bootstrap.js"></script>
    <script src="../js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
            asp-fallback-src="../lib/jquery/dist/jquery.min.js"
            asp-fallback-test="window.jQuery"
            crossorigin="anonymous"
            integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
            asp-fallback-src="../lib/bootstrap/dist/js/bootstrap.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
            crossorigin="anonymous"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
    </script>
    <script src="../js/site.min.js" asp-append-version="true"></script>
</environment>

@RenderSection("Scripts", required: false)


text:
Q: Cannot phoenix::bind qi::_val with boost 1.53 (regression ?) The code below, using boost::spirit, used to work with boost 1.44 and boost 1.49:
qi::string("a_token")
[
    boost::phoenix::bind(&node_t::some_func, *qi::_val, true)
]

I updated boost to version 1.53, but now this code does not compile anymore. g++ complains about
error: pointer to member type 'void (node_t::)(bool)' incompatible with object type 'boost::error_cant_deduce_type'

I can't figure out how to fix it. The following code compiles :
qi::string("a_token")
[
    boost::phoenix::bind(&node_t::some_func, (node_t*)0, true)
]

So I guess the problem is with qi::val_... Did the API of boost::spirit changed or am I missing an include file ?
I'm using g++4.7, with --std=c++0x.
Here I tried a small test case to reproduce the problem. The error message is not the same (but it's still big !), but once again the dereference operator seems to be the problem.
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_bind.hpp>
#include <boost/shared_ptr.hpp>

struct node_t
{
    void foo(bool){}
};

int main()
{
    namespace qi = boost::spirit::qi;

    boost::spirit::qi::rule
    <
        std::string::const_iterator,
        boost::shared_ptr<node_t>(),
        boost::spirit::ascii::space_type
    > rule;

    rule = qi::string("true")
        [boost::phoenix::bind(&node_t::foo, *qi::_val, true)];
}

A: This is an answer made from the helpfull comments above (thanks to llonesmiz).
Changes made in boost::shared_ptr affects old version of boost::pheonix when trying to use the dereference operator * over a boost::shared_ptr.
Before including boost::spirit, #define BOOST_SPIRIT_USE_PHOENIX_V3 1 can be added to the source.
Also, some includes such as #include <boost/spirit/home/phoenix/ ... > are to be removed because it will conflict with spirit v3. Instead, include files such as #include <boost/spirit/include/phoenix.hpp>.


text:
Q: Django model object is deleted when I update the model object that has as foreign key I have this two models in my models.py archive:
class Ticket(models.Model):
    name = models.CharField(max_length=50)
    description_issue = models.CharField(max_length=1000)
    pub_date = models.DateTimeField("publication date", default=timezone.now)

class PossibleSolution(models.Model):
    title = models.CharField(max_length=50)
    description_solution = models.CharField(max_length=1000)
    final = models.BooleanField()
    sol_date = models.DateTimeField("solution date", default=timezone.now)
    tickets = models.ForeignKey(Ticket, blank=True, null=True)

Example: I have a Ticket, with a name, description and the publication date, and then I create a PossibleSolution, and in the form from which I create the PossibleSolution, I choose the related ticket.
Then, in another form, I update the original Ticket, changing it's name, and then I lose the PossibleSolution I created.
What can be happening here?
EDIT: This is the from from where I edit the Ticket
class TicketForm(forms.ModelForm):
    class Meta:
        def __init__(self, *args, **kwargs):
            super(TicketForm, self).__init__(*args, **kwargs)
            self.fields['pub_date'].widget = widgets.AdminSplitDateTime()
            self.fields['closing_date'].widget = widgets.AdminSplitDateTime()
            self.fields['issuer'].widget.attrs['readonly'] = True

        model = Ticket
        fields = '__all__'
        labels = {
            'name': _('Nombre'),
            'description_issue': _('Descripción'),
            'pub_date': _('Fecha de creacion'),
            'closing_date': _('Fecha de cierre'),
            'priority': _('Prioridad'),
            'issuer': _('Creado por'),
            'category': _('Categoría')
        }
        widgets = {
            'pub_date': DateTimeWidget(attrs={'id': "pub_date"}, usel10n=True, bootstrap_version=3),
            'closing_date': DateTimeWidget(attrs={'id': "closing_date"}, usel10n=True, bootstrap_version=3),
        }

And this is the view where I have the POST
def ticket(request, id_ticket):
    if request.method == "POST":
        form = TicketForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            messages.success(request, 'ticket-saved')
            if id_ticket and int(id_ticket) > 0:
                # I have this because I don't know how to really modify
                Ticket.objects.get(id=id_ticket).delete()
            return redirect('index')

A: Remove the line which performs the delete query,
def ticket(request, id_ticket):
    ticket = Ticket.objects.get(id=id_ticket)
    if request.method == "POST":
        form = TicketForm(request.POST, instance=ticket)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            messages.success(request, 'ticket-saved')
            return redirect('index')
    else:
        form = TicketForm(instance=ticket)
    return render(request, 'template_name', {'form':form})


text:
Q: R: data.table. How to save dates properly with fwrite? I have a dataset.  I can choose to load it on R from a Stata file or from a SPSS file.
In both cases it's loaded properly with the haven package.
The dates are recognized properly.
But when I save it to disk with data.table's fwrite function.
fwrite(ppp, "ppp.csv",  sep=",", col.names = TRUE)
I have a problem, the dates dissapear and are converted to different numbers. For example, the date 1967-08-06 is saved in the csv file as -879
I've also tried playing with fwrite options, such as quote=FALSE, with no success.
I've uploaded a small sample of the files, the spss, the stata and the saved csv.
and this is the code, in order to do things easier for you.
library(haven)
library(data.table)
ppp <- read_sav("pspss.sav") # choose one of these two.
ppp <- read_dta("pstata.dta")  # choose one of these two.
fwrite(ppp, "ppp.csv",  sep=",", col.names = TRUE)

The real whole table has more than one thousand variables and one million individuals. That's why I would like to use a fast way to do things.
http://www73.zippyshare.com/v/OwzwbyQq/file.html
This is for @ArtificialBreeze:
> head(my)
# A tibble: 6 x 9
  ID_2006_2011              TIS FECHA_NAC_2006    año2006 Edad_31_12_2006 SEXO_2006
         <dbl>            <chr>         <date>     <date>           <dbl>     <chr>
1  1.60701e+11 BBNR670806504015     1967-08-06 2006-12-31              39         M
2  1.60701e+11 BCBD580954916014     1958-09-14 2006-12-31              48         F
3  1.60701e+11 BCBL451245916015     1945-12-05 2006-12-31              61         F
4  1.60701e+11 BCGR610904916012     1961-09-04 2006-12-31              45         M
5  1.60701e+11 BCMR580148916015     1958-01-08 2006-12-31              48         F
6  1.60701e+11 BCMX530356917018     1953-03-16 2006-12-31              53         F
# ... with 3 more variables: PAIS_NAC_2006 <dbl>, FECHA_ALTA_TIS_2006 <date>,
#   FECHA_ALTA_TIS_2006n <date>

A: Since this question was asked 6 months ago, fwrite has improved and been released to CRAN. I believe it should work as you wanted now; i.e. fast, direct and convenient date formatting. It now has the dateTimeAs argument as follows, copied from fwrite's manual page for v1.10.0 as on CRAN now. As time progresses, please check the latest version of the manual page.
====
dateTimeAs : How Date/IDate, ITime and POSIXct items are written.

*

*"ISO" (default) - 2016-09-12, 18:12:16 and 2016-09-12T18:12:16.999999Z. 0, 3 or 6 digits of fractional seconds are printed if and when present for convenience, regardless of any R options such as digits.secs. The idea being that if milli and microseconds are present then you most likely want to retain them. R's internal UTC representation is written faithfully to encourage ISO standards, stymie timezone ambiguity and for speed. An option to consider is to start R in the UTC timezone simply with "$ TZ='UTC' R" at the shell (NB: it must be one or more spaces between TZ='UTC' and R, anything else will be silently ignored; this TZ setting applies just to that R process) or Sys.setenv(TZ='UTC') at the R prompt and then continue as if UTC were local time.

*"squash" - 20160912, 181216 and 20160912181216999. This option allows fast and simple extraction of yyyy, mm, dd and (most commonly to group by) yyyymm parts using integer div and mod operations. In R for example, one line helper functions could use %/%10000, %/%100%%100, %%100 and %/%100 respectively. POSIXct UTC is squashed to 17 digits (including 3 digits of milliseconds always, even if 000) which may be read comfortably as integer64 (automatically by fread()).

*"epoch" - 17056, 65536 and 1473703936.999999. The underlying number of days or seconds since the relevant epoch (1970-01-01, 00:00:00 and 1970-01-01T00:00:00Z respectively), negative before that (see ?Date). 0, 3 or 6 digits of fractional seconds are printed if and when present.

*"write.csv" - this currently affects POSIXct only. It is written as write.csv does by using the as.character method which heeds digits.secs and converts from R's internal UTC representation back to local time (or the "tzone" attribute) as of that historical date. Accordingly this can be slow. All other column types (including Date, IDate and ITime which are independent of timezone) are written as the "ISO" option using fast C code which is already consistent with write.csv.
The first three options are fast due to new specialized C code. The epoch to date-part conversion uses a fast approach by Howard Hinnant (see references) using a day-of-year starting on 1 March. You should not be able to notice any difference in write speed between those three options. The date range supported for Date and IDate is [0000-03-01, 9999-12-31]. Every one of these 3,652,365 dates have been tested and compared to base R including all 2,790 leap days in this range. This option applies to vectors of date/time in list column cells, too. A fully flexible format string (such as "%m/%d/%Y") is not supported. This is to encourage use of ISO standards and because that flexibility is not known how to make fast at C level. We may be able to support one or two more specific options if required.
====

A: I had the same problem, and I just changed the date column to as.character before writing, and then changed it back to as.Date after reading. I don't know how it influences read and write times, but it was a good enough solution for me.

A: These numbers have sense :) It seems that fwrite change data format into "Matlab coding" where origin is "1970-01-01".
If you read your data, you can simply change number into date using these code:
my$FECHA_NAC_2006<-as.Date(as.numeric(my$FECHA_NAC_2006),origin="1970-01-01")
For example
as.Date(-879,origin="1970-01-01")
[1] "1967-08-06"

A: Since it seems there is no simple solution I'm trying to store column classes and change them back again.
I take the original dataset ppp,
areDates <- (sapply(ppp, class) == "Date")

I save it on an file and I can read it next time.
ppp <- fread("ppp.csv", encoding="UTF-8")

And now I change the classes of the newly read dataset back to the original one.
ppp[,names(ppp)[areDates] := lapply(.SD,as.Date),
 .SDcols = areDates ]

Maybe someone can written it better with a for loop and the command set.
 ppp[,lapply(.SD, setattr, "class", "Date") ,
.SDcols = areDates]

It can be also written with positions instead of a vector of TRUE and FALSE

A: You need to add the argument: dateTimeAs = "ISO".
By adding the argument dateTimeAs = and specifying the appropriate option, you will get dates writting in your csv file with the desired format AND with their respective time zone.
This is particularly important in the case of dealing with POSIXct variables, which are time zone dependant. The lack of this argument might affect the timestamps written in the csv file by shifting dates and times according to the difference of hours between time zones. Thus, the date/time variable POSIXct, you will need to add: dateTimeAs = "write.csv" ; unfortunately this option can be slow (https://www.rdocumentation.org/packages/data.table/versions/1.10.0/topics/fwrite?). Good luck!!!


text:
Q: Is it possible to execute a method after sending a response back to the browser in Rails? I'm trying to run an action after I send a response back to the client in Rails.  Is it possible to do this without background workers or creating new threads?
I looked into the after_filter callback, but it seems like this only lets you execute code before you render the view / response.
Thanks

A: Short answer: No, it is not possible. You have to use threads or some kind of delayed job framework (Sidekiq, Resque, etc.).
Long answer: you actually can use ActionController::Live to control the moment on which your response is 'flushed' to client.
Modified example from the docs:
class MyController < ActionController::Base
  include ActionController::Live

  def stream
    begin
      response.headers['Content-Type'] = 'text/event-stream'
      100.times {
        response.stream.write "hello world\n"
        sleep 1
      }
    ensure
      response.stream.close
    end
    do_my_after_response_job
  end
end


text:
Q: Adjusting screen split pane sizes in tmux I'd like to resize the panes so I can expand / compress the pane sizes (up / down / left / right etc) ..
Any way to get this done?

A: Assuming your prefix key is still the default of CtrlB
To resize down, use: CtrlB:resize-p -D 2
To resize up, use: CtrlB:resize-p -U 2
To resize left, use: CtrlB:resize-p -L 2
To resize right, use: CtrlB:resize-p -R 2
So, this means to first hold Ctrl, then press and release B, then release B, then type a colon (:, which is typically typed by holding Shift and pressing semi-colon ;), then type the word resize and the rest.  Those horizontal lines are common hyphens/dashes/minus-signs.  At the end of the line, issue a "newline" (pressing Enter or Return depending on what is on the keyboard).
The numbers at the end are optional, defaulting to 1.  The -U is also a default, and is unnecessary.
If you ever forget that, ^B ? will show these found to C-Up and C-Down and C-Left and C-Right, at the end of the keys (with the default key bindings).
You could also try pressing Ctrl+B followed by a Ctrl+arrow-keys.
However, note that Ctrl-arrow-keys may be problematic on some terminals.  So you can either try to address the terminal limitations, or create new shortcut key bindings, or just not use shortcuts and use the longer commands shown above.
Update: I've certainly appreciated this question.  It continues to get upvotes years after being initially posted.
The information I provided above should work in a wide variety of circumstances.  For instance, it works when using SSH to control a remote machine that uses OpenBSD which has tmux built-in.
There are some other techniques that some people have found work well for them, and those techniques may use fewer keystrokes.  In particular, it seems like tmux has become built-in on Macs and people have had some success with holding down one or more keys.  Such techniques are not as likely to work in as wide of a variety of scenarios (such as when using different types of computers/operating systems, and possibly remote terminals), but in some environments an alternate method may be a faster way than what is described by these instructions.
This answer has generated a few comments below that describe some alternates that have worked for other people.  If you just want to get the job done with a reliable method, I suggest following the instructions near the top of this answer.  If you want to read even further to see about potentially faster methods, make sure to take the time to review comments under this answer because information there has clearly worked well for people too.

A: One option for resizing panes is to use the mouse. To do this, add these lines to your .tmux.conf:
set -g mode-mouse on
set -g mouse-resize-pane on

If you are on a Mac and the above doesn't work, use this instead (source):
set-option -g mouse on

Once this mode is on, simply click and drag on pane dividers to resize them.

A: Assuming your prefix key is Ctrl-B (Cmd-B on Mac):

*

*Press Ctrl-B and release

*Press and hold Meta (Option on Mac)

*While holding Meta press arrow keys repeatedly to resize current pane

It seems however that there is some timeout so if you don't press an arrow key while holding Meta within 1 or 2 seconds Meta-{arrow} will be considered as an input in current prompt.

A: I just added the following lines to my tmux.conf file
bind j resize-pane -D 10
bind k resize-pane -U 10
bind l resize-pane -L 10
bind h resize-pane -R 10

and now I can use Ctrl-a (my prefix key) with [h|j|k|l] to resize the panes

A: I just discovered another way. Apparently tmux has two different kinds of key presses (assuming that your prefix key is still Ctrlb)

*

*Press Ctrlb, lift your fingers then press one of the arrow keys. This switches focus.

*Press Ctrlb, don't lift your fingers, and then press one of the arrow keys simultaneously. This resizes panes, and I guess is faster than any of the other methods.

In a similar fashion, Ctrlbo also has different behaviours. The first kind of keypress switches focus, and the second kind of keypress swaps panes.

A: On Linux, you should be able to use Ctrl+B, then Ctrl+arrow key, and on my macbook, by default I can use Ctrl+B, then Esc+arrow key.
If you press the arrow keys in rapid succession, you don't need to re-type Ctrl+B.

A: Ctrl B followed by any of these commands. see description in brackets
:resize-pane -D (Resizes the current pane down)
:resize-pane -U (Resizes the current pane upward)
:resize-pane -L (Resizes the current pane left)
:resize-pane -R (Resizes the current pane right)
:resize-pane -D 10 (Resizes the current pane down by 10 cells)
:resize-pane -U 10 (Resizes the current pane upward by 10 cells)
:resize-pane -L 10 (Resizes the current pane left by 10 cells)
:resize-pane -R 10 (Resizes the current pane right by 10 cells)


text:
Q: Wrong data display on stdout: C File Operation I wrote the following code:
main()
{
    FILE *fp;
    fp=fopen("ftest.txt","r");
    char c, filestring[100];
    int i=0;
    while((c=getc(fp))!=EOF)
    {
        filestring[i]=c;
    }
    printf("str is %s",filestring);
    fclose(fp);
}

The file ftest.txt contains the words Hello World.

The output displayed is not correct, it is either some other font or some other encoding.

What is the reason for this? And how do I solve this problem?
At the same time, this code runs well (shows output on stdout in "English"):
 main()
    {
        FILE *fp;
        fp=fopen("ftest.txt","r");
        char c;
        while((c=getc(fp))!=EOF)
        {
            printf("%c",c);
        }
        fclose(fp);
    }

I need the first code to work, as I've to search in the text file. How to solve this?
The question is different from Output is not displying correctly in file operation as I'm able to "display" the correct output (as in second code), but I'm not able to write the contents of the file into a string.
Things I've tried:
1) Changing the mode in which the file is opened from "r" to "rb".
2) Changing the Notepad encoding to all available options: ANSI, UTF etc.

A: There are two parts of the answer:

*

*You never increment i.  This means you're just overwriting the same spot (the first space in the array) in the while loop.  That's why the first value of the junk is a 'd' (the last character of your input).

*The junk after the 'd' is because the array is never initialized, meaning that there is random junk already there that is never overwritten.
Another note: doing the first way would require manually adding a null byte \0 to the end of the array (either by initializing the whole thing to \0s or just after the last character is read in.  This is so the string is read correctly by printf.

A: ... and there's also a third part that's wrong here:
getc() returns an int, you're assigning it to a char before comparing it with EOF, which is defined as -1. If it just so happens that getc returns character 255, it gets assigned to a char, a signed 8 bit value, which results in, in a manner of speaking (char)-1, which then gets signed-extended to -1.


text:
Q: Does the series $ \sum_{n=0}^{\infty}\frac{n^4}{4^n} $ converge? Use a suitable test to justify. I have used the ratio test for series.
Let $a_n = \frac{n^4}{4^n}$
Therefore $\lim_{n\to\infty}| \frac{a_{n+1}}{a_n} |= \lim_{n\to\infty} \frac{(n+1)^4}{4^{(n+1)}} * \frac{4^n}{n^4}$
= $\lim_{n\to\infty} \frac{(n+1)^4}{4n^4} = |\frac{1}{4} | $
Since the ratio is less than 1, the series converges.
Is this correct?

A: Yes, what you have done is correct. Alternatively, we can also use root test as follows:
$$\lim_{n\to\infty}|a_n|^{\frac{1}{n}}=\lim_{n\to\infty}\left(\frac{n^4}{4^n}\right)^\frac{1}{n}=\lim_{n\to\infty}\frac{(n^{\frac{1}{n}})^4}{4}=\frac{1}{4}$$
since $\lim_{n\to\infty}n^{\frac{1}{n}}=1$. Since $\lim_{n\to\infty}|a_n|^{\frac{1}{n}}=\frac{1}{4}<1$, by root test, the series $\sum a_n$ converges.

A: One way to find out (yes, it is cheating ...) is to fire up sympy
(I do use the interface isympy, which uses ipython) and type:
In [1]: summation( n**4/4**n, (n,0,oo))
Out[1]:
380
───
 81

In [2]:

I leave the easy proof for you ... But think about this generalization:
$$
   \sum_{i=0}^{\infty} \frac{ P(i) }{4^i}
$$
should converge for any polynomial $P$,
and thinking about why should help you!
An example:
In [2]: summation( (n**4 + n**8)/4**n, (n,0,oo))
Out[2]:
4673320
───────
  2187


text: Q: pfsense Captive Portal redirect to :8000/$PORTAL_ACTION$ Something is wrong when I try to replace the portal login page with a customized one. After the sign in button is clicked, I was redirected to: (server IP):8000/$PORTAL_ACTION$. What is this $PORTAL_ACTION$ thing, and how do I determine it?


text:
Q: Column 'name' in field list is ambiguous codigniter this is my table structure.
tbl_user:
companyname,name,email.
tbl_userinfo:
phone,address,area,state,city,description.
tbl_category:
category_id,name.
i am joining three tables here is my model
$this->db->select(array('name', 'companyname','phone','address','email','state','city','pincode','area','description','image', 'c.name AS categoryname'));
        $this->db->from('tbl_user');
        $this->db->join('tbl_userinfo', 'tbl_userinfo.user_id = tbl_user.user_id');
        $this->db->join ('tbl_category', 'tbl_category.category_id = tbl_userinfo.service_category');
        $this->db->group_by(array('name', 'companyname', 'phone', 'address', 'email','state','city','pincode','area','description','image','categoryname'));
        //$this->db->order_by('tbl_category.category_id');
        $this->db->where(array('tbl_user.user_id' => 16));

i wanted third column name as well but i m getting Column 'name' in field list is ambiguous codigniter
another code that i did use but it wont show me any values for joining of two table.
$this->db->select(array('tbl_user.name', 'tbl_user.companyname','tbl_userinfo.phone','tbl_userinfo.address','tbl_user.email','tbl_userinfo.state','tbl_userinfo.city','tbl_userinfo.pincode','tbl_userinfo.area','tbl_userinfo.description','tbl_userinfo.image', 'tbl_category.name'));
        $this->db->from('tbl_user');
        $this->db->join('tbl_userinfo', 'tbl_userinfo.user_id = tbl_user.user_id');
        $this->db->join ('tbl_category', 'tbl_userinfo.service_category = tbl_category.category_id');
        $this->db->group_by(array('tbl_user.name', 'tbl_user.companyname','tbl_userinfo.phone','tbl_userinfo.address','tbl_user.email','tbl_userinfo.state','tbl_userinfo.city','tbl_userinfo.pincode','tbl_userinfo.area','tbl_userinfo.description','tbl_userinfo.image', 'tbl_category.name'));
        $this->db->where(array('tbl_user.user_id' => 16));

A: This is most likely happening because two of your tables both have a 'name' column. I would suggest explicitly selecting the column by using [table name].[column].
$result = $this->db->query('past your query here after checking it in an sql browser');

A: Try this:
 $user_id = '16';
 $query = $this->db->select('tbl_user.companyname, tbl_user.name as UserName, tbl_user.email, tbl_userinfo.phone, tbl_userinfo.address, tbl_userinfo.area, tbl_userinfo.state, tbl_userinfo.city, tbl_userinfo.description, tbl_category.category_id, tbl_category.name as CategoryName')
                    ->from('tbl_user')
                    ->join('tbl_userinfo', 'tbl_userinfo.user_id = tbl_user.user_id')
                    ->join ('tbl_category', 'tbl_category.category_id = tbl_userinfo.service_category')
                    ->where('tbl_user.user_id', $user_id)
                    ->group_by('tbl_user.companyname')
                    ->get()
                    ->result();

You can replate 'tbl_user.*' with the columns names you want to get from that table, example: 'tbl_user.user_id, tbl_user.name as UName, tbl_category.name as CName' change the name of column if you have 2 or more columns with the same name in diferent tables you are joining, it will create always an ambiguous error because there are 2 columns with the same name and codeigniter doesn't know which one you want, if you want both you need to rename the both columns.
Also add the join to left because if there is no user_id or category_id it will not display you the result.
Hope this will help you.

A: comes with my own code.
$this->db->select(array('u.name', 'u.companyname','i.phone','i.address','u.email','i.state','i.city','i.pincode','i.area','i.description','i.image', 'c.name AS categoryname'));
        $this->db->from('tbl_user as u');
        $this->db->join('tbl_userinfo as i', 'i.user_id = i.user_id');
        $this->db->join ('tbl_category as c', 'c.category_id = i.service_category');
        $this->db->group_by(array('u.user_id'));
        $this->db->where(array('u.group_id' => 16));
        $query = $this->db->get ();
        return $query->result();


text:
Q: About paging and moving circularly from one page to another In my application am using paging concept with 4 pages along with UIScrollView.
Its working fine but
my problem is
1.
I want to show 2nd page(some part) in 1st page ending,
                3rd page(some part) in 2nd page ending,
         and    4th page(some part) in 3rd page ending.
2.
Now i can move from 1st to 2nd , 2nd to 3rd, 3rd to 4th page again if want to move to 1st page means i have to go pages like 4-3-2-1
but i want to move pages circularly like 1-2-3-4-1-2-3-..... like that
Example code
    NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < kNumberOfPages; i++)
{
    [controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;

// a page is the width of the scroll view
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * kNumberOfPages, 1);
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;

pageControl.numberOfPages = kNumberOfPages;
pageControl.currentPage = 0;

// pages are created on demand
// load the visible page
// load the page on either side to avoid flashes when the user starts scrolling
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];

}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= kNumberOfPages) return;

// replace the placeholder if necessary
WhatsNewViewConroller *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
    controller = [[WhatsNewViewConroller alloc] initWithPageNumber:page];
    [viewControllers replaceObjectAtIndex:page withObject:controller];
    controller.delegateController = self;
}

// add the controller's view to the scroll view
if (nil == controller.view.superview) {
    CGRect frame = scrollView.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    controller.view.frame = frame;
    [scrollView addSubview:controller.view];
}

}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
    // do nothing - the scroll was initiated from the page control, not the user dragging
    return;
}

// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;

// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];

// A possible optimization would be to unload the views+controllers which are no longer visible

}
Here am changing page
- (IBAction)changePage:(id)sender {
int page = pageControl.currentPage;

// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];

// update the scroll view to the appropriate page
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];

// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
pageControlUsed = YES;

}
Any one can help or suggest.
Thanks in advance

A: When you are loading new page, instead of using page-1, page and page+1; use (page -1)%4 , page%4 and (page+1)%4


text:
Q: Создать сайт без хостинга Я конечно в этом не разбираюсь, и если что не так спросил, пожалуйста, не надо оскорблять. Так вот.
Хочется сделать свой личный сайт. Дело в том, что я не хочу пользоваться общественным хостингом. Хочется, чтобы ссылка на сайт была известна только мне и (можно так выразиться) доверенным лицам. Как раз нагрузка на сайт будет маленькая.
Можно же как-нибудь такое устроить?
[Правка {Желательно, чтобы данные сайта никто узнать не мог. Я конечно не разбираюсь в хостингах, но на всякий случай дополняю}]

A: Вы не сообщили ничего о том, что имеете как базу для такого желания. Поэтому ответы будут очень широкими. Если не вдаваться в подробности то план построения такой:

*

*На домашний компьютер устанавливается программа web-сервер. Это может быть apache, nginx, lighttpd, iis в зависимости от операционной системы на домашнем компьютере. Кроме того вам скорее всего понадобится поддержка баз данных (например, mysql) и некоторых языков программирования (например, php), на которых обычно пишут сайты. Бывают и готовые наборы типа Denwer - при их установке вы фактически получите ранее указанные программы и они будут настроены для работы друг с другом.

*После этого надо собственно создать ваш сайт. При этом вы можете задать и параметры зашиты от посторонних. Можно делать это как силами самого сайта так и силами web-сервера (например, можно запрашивать пароль при подключении к сайту). Есть еще возможность для открытых сайтов указать какую информацию должны игнорировать поисковики при сканировании сайта.

*Обеспечить работу вашего "сервера" с внешним миром. Проверить настройки firewall/Брандмауэра. При наличии роутера для связи с внешним миром, сделать в нем настройки для доступа интернет пользователей к локальному компьютеру.

*на этом этапе пользователи уже смогут заходить к вам по вашему ip адресу. Узнать адрес можно, например, зайдя на сайт 2ip.ru Как уже писали выше, этот адрес может быть постоянным или иногда меняться на другой в зависимости от способа работы вашего провайдера.

*Если вы хотите купить имя/адрес для вашего сайта или достали бесплатный вариант, то на сайте dns-провайдера (того кто продает вам адрес) вы указываете соответствие этого адреса вашему ip-адресу. Если ip-адрес у вас не постоянный (динамический), то вам помогут провайдеры dynDns. В последнем случае, ваш компьютер или роутер (в зависимости от их возможностей и вашего способа подключения к интернету) самостоятельно будет подключаться к службе ddns и каждый раз указывать текущий ip-адрес

Вот как-то так...

A: Попробуйте Github Pages. Этот сервис бесплатный и Вы сможете хостить на нём простые веб-сайты(без php, простой html+css+js). Но такой сайт могут просамтривать все и, если не ошибаюсь, его код тоже.

A: Для того чтобы сделать сайт тебе надо:
1 Узнать какой у тебя ip адрес статический или динамический. Эту информацию можно узнать у провайдера.
2 Определиться с веб сервером это зависит от операционной системы и того что ты хочешь от сайта.
3 Сам сайт.


text:
Q: Why smaller data set is hashed in memory for a hash join Why in a hash join, it is the smaller data set that is held in memory? I understand that holding the smaller set saves memory space, but it does mean that we need to iterate over the bigger data set, so is that not bad for performance?

A: The idea is to make a single pass over the bigger set (which you have to read at least once anyway), and multiple passes over the smaller (which is made even faster by having it in memory).


text:
Q: IBM Worklight - How to add barcode scanner phonegap plugin into config.xml in Xcode 5? I'm using IBM Worklight for my mobile app (iOS) project.
My question is: How to add a Barcode Scanner PhoneGap plug-in into config.xml in Xcode 5? I just found this config.xml in xcode. I found this documentation from phonegap's site.
config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<widget>
    <preference name="AllowInlineMediaPlayback" value="false" />
    <preference name="AutoHideSplashScreen" value="true" />
    <preference name="BackupWebStorage" value="cloud" />
    <preference name="DisallowOverscroll" value="false" />
    <preference name="EnableViewportScale" value="false" />
    <preference name="FadeSplashScreen" value="true" />
    <preference name="FadeSplashScreenDuration" value=".25" />
    <preference name="HideKeyboardFormAccessoryBar" value="false" />
    <preference name="KeyboardDisplayRequiresUserAction" value="true" />
    <preference name="KeyboardShrinksView" value="false" />
    <preference name="MediaPlaybackRequiresUserAction" value="false" />
    <preference name="ShowSplashScreenSpinner" value="false" />
    <preference name="SuppressesIncrementalRendering" value="false" />
    <preference name="TopActivityIndicator" value="gray" />
    <preference name="GapBetweenPages" value="0" />
    <preference name="PageLength" value="0" />
    <preference name="PaginationBreakingMode" value="page" />
    <preference name="PaginationMode" value="unpaginated" />
    <preference name="EnableLocation" value="false" /><!-- DEPRECATED -->
    <preference name="UIControls" value='{"TabBarSettings": {"position": "bottom", "height": 49}, "ToolBarSettings": {"style": "Default"}}'/>

    <feature name="LocalStorage">
        <param name="ios-package" value="CDVLocalStorage" />
    </feature>
    <feature name="Battery">
        <param name="ios-package" value="CDVBattery" />
    </feature>
    <feature name="Camera">
        <param name="ios-package" value="CDVCamera" />
    </feature>
    <feature name="Console">
        <param name="ios-package" value="CDVLogger" />
    </feature>
    <feature name="Contacts">
        <param name="ios-package" value="CDVContacts" />
    </feature>
    <feature name="Device">
        <param name="ios-package" value="CDVDevice" />
    </feature>
    <feature name="Accelerometer">
        <param name="ios-package" value="CDVAccelerometer" />
    </feature>
    <feature name="Compass">
        <param name="ios-package" value="CDVCompass" />
    </feature>
    <feature name="Notification">
        <param name="ios-package" value="CDVNotification" />
    </feature>
    <feature name="File">
        <param name="ios-package" value="CDVFile" />
    </feature>
    <feature name="FileTransfer">
        <param name="ios-package" value="CDVFileTransfer" />
    </feature>
    <feature name="Geolocation">
        <param name="ios-package" value="CDVLocation" />
    </feature>
    <feature name="Globalization">
        <param name="ios-package" value="CDVGlobalization" />
    </feature>
    <feature name="InAppBrowser">
        <param name="ios-package" value="CDVInAppBrowser" />
    </feature>
    <feature name="Media">
        <param name="ios-package" value="CDVSound" />
    </feature>
    <feature name="Capture">
        <param name="ios-package" value="CDVCapture" />
    </feature>
    <feature name="NetworkStatus">
        <param name="ios-package" value="CDVConnection" />
    </feature>
    <feature name="SplashScreen">
        <param name="ios-package" value="CDVSplashScreen" />
        <param name="onload" value="true" />
    </feature>
    <feature name="Vibration">
        <param name="ios-package" value="CDVVibration" />
    </feature>

    <!--worklight-->
    <feature name="DeviceAuth">
        <param name="ios-package" value="DeviceAuthPlugin" />
    </feature>
    <feature name="UserAuth">
        <param name="ios-package" value="UserAuthPlugin" />
    </feature>
    <feature name="WebResourcesDownloader">
        <param name="ios-package" value="WebResourcesDownloader" />
    </feature>
    <feature name="WLNotification">
        <param name="ios-package" value="WLNotification" />
    </feature>
    <feature name="WLApp">
        <param name="ios-package" value="WLApp" />
    </feature>
    <feature name="UIControls">
        <param name="ios-package" value="UIControls" />
    </feature>
    <feature name="Push">
        <param name="ios-package" value="Push" />
    </feature>
    <feature name="NetworkDetector">
        <param name="ios-package" value="NetworkDetector" />
    </feature>
    <feature name="NativePage">
        <param name="ios-package" value="NativePage" />
    </feature>
    <feature name="SecurityPlugin">
        <param name="ios-package" value="SecurityPlugin" />
    </feature>
    <feature name="StoragePlugin">
        <param name="ios-package" value="StoragePlugin" />
    </feature>
    <feature name="AnalyticsConfigurator">
        <param name="ios-package" value="AnalyticsConfigurator" />
    </feature>
    <feature name="FIPSHttpPlugin">
        <param name="ios-package" value="FIPSHttpPlugin" />
    </feature>
    <feature name="Badge">
        <param name="ios-package" value="Badge" />
    </feature>
    <feature name="NotificationEx">
        <param name="ios-package" value="NotificationEx" />
    </feature>
    <feature name="WifiPlugin">
        <param name="ios-package" value="WifiPlugin" />
    </feature>
    <feature name="CoreLocationGetLocationPlugin">
        <param name="ios-package" value="CoreLocationGetLocationPlugin" />
    </feature>
    <feature name="CoreLocationWatchPlugin">
        <param name="ios-package" value="CoreLocationWatchPlugin" />
    </feature>
    <feature name="SignificantChangeWatchPlugin">
        <param name="ios-package" value="SignificantChangeWatchPlugin" />
    </feature>
    <feature name="SignificantChangeGetLocationPlugin">
        <param name="ios-package" value="SignificantChangeGetLocationPlugin" />
    </feature>

    <access origin="*" />
</widget>

You can check my repo here: https://github.com/datomnurdin/worklight-mobile

A: At the bottom of config.xml, add the following:
<feature name="your-plugin-name">
    <param name="io-package" value="your-plugin-name">
</feature>

Basically, just follow the structure of all the rest of the Cordova plug-ins that are declared there...
But why not read the training module Worklight provides (sample project), also for this purpose with step-by-step instructions?

*

*Slide 7: shows what you need to add to the config.xml file

*Slide 13 onwards: shows what you need to do in Xcode

*All other slides: How to use the plug-in in Worklight. JS and Objective-C sides

If you intend on using Cordova plug-ins in a Worklight application, this training module is a required reading; even though it talks about creating your own Cordova plug-in, it is also relevant if you intend on adding a Cordova plug-in you've found on the web, and how to use it in the context of Worklight.
Related:

*

*Adding native functionality to hybrid apps with Apache Cordova

*IBM Worklight 6.1 - How to add custom written native code from Eclipse to Xcode?


text:
Q: Compiled directive with isolate scope variable coming up undefined I need to compile a directive because it needs an ID that comes back from the DB, but can't seem to get that to persist through to the directive.
$scope.orderInfo = {
  orderId: 'lkdfj232jh'
};
$scope.compile = function() {
   var html = $compile('<apps orderId="orderInfo.orderId"></apps>')($scope);
   $('#apps').append(html);
};

return {
  templateUrl: 'apps.html',
  restrict: 'E',
  scope: {
    orderId: '='
  },
  controller: function($scope) {
    console.log($scope.orderId);
  }
}

orderId is always undefined inside directive.
Plunker

A: Attribute name should be order-id(hyphenated) not orderId
$scope.compile = function() {
   var html = $compile('<apps order-id="orderInfo.orderId"></apps>')($scope);
   $('#apps').append(html);
};

Working Plnkr


text:
Q: Outer measure and Measurable set Let $ Ω =  \mathbb{N} \times \mathbb{N} = { (i,j) : i,j ∈ \mathbb{N}}$,
and for any set  $ A \subset Ω $ , let $μ(Α)$ be the number of distinct first coordinates among the points in $A$, i.e,
$μ(Α)$ = #( { $i:$ there exists $j ∈  \mathbb{N}$ such that $(i,j) ∈ A $} , $A \subset Ω$.
Note that $μ$  can be written as
$ μ(Α) =$ # $( π_1 (Α))$ $A \subset Ω$ ,
Where # is counting measure on  $(  \mathbb{N} , 2^ \mathbb{N} )$
  and $π_1  : \mathbb{N} \times \mathbb{N}  - > \mathbb{N}$   is the projection mapping each point in $\mathbb{N} \times \mathbb{N} $ onto it's first coordinate ,
i.e  $π_1 ( ( i,j)) = i , (i,j) ∈ \mathbb{N} \times \mathbb{N}$.
Question I want to show the below:
i) $μ$ is an outer measure
ii) Characterize the class of μ-measurable sets.
and is μ a measure on $2^Ω$?


text:
Q: how to create a singleton asmx service how can i create an singleton asmx webservice ? (please don't say use WCF and WWF :D )

A: Short Answer: You don't want to.
Long Answer: A request to an .ASMX is going to non deterministically use a new worker thread, so even if you used the singleton pattern, the life of the singleton will not be known.
Perhaps elaborate on what you want to do, and I can guide you towards the best pattern.

A: I'm not sure how a singleton solves your performance problem, unless you are caching data inside the instance. In that case, I'd agree with the above suggestion of introducing the cache between the service and the database. Just how mutable is this data?

A: I won't suggest WCF, but only because you asked us nicely not to.
I will mention that you've found yet another reason to use WCF over ASMX. You might want to keep a list.
You might also want to keep a list of reasons to use ASMX over WCF. You might even want to use the same list for the reasons not to upgrade to .NET 3.5 SP1. It won't be a long list.
There may come a time, when Management wonders why certain things take so long to accomplish, when you'll want to send them your list.

A: You could use an ashx (HttpHandler). Implement IHttpHandler and set IsReusable to false.
http://neilkilbride.blogspot.com/2008/01/ihttphandler-isreusable-property.html

A: Depending on what you want to do, maybe you can write the engine as a singleton that's accessed by whatever thread services the ASMX call.


text:
Q: Java Array returning weird output I'm creating a method for a homework problem that returns the highest value in an array. I'm using a for
loop to input the numbers into the array. Here is what the input code looks like.
int[] array = new int [n];
    for(i=0;i<array.length;i++){
        array[i]=sc.nextInt();
        System.out.println(array);}

When i run the program to try and see if there's anything wrong as a I go along I notice the array not returning the value I input into it. For example
putting the number 12 it returns [I@6c80d028. I'm pretty new to java so I don't really know what's going on with the input. Is there any thing that can be done?

A: Please use:
System.out.println(Arrays.toString(array));

A: Please do this
System.out.println(array[i]);

or
System.out.println(Arrays.toString(array));

when you
System.out.println(array);

It prints the address and not the value hence you see a junk characters / not expected value.


text:
Q: How do I make the background image continue into the container On the following site: http://bit.ly/1gEehw2
I need to get the background for the header to continue into the body and .container div. I tried wrapping container in another div and padding margin/padding and making the background transparent, it did not work. I also tried to use z-index to solve this, and that also didnt work.
Can someone give me some insight on what I am doing wrong?

A: I just changed some of you code and worked. first give your header a bigger height:
.header{
height: 500px;
}

clear many many background:#fff css from you items like .jbcbackground and its children
and add this css to your main body element (give a negative margin-top):
.jbcbackground {
margin-top: -250px;
position: relative;
z-index: 100;
}


text:
Q: How to use the result of two find for a single xargs I am on Ubuntu 14.04. Lets say there are unknown number of executables in  a folder.
ATest, BTest, CTest

I want to execute each executables with a custom command line argument that is related to it's name. For example,
valgrind --xml=yes --xml-file=ATest.log ./ATest
valgrind --xml=yes --xml-file=BTest.log ./BTest
valgrind --xml=yes --xml-file=CTest.log ./CTest

I can get the executables by
find . -executable -type f

I can get the custom command line argument by
find . -executable -type f -printf '%f\n'

I can do
find . -executable -type f | xargs -n 1 valgrind --xml=yes --xml-file=Test.log

but unfortunately the name of the log file is not customized. I've attempted to combine it as below but it didn't work
find . -executable -type f -printf '%f\n' && find . -executable -type f | xargs -n 2 valgrind --xml=yes --xml-file={}.log

What is the correct way to combine the result of two find for a single xargs?

A: You can use:
find . -executable -type f -printf '%f\n' |
xargs -I {} valgrind --xml=yes --xml-file={}.log ./{}

Or this xargs:
find . -name '*Test' -executable -type f -print0 |
xargs -0 -I {} bash -c 'valgrind --xml=yes --xml-file="${1##*/}.log" "$1"' - {}

This will execute these 3 commands:
valgrind --xml=yes --xml-file=ATest.log ./ATest
valgrind --xml=yes --xml-file=BTest.log ./BTest
valgrind --xml=yes --xml-file=CTest.log ./CTest

A: Use xargs's -I switch:
edward@esmith-Dell-XPS-L502X:~/tmp$ ls
a  b  c
edward@esmith-Dell-XPS-L502X:~/tmp$ find . -type f -printf '%f\n' | xargs -IXXX echo XXX some more stuff -f XXX and more XXX
a some more stuff -f a and more a
c some more stuff -f c and more c
b some more stuff -f b and more b


text:
Q: Reading and external file with integers and strings in C I am trying to read an external text file. The file contains both numbers and words in the form:
hello 1239 4943 melissa

(with each element on its own line) The actual text file has over 1200 words. I want to read each line and store them as strings, but fscanf skips over the numbers.  How can I read the numbers into my program and store them as strings?
    char word[1263][13];
    FILE * fh;

    fh=fopen("wordlist.txt","r");
    for (a=0;a<1263;a++)
    {
      fscanf(fh,"%s",word[a]);
    }
    fclose(fh);

A: You should be able to achieve this via fscanf
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( int argc, char ** argv ) {
   FILE * source_file;

   char * buffer = malloc( 100 * sizeof(char));
   char ret = '\0';

   source_file = fopen("TENLINES.TXT","r+");
   do {
      ret = fscanf(source_file, "%s", buffer);
      printf("%s\n", buffer);

   } while (ret != EOF);

   return 0;
}

A: How are you using fscanf? The following code will work:
char s1[100];
int i1;
int i2;
char s2[100];

while (!feof (file))
  {
    // Should check return value.
    fscanf (file, "%s %d %d %s", s1, &i1, &i2, s2);
    printf ("%s %d %d %s\n", s1, i1, i2, s2);
  }


text:
Q: Some help with hibernate Criteria query Can somebody please help me complete / clean up this query.  I am trying to first get the number of rows in the table, then I need to actually fetch a set of rows.  I am not sure how I can use the same criteria instance to perform both queries.
To fetch the count I have something like this:
Criteria criteria = session.createCriteria(MyTable.class);
criteria.setProjection(Projections.rowCount());
Integer count = (Integer) criteria.uniqueResult();
int numRows = count.intValue();

And to fetch the rows (I need only a subset for pagination purposes):
Criteria criteria = session.createCriteria(MyTable.class);
criteria.setFirstResult(offset);
criteria.setMaxResults(limit);
criteria.addOrder(Order.desc(orderBy.toString()));
List<MyType> myType = criteria.list();

Do I first need to Null out the projection or something like that so that I can use the criteria to fetch rows (after performing the count)?
I would love some help cleaning this up so that I can efficiently perform both queries and end up with the total number of rows and a list of results.  Thanks!!

A: You need to clear the count projection and set a result transformer to retrieve the MyTable objects. Try this for the second query:

criteria.setProjection(null)
criteria.setResultTransformer(Criteria.ROOT_ENTITY);

A: You are asking about re-using the same criteria for the count and the projection, correct? I couldn't find a way to do it so I've been putting the criteria and restrictions building in it's own method and building it up twice...once for count and once for the page of data. If there is a better way, I'm all ears...