Q:

Apply specific check (beyond Moose types) to Moose attribute

Moose types are great, but sometimes you need to be more specific. You all know these data type rules: that parameter may only be 'A', 'B' or 'C', or only a currency symbol, or must conform to some regular expression.
Take a look at the following example which has two constrained attributes, one must be either 'm' or 'f', the other must be a valid ISO date. What's the best way in Moose to specify these constraints? I'd think of the SQL CHECK clause, but AFAICS there is no check keyword in Moose. So I used trigger, but it sounds wrong. Anyone has a better answer?
package Person;
use Moose;

has gender          => is => 'rw', isa => 'Str', trigger =>
    sub { confess 'either m or f' if $_[1] !~ m/^m|f$/ };
has name            => is => 'rw', isa => 'Str';
has dateOfBirth     => is => 'rw', isa => 'Str', trigger =>
    sub { confess 'not an ISO date' if $_[1] !~ m/^\d\d\d\d-\d\d-\d\d$/ };

no Moose;
__PACKAGE__->meta->make_immutable;

package main;
use Test::More;
use Test::Exception;

dies_ok { Person->new( gender => 42 ) } 'gender must be m or f';
dies_ok { Person->new( dateOfBirth => 42 ) } 'must be an ISO date';

done_testing;

Here's what I wound up using:
package Blabla::Customer;
use Moose::Util::TypeConstraints;
use Moose;

subtype ISODate => as 'Str' => where { /^\d\d\d\d-\d\d-\d\d$/ };

has id              => is => 'rw', isa => 'Str';
has gender          => is => 'rw', isa => enum ['m', 'f'];
has firstname       => is => 'rw', isa => 'Str';
has dateOfBirth     => is => 'rw', isa => 'ISODate';

no Moose;
__PACKAGE__->meta->make_immutable;

This is Moose version 1.19, in case it matters. I got the following warning for the wrong subtype as => 'Str', where => { ... } syntax I erroneously introduced: Calling subtype() with a simple list of parameters is deprecated. So I had to change it a bit according to the fine manual.

A:

Just define your own subtype, and use that.
package Person;

use Moose::Util::TypeConstraints;

use namespace::clean;
use Moose;

has gender => (
  is => 'rw',
  isa => subtype(
    as 'Str',
    where { /^[mf]$/ }
  ),
);
has name => (
  is => 'rw',
  isa => 'Str'
);
has dateOfBirth => (
  is => 'rw',
  isa => subtype(
    as 'Str',
    where { /^\d\d\d\d-\d\d-\d\d$/ }
  ),
);

no Moose;
__PACKAGE__->meta->make_immutable;
1;

package main;
use Test::More;
use Test::Exception;

dies_ok { Person->new( gender => 42 ) } 'gender must be m or f';
dies_ok { Person->new( dateOfBirth => 42 ) } 'must be an ISO date';

done_testing;

Or you could use the MooseX::Types module.
package Person::TypeConstraints;

use MooseX::Types::Moose qw'Str';
use MooseX::Types -declare => [qw'
  Gender ISODate
'];

subtype Gender, (
  as Str,
  where { /^[mf]$/ },
);

subtype ISODate, (
  as Str,
  where { /^\d\d\d\d-\d\d-\d\d$/ }
);
1;

package Person:

use MooseX::Types::Moose qw'Str';
use Person::TypeConstraints qw'Gender ISODate';

use namespace::clean;
use Moose;

has gender => (
  is => 'rw',
  isa => Gender,
);
has name => (
  is => 'rw',
  isa => Str,
);
has dateOfBirth => (
  is => 'rw',
  isa => ISODate,
);

no Moose;
__PACKAGE__->meta->make_immutable;
1;

A:

Adding your own type like Brad said:
use Moose::Util::TypeConstraints;

my $gender_constraint = subtype as 'Str', where { $_ =~ /^[FfMm]$/ };
has gender => ( is => 'rw', isa => $gender_constraint );


Q:

How to use pear without installation

I am developing a script for a site using php and I want to use some PEAR classes as they are very helpful to save me from some repeated tasks.
The Problem is that I have to deliver the project as a standalone folder that will be placed in an existing website without depending on any server configuration other than PHP 5 and MySQL.
So I am looking for an easy way to do that. Can any one help?

A:

You can download the packages (be sure do download any dependencies as well), and put them into a directory.  Then, in php, adjust the include path to include that directory:
$path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mypear';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

Then, you can use pear just like normal (include Mail.php;)...

A:

You want to use the Pyrus installer: http://pear2.php.net/
It allows you to do this exact thing, multiple PEAR package installs in different locations.
$>php pyrus.phar install /Path/to/project/lib pear/Net_URL
where lib is a directory within your project.  The main issue I ran into is while the docs say it's for 5.3+ you need 5.3.1.

http://pear.php.net/manual/en/pyrus.php
https://pyrus.com/en/help/tasks/getting-started


Q:

Click radio button, change inner icon

When the user clicks on the label of the radio button. I'd like to change the gear to the selected labels icon. So for example. :
If a user clicks on the tags. The top gear(cog) would change to a tag.
This is my code:
var current-icon = $('span.carat i.icon-cog');
$('#hidden-search-filter label').click(function(){
    var icon = $(this).find('i');
    current-icon.val(icon);
});

How do I make this possible? Here is a fiddle to show what Im working with. Thank you in advance!

A:

Something like this :
$('#hidden-search-filter label').on('click', function(){
    $('.carat i:first-child').attr('class', $('i', this).attr('class'));
});

FIDDLE
val() sets and gets the value of an element, as in:
<input type="text" value="It gets this string" />

You need to change the class, and using attr() (we're trying to change the attribute, not the className property) resets the class to a new value, where addClass and removeClass would add or remove a class while all other classes would be kept etc.


Q:

OData, method get with key not found

With the code below, I can hit (using Fiddler):

GetCustomers via GET: odata/Customers
Post(CustomerModel customer) via POST: odata/Customers
Delete via DELETE: odata/Customers(5)

The delete method look like :
public IHttpActionResult Delete([FromODataUri] int key)
{
    Console.WriteLine(key);
}

I hit the method and I get the key, no problem.
But I don't hit the get method with the key (no problem with the get method without the key, I get the full list) :
// GET: odata/Customers(5)
public IHttpActionResult GetCustomer([FromODataUri] int key)
{
    Console.WriteLine(key);
}

I get this error (Response headers via Fiddler):
HTTP/1.1 404 Not Found
The WebApiConfig is :
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ODataModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<CustomerModel>("Customers");
        builder.EntitySet<EmployeeModel>("Employees");
        config.MapODataServiceRoute(
            routeName: "ODataRoute",
            routePrefix: "odata",
            model: builder.GetEdmModel());
    }
}

A:

The method name needs to be Get to be picked up by the OData routing:
Get([FromODataUri] int key)


Q:

How to form static data with the structure like array of objects in swift 4?

Currently, I'm building an app using the Swift platform. I need to show static data like an array of objects structure because I need to load data on UITableView section and rows. Below is the example array of objects structure in objective C. I need to replicate the same thing in Swift.
NSArray *dummyArray = [[NSArray alloc] initWithObjects:
                       [[NSDictionary alloc] initWithObjectsAndKeys:@"India",@"team",@"280",@"score",@"5",@"wickets", nil],
                       [[NSDictionary alloc] initWithObjectsAndKeys:@"SouthAfrica",@"team",@"279",@"score",@"9",@"wickets", nil],
                       nil];

NSMutableArray *demoArrayOfObjects = [[NSMutableArray alloc] initWithObjects:
                                      [[NSDictionary alloc] initWithObjectsAndKeys:@"17-03-2018",@"date",@"Ind win by 5 wickets",@"result",@"SouthAfrica",@"Place",dummyArray,@"data", nil], nil];

NSLog(@"demoArrayOfObjects = %@",demoArrayOfObjects);

Output:
demoArrayOfObjects = (
    {
    Place = SouthAfrica;
    data =         (
                    {
            score = 280;
            team = India;
            wickets = 5;
        },
                    {
            score = 279;
            team = SouthAfrica;
            wickets = 9;
        }
    );
    date = "17-03-2018";
    result = "Ind win by 5 wickets";
    }
)

A:

This sudo code might help you implement datasource in swift.
func prepareMatchInfo () -> Array>{
    var arrayOfMatches : Array<Dictionary<String,Any>> = Array<Dictionary<String,String>>();

    var arrayOfScores : Array<Dictionary<String,String>> = Array<Dictionary<String,String>>();
    arrayOfScores.append(getTeamScore(teamName: "India", score: "280", wickets: "5"));
    arrayOfScores.append(getTeamScore(teamName: "South Africa", score: "279", wickets: "6"));

    arrayOfMatches.append(getMatchInfo(place: "South Africa", data: arrayOfScores, date: Date(), result: "India Won by 5 Wickets"));

    return arrayOfMatches;
}

func getMatchInfo (place:String, data:Array<Dictionary<String,String>>, date:Date, result:String) -> Dictionary<String, Any>{
    var dict : Dictionary<String, Any> = Dictionary();
    dict["Place"] = place;
    dict["Data"] = data;
    dict["Date"] = date;
    dict["Result"] = result;
    return dict;
}

func getTeamScore (teamName:String, score:String, wickets:String) -> Dictionary<String, String>{
    var dict : Dictionary<String, String> = Dictionary();
    dict["TeamName"] = teamName;
    dict["Score"] = score;
    dict["Wickets"] = wickets;
    return dict;
}


Q:

Changing the header of the response on NodeJS using request

I have the following problem:
I want to get a static file from another server, and give it back to the user with another content-type header.
The following code works just fine, but I can't figure out a way to change the response header, though.
const request = require('request');

app.get('video', function (req, res) {
    request.get('http://anotherurl.com/video-sample.mp4').pipe(res);
});

I tried to do this thing more manually, but the response was very slow.
app.get('video', function (req, res) {
  request.get('http://anotherurl.com/video-sample.mp4', function(error, response, body) {
    // ...
    res.setHeader('content-type', 'image/png');
    res.send(new Buffer(body));
  });
});

Can you guys help me with that?
Thanks

A:

Just set the response header when the 'response' event fires.
app.get('video', (req, res) => {
    request.get('http://anotherurl.com/video-sample.mp4')
    .on('response', response => {
      res.setHeader('Content-Type', 'image/png');

      // pipe response to res
      // since response is an http.IncomingMessage
      response.pipe(res);
    });
});


Q:

Why does the Trackbar value decrease on arrow up/PgUp?

I stumbled upon an interesting behavior in the Trackbar Winforms control.
On a horizontal trackbar, the left/right arrow keys work as expected. (Left arrow moves the slider to the left and decreases the value, right arrow does the opposite)
It is also possible to manipulate the slider using the up/down arrow keys and PageUp/PageDown.
However, the behavior seem counter-intuitive: arrow up and page up move the slider to the left and consequently decrease the value.
Arrow down and page down move the slider to the right and increase the value.
When using a vertical trackbar, up/down keys work as expected but arrow left = increase and arrow right = decrease.
This is the default behavior in C# Winforms, and apparently in native Windows. (Not sure about the latter, the slider for UAC does work this way)
In WPF the slider control works "properly" i.e. the value increases with arrow up, arrow right und PgUp.
Also the slider in Internet Explorer Privacy settings works properly. Not sure why, but I suspect a custom handling of the keys.
From an ergonomics standpoint, it is clear that up, right, forward and clockwise manipulation of anything is supposed to increase the value. (This nothing new, compare A Guide to Human Factors and Ergonomics, Second Edition Page 100 )
Now to my Question: Does anyone know why this is the way it is?

A:

I'm strongly inclined to think this behavior was chosen to keep the trackbar control consistent with the scrollbar control.
These two controls have very much in common (their thumb can be moved by "line" or "page" increments, both controls can be laid out horizontally or vertically, both use WM_HSCROLL and WM_VSCROLL to notify their parent when the thumb position changes).
From the control's point of view, the thumb can move "up" or "down" ("left" or "right" respectively). The keyboard navigation for scrollbars used Left and Up for upwards (leftwards) movement, as well as Right and Down for downwards (rightwards) movement.
It must have made sense for the trackbar control to follow the same conventions, so developers used to the scrollbar control's implementation could apply the same principles to the trackbar control.


Q:

MultiTasking isn't working in my program in  C++11

How do I start a new thread in parallel without pausing the main function?
Here is my code:
void someFunction { while(1);}

int main(){

thead *th = new thead(&someFunction);
thead.join();
return 0;

}

But program doesn't stop

P.S. How run thread in parallel source

A:

In C++11, the implementation is permitted to assume that this kind of loop terminates. So your code can be optimized to nothing at all. Otherwise, lots of legitimate and valuable optimizations wouldn't be possible, but the effects can occasionally be surprising.

A:

The program can't stop as the main thread calls thread.join() which means that it will wait for the thread "thread" to finish, however that one is calling a function which never finish as it loops to infinity.

A:

This call:
thread.join();

explicitely tells your program to wait until the function the thread is executing, returns. Your function never returns, so you program never gets past this function call. You can start extra threads between the thread creation and the corresponding call to join(). For example:
#include <thread>

void someFunction() { for(volatile int x = 0; ; x = x){};}

int main()
{
    std::thread t1(someFunction);
    std::thread t2(someFunction);
    std::thread t3(someFunction);
    t1.join();
    t2.join();
    t3.join();
    return 0;
}

will spawn 3 threads that do absolutely nothing. If the functions passed to the threads do return, this is what you want to do.
If you want to have the task run and the main program exit before that, you will need to spawn a new process in a platform-dependent way, so that their execution is not stopped by your program exiting.


Q:

How does projection work with cameras?

So I want to measure the displacement of a model car at a bunch of times as it crosses a distance of two metres.
Now, I intend to do this by filming it, measuring what percentage of the frame it has travelled at each time step, calculating the length of the frame given the distance between the camera and the car and then finding that percentage of that distance.
Let me show you the method I've intended to use to find the distance across.
I took a photo with the camera at a distance of 0.3m, and found that a 0.3-metre ruler took up 70% of the frame.

To calculate $x$, I would think I can just write:
$$0.7x=0.3$$
and hence that $x\approx0.43m$.
Given $x$ and noting that the camera has a focal length of 0.008m, I can find the length at any distance using similar triangles as follows:

$$\frac{y}{0.43}=\frac{0.6+0.008}{0.3+0.008}$$
$$y\approx0.85m$$
Unfortunately, when I tried to experimentally calculate the values I found I undershot by somewhere around 10cm.
Am I misunderstanding how this kind of geometry works? Do I not understand how camera's work? How can I do this? What other variables do I need to take into account?

A:

You misunderstand how cameras work. The vertex of the triangle is at the lens. The focal length ($0.008$) is the distance from the lens to the sensor on the other side.
Provided that your lens has no fisheye effect, pincushion effect, or other such distortion--that is, if a photo of a chessboard from directly above the board comes out as a perfectly square and regular chessboard--your calculation only needs to consider the triangles between the lens and the subject. You can ignore what goes on behind the lens. (You assume it is geometrically similar to what happens in front.)
Therefore you should not put the $0.008$ focal length in your diagram at all.
You should have only one triangle with leg $0.3$ and another with leg $0.3 + 0.3.$
Then you will find that $y \approx 0.86.$


Q:

Quadratic variation question

Here I have this question
(i) state Ito's formula
(ii) hence or otherwise show that
$\int^t_0B_s dB_s = \dfrac{1}{2}B^2_t -\dfrac{1}{2} t$
(iii) define the quadratic variation $Q(t)$ of Brownian motion over [0,t], given that $Q(t) = t$, use this result to prove (ii)
I can do everything up to the last bit of (iii), how can quadratic variation tell you this relationship?
disclaimer: this is not homework. I am trying to help a friend preparing for an exam and this was a past paper question.

A:

"Like" Ito:
$$d (B^2) = B dB + B dB + dB dB$$
That is
$$B dB = \frac{1}{2} d (B^2) - \frac{1}{2} dB dB$$
Integrate. Last term is 1/2 the quadratic variation.
I understand the questions as follows: In iii) one has to define what $dB dB$ stands for and one has to "proof" the first line in my answer. In ii) one may use Ito to "know" that $dB dB = dt$.


Q:

¿Cómo puedo ejecutar varias funciones asíncronas SIN acoplarlas?

Quiero tener un conjunto de funciones asíncronas pero que estén desacopladas, es decir, que las funciones sean independientes unas de otras. Y después, tener una función síncrona que las invoque.
Por ejemplo:
function readFiles() {
  file1()
  file2()
  file3()
}

function file1 () {
  fs.readFile('file1', 'utf8', function (err,data) {
    if (err) {
      return console.log(err)
    }
    console.log(data)
  })
}

function file2 () {
  fs.readFile('file2', 'utf8', function (err,data) {
    if (err) {
      return console.log(err)
    }
    console.log(data)
  })
}

function file3 () {
  fs.readFile('file3', 'utf8', function (err,data) {
    if (err) {
      return console.log(err)
    }
    console.log(data)
  })
}

Por poner sólo un ejemplo de funciones asincrónicas, la idea es que no importa qué función concreta se use, puede ser una consulta de mongoose o cualquier otra ejecución de una función asincrónica.
Una manera en que lo resuelvo es invocar la siguiente función después de que se ejecuta el callback:
function readFiles() {
  file1()
}

function file1 () {
  fs.readFile('file1', 'utf8', function (err,data) {
    if (err) {
      return console.log(err)
    }
    console.log(data)
    file2()
  })
}

function file2 () {
  fs.readFile('file2', 'utf8', function (err,data) {
    if (err) {
      return console.log(err)
    }
    console.log(data)
    file3()
  })
}

function file3 () {
  fs.readFile('file3', 'utf8', function (err,data) {
    if (err) {
      return console.log(err)
    }
    console.log(data)
  })
}

Pero no estoy cómodo, hace que una fuerte dependencia entre las funciones lo cual es mala idea para el mantenimiento a futuro.
¿Sí me explico lo que pregunto?

A:

Usa Promise.All
let promises = [];
promises.push(asyncA(done));
promises.push(asyncB(done));
promises.push(asyncC(done));

Promise.all(promises).then(function(){
     finalFunction();
}


Q:

Adding a field to a Spotify list

I'm trying to add a field to the List provided by the Spotify API.
Here is my code to create the list:
var playList_view = new views.List(playlist_test, function(track) {
                return new views.Track(track, views.Track.FIELD.NAME |
                                            views.Track.FIELD.ARTIST |
                                            views.Track.FIELD.ALBUM);
            });

$('#tracks').append(playList_view.node);

I don't know how to add it to the view through the function, so I'm adding it after the fact. If there is a better way to do this, please let me know.
Here is the attempt (which is partially successful):
$('.sp-list a').append("Test");

This correctly adds a column to the right of the other columns for all the tracks shown on the screen. The problem arises when I scroll down in the list. It appears to be getting refreshed and the html is rewritten. I think the solution here would be either to add the code to the function at view creation time, or observe some kind of change/refresh event. Unfortunately, I'm not sure what the events are or a good place to find a list of them.
Any help is appreciated!
Thanks,
Kevin

A:

One way of doing this is to use a handler on the scroll event to detect that the list has been scrolled and then re-add the field. However, you need to be careful that it doesn't end up adding it to rows which already have it added or you will end up with duplicated fields. This is something which seems to work:
function addCustomField() {
    $('.sp-list a.sp-item').each(function() {
        if($(".custom-field",$(this)).length == 0) // check field doesn't already exist
        {
            $(this).append("Test");
        }
    });
}

setTimeout(function() {
    addCustomField(); // Add the custom field to the visible tracks
    $('.sp-list').scroll(addCustomField); // Register the scroll handler
},10);


Q:

checkbox values not being received in laravel controller

I have this bit of code in my form edit.blade.php :
@php
    $imagepath="images/Service/".$services->name."/";
    $images=glob($imagepath.'*.*');
@endphp

     @foreach($images as $image)
         @php
             $count++;
         @endphp

             <input form="services" type="checkbox"  name="deleteimagelink[]" value="{{($image)}}"  >

    @endforeach

This is for passing the path of those images meant to be deleted.
And I have this snippet in my controller:
print_r($request->input('deleteimagelink'));
$deletables=$request->input('deleteimagelink');
foreach ($deletables as $deletable)
{
    print_r($deletable);
    unlink($deletable);
}

I have this problem that nothing is being received in the $request->input('deleteimagelink') parameter.
Please guide me if I'm doing anything wrong.
If nothing seems weird, can you please guide me how to deal with these checkbox situations in laravel.
I consulted related answers from internet but nothing seems to work.

A:

I had included the code above outside the <form></form> tag in order to justify to my view. Interestingly, it didn't work even though that I had included form="services" as a parameter in my input field{services is the form name here}. I had worked something like this before and it had worked pretty good that time. I managed to get the <form></form> tags outside the whole of my form elements and it is working fine now.
Thank you everybody who tried to help.


Q:

SQL Server: what is the virtual log file?

What is the Virtual Transaction Log file in SQL Server?

A:

From MSDN:

The SQL Server Database Engine divides
  each physical log file internally into
  a number of virtual log files. Virtual
  log files have no fixed size, and
  there is no fixed number of virtual
  log files for a physical log file. The
  Database Engine chooses the size of
  the virtual log files dynamically
  while it is creating or extending log
  files. The Database Engine tries to
  maintain a small number of virtual
  files. The size of the virtual files
  after a log file has been extended is
  the sum of the size of the existing
  log and the size of the new file
  increment. The size or number of
  virtual log files cannot be configured
  or set by administrators.

The transaction log is a wrap-around
  file. For example, consider a database
  with one physical log file divided
  into four virtual log files. When the
  database is created, the logical log
  file begins at the start of the
  physical log file. New log records are
  added at the end of the logical log
  and expand toward the end of the
  physical log. Log truncation frees any
  virtual logs whose records all appear
  in front of the minimum recovery log
  sequence number (MinLSN).

When the end of the logical log
  reaches the end of the physical log
  file, the new log records wrap around
  to the start of the physical log file.


Q:

Reload the .profile file

I've modified the .profile file of a user. It contains some new environement vars, how can i reload this file without restarting the server ?
The .profile file is only charged when the system boots or in any other case ??
Thanks in advance.

A:

Normally the file gets parsed on startup of a new shell (not at system boot!). So you can just start another shell and your changes to ~/.profile will be present. However, you can also "source" the file in the current shell session:
source ~/.profile

Note that source is just human readable shortcut for the . command. So, you can also issue
. ~/.profile

Thanks to @chepner for explaining that source is an alias of . and not vise versa.


Q:

Add view on UIScrollView without it scrolling (programatically)

I am trying to add a Page Control on top of my UIScrollView Custom class. Everything is wokring fine. But whenever I slide the scrollView, the Page Control will slide along the first Image as well.
Here is my code:
import Foundation
import UIKit
import SwiftyGif

class MBSPagingScrollView: UIScrollView {

var pageControl = UIPageControl()
var imagesArray = [String]()

override init (frame : CGRect) {
    super.init(frame : frame)
}

convenience init () {
    self.init(frame:CGRect.zero)
}

required init(coder aDecoder: NSCoder) {
    fatalError("This class does not support NSCoding")
}

init(frame : CGRect, imagesarray : [String]){
    super.init(frame : frame)

    imagesArray = imagesarray

    self.isPagingEnabled = true
    self.showsHorizontalScrollIndicator = false

    for (index, imageName) in imagesArray.enumerated() {

        var imageView = UIImageView()

        if imageName.hasSuffix(".gif") {
            let gifManager = SwiftyGifManager(memoryLimit:30)
            let gif = UIImage(gifName: imageName)
            imageView = UIImageView(gifImage: gif, manager: gifManager)
        }

        else {
            imageView = UIImageView(image: UIImage(named: imageName))
            imageView.contentMode = UIViewContentMode.scaleToFill
        }

        imageView.frame = CGRect(x: CGFloat(index) * self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        self.addSubview(imageView)

    }

    self.contentSize = CGSize(width:self.frame.size.width * CGFloat(imagesArray.count),height: self.frame.size.height)

    configurePageControl()
    pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)
}

func configurePageControl() {
    self.pageControl.frame = CGRect(x: 0, y: self.frame.size.height - 50, width: self.frame.size.width, height: 50)
    self.pageControl.numberOfPages = imagesArray.count
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.red
    self.pageControl.pageIndicatorTintColor = UIColor.black
    self.pageControl.currentPageIndicatorTintColor = MainOrangeColor
    self.addSubview(pageControl)
}

//    // MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
    func changePage(sender: AnyObject) -> () {
        let x = CGFloat(pageControl.currentPage) * self.frame.size.width
        self.setContentOffset(CGPoint(x:x, y:0), animated: true)
    }

func selfDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageNumber = round(self.contentOffset.x / self.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}

}
And here are images of the problem happening

As you can see the Page Control is sliding with the first image. I need it to stay in the center.
Any help would be appreciated!

A:

I think you can do that by going to Storyboard, and from the left menu of the UI Builder, drag your page control down and put it out of your scroll view and under it, like in the following picture:

Then you'll need to add the suitable constraints to place your page control properly.
Good luck!


Q:

Android viewpager with DepthPageTransformer z-index issue

I implemented a viewpager with a DepthPageTransformer , in pages I have some inputs ( radio , check boxs , select options ... ). It works fine except one wired bug: Sometimes when I click on position(x,y) on a page P1  the input in that position of page P2 gets triggered.
P1:

P2( the one after P1):

Now when I click on this position on page P1 :

I get the select options displayed of page P2:

It's similar to z-index problem in web development.
The code of the DepthPage Transformer is the same as in the documentation : http://developer.android.com/training/animation/screen-slide.html#pagetransformer.
public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.75f;
@Override
public void transformPage(View view, float position) {
    int pageWidth = view.getWidth();

    if (position < -1) { // [-Infinity,-1)
        // This page is way off-screen to the left.
        view.setAlpha(0);

    } else if (position <= 0) { // [-1,0]
        // Use the default slide transition when moving to the left page
        view.setAlpha(1);
        view.setTranslationX(0);
        view.setScaleX(1);
        view.setScaleY(1);

    } else if (position <= 1) { // (0,1]
        // Fade the page out.
        view.setAlpha(1 - position);

        // Counteract the default slide transition
        view.setTranslationX(pageWidth * -position);

        // Scale the page down (between MIN_SCALE and 1)
        float scaleFactor = MIN_SCALE
                + (1 - MIN_SCALE) * (1 - Math.abs(position));
        view.setScaleX(scaleFactor);
        view.setScaleY(scaleFactor);

    } else { // (1,+Infinity]
        // This page is way off-screen to the right.
        view.setAlpha(0);
    }
}
}

Any idea on how to solve this overlapping problem ?

A:

Try this:
public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.75f;
@Override
public void transformPage(View view, float position) {
    int pageWidth = view.getWidth();

if (position < -1) { // [-Infinity,-1)
    // This page is way off-screen to the left.
    view.setAlpha(0);

} else if (position <= 0) { // [-1,0]
    // Use the default slide transition when moving to the left page
    view.setAlpha(1);
    view.setTranslationX(0);
    view.setScaleX(1);
    view.setScaleY(1);
    // -------- THIS LINE ---
    view.bringToFront();
    // -------- THIS LINE ---

} else if (position <= 1) { // (0,1]
    // Fade the page out.
    view.setAlpha(1 - position);

    // Counteract the default slide transition
    view.setTranslationX(pageWidth * -position);

    // Scale the page down (between MIN_SCALE and 1)
    float scaleFactor = MIN_SCALE
            + (1 - MIN_SCALE) * (1 - Math.abs(position));
    view.setScaleX(scaleFactor);
    view.setScaleY(scaleFactor);

} else { // (1,+Infinity]
    // This page is way off-screen to the right.
    view.setAlpha(0);
}
}
}


Q:

How can I extract the IP addresses from .cap file?

I have a fwcapture.cap file, which is used by Wireshark.
in it, there have many IP addresses source IPs and destination IPs.
How can I extract the unique IP addresses(no mater source or destination) as a list?

A:

You can use tshark, which already in Wireshark installation.
tshark -T json -e 'ip.src' -e 'ip.dst' -r filename.pcap  | grep '\.[0-9]' | sort -u


Q:

To check if session is available or not

I tried some code in Application_Error like this
Session["mysession"] = "Some message";

but the problem is sometimes session is not available in Application_Error. So I want to check whether session is available or not.

A:

Session doesn't always exist within the context of the current Application_Error. Try the following:
protected void Application_Error(object sender, EventArgs e)
{
    if (Context.Handler is IRequiresSessionState ||
        Context.Handler is IReadOnlySessionState)
    {
         // Session exists
         Session["mysession"] = "Some message";
    }
}


Q:

Any disadvantage to calling _documentSession.Store when updating existing documents in RavenDB?

When creating new or updating existing documents in RavenDB, the documentation says to do it along these lines:
public string Save(Blogpost post)
{
    Blogpost model;

    if (String.IsNullOrEmpty(post.Id))
    {
        model = new Blogpost();
        _documentSession.Store(model);
    }
    else
    {
        model = _documentSession.Load<Blogpost>(post.SimpleId);
    }

    model.Text = template.Text;
    model.Name = template.Name;
    _documentSession.SaveChanges();

    return model.Id;
}

Someone on my team is doing saves another way for both creating new documents or updating existing ones:
public string Save(Blogpost post)
{
    _documentSession.Store(post);
    _documentSession.SaveChanges();
    return post.Id;
}

Is there any disadvantage to always calling .Store() even if the document already exists?

A:

If you are doing a rich client app and serializing the full BlogPost to the client like so:
//GET BlogPost/1
public BlogPost Get(int id)
{
    return _documentSession.Load<BlogPost>(id)
}

Then rehyrdating a full BlogPost on the server after a user has made changes. The below code appears to be more efficient than doing a Load and then a Store:
//POST BlogPost/
public void Post(BlogPost post)
{
    //blog post already has an Id in this example
    _documentSession.Store(post)
    _documentSession.SaveChanges();
}

When you do a
documentSession.Load<Blogpost>(id)

RavenDB returns the full JSON for the blog post that you already have just for you to overwrite it, turn around and re-save sending the full JSON for the blog post back again over the wire to Raven.
This means that doing a Load and Store when you already have all the data results in twice the network traffic to Raven for no added benefit that I can see using Fiddler.
Even if you were only changing a part of the object (say the Name of the BlogPost) the RavenDB .NET API still sends the full object over the wire when doing a:

Load()
make some changes (but not changes to everything)
Store()
SaveChanges()

Perhaps Ayende Rahien can enlighten us on anything I missed here?

A:

Jason,
Your code will always overwrite the document. Is that something that you want to do?

A:

Store will store this object in a new document. Use the change tracking feature built-in in the session object aka the Unit of Work pattern, like the docs suggest.


Q:

Set multiple datepickers' value based on one datepicker's selected date

I have follow jQuery UI Datepicker sample code
<!doctype html>

    <meta charset="utf-8">
    <title>jQuery UI Datepicker - Default functionality</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">

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

Date1: <input type="text" id="datepicker1">

Date2: <input type="text" id="datepicker2">

Date3: <input type="text" id="datepicker3">

Date4: <input type="text" id="datepicker4">

I want to set date pickers 2,3 and 4's value based on value selected in datepicker1.
Let say if #datepicker1 have valud 12/05/2013 then I would like to show +1 date for each other jQuery datepickers like below
datepicker1 => 12/05/2013 then
datepicker2 => 12/06/2013
datepicker3 => 12/07/2013
datepicker4 => 12/08/2013

I tried above.
Can you please help?

A:

You can use the onSelect event and call setDate method:
$("#datepicker1, #datepicker2, #datepicker3, #datepicker4").datepicker();
$("#datepicker1").datepicker("option", "onSelect", function (dateText, inst) {
    var date1 = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);

    var date2 = new Date(date1.getTime());
    date2.setDate(date2.getDate() + 1);
    $("#datepicker2").datepicker("setDate", date2);

    var date3 = new Date(date1.getTime());
    date3.setDate(date3.getDate() + 2);
    $("#datepicker3").datepicker("setDate", date3);

    var date4 = new Date(date1.getTime());
    date4.setDate(date4.getDate() + 3);
    $("#datepicker4").datepicker("setDate", date4);
});

Demo here

The onSelect passes the date as a string so we convert it to JavaScript Date object for convenience, using the following jQuery UI datepicker utility function:
$.datepicker.parseDate( format, value[, settings] )

The expression:
inst.settings.dateFormat || $.datepicker._defaults.dateFormat

means use the dateFormat value specified on the datepicker, if there is one; otherwise use the dateFormat from datepicker defaults (which is "mm/dd/yy").


Q:

How to get all objects of a class in Realm to an array

Currently I am using this:
    var matchedUsersFromRealm = MatchedUser.allObjects()
    var matchedUsersInRealm = RLMArray(objectClassName: MatchedUser.className())
    matchedUsersInRealm.removeAllObjects()
    matchedUsersInRealm.addObjects(matchedUsersFromRealm)

But it just looks cumbersome rather than just getting it in one line as it should (or did?). Maybe there is a better way?
PS, I am working on a mix project and somehow I can only use the Objective-C version and bridge it to my swift project. So the Realm().objects() is not available, even though it returns a Results not an array.

A:

You can add these extensions:
import Foundation
import RealmSwift

extension Results {

    func toArray() -> [T] {
        return self.map{$0}
    }
}

extension RealmSwift.List {

    func toArray() -> [T] {
        return self.map{$0}
    }
}

And then when fetching:
do {
    let realm = try Realm()
    let objs = realm.objects(MyObjType).toArray()
    // ...

} catch _ {
    // ...
}

(Remove do try catch if you're using Swift pre-2.0)
Note that this loads everything into memory at once, which may be in some cases not desired. If you're fetching in the background, it's required though, as Realm currently doesn't support using the objects in the main thread after that (you will also have to map the array to non-Realm objects in this case).

A:

I preferred to add a helper class to save and retrieve any type of objects using Generics.
class RealmHelper {
    static func saveObject<T:Object>(object: T) {
        let realm = try! Realm()
        try! realm.write {
            realm.add(object)
        }
    }
    static func getObjects<T:Object>()->[T] {
        let realm = try! Realm()
        let realmResults = realm.objects(T.self)
        return Array(realmResults)

    }
    static func getObjects<T:Object>(filter:String)->[T] {
        let realm = try! Realm()
        let realmResults = realm.objects(T.self).filter(filter)
        return Array(realmResults)

    }
}


Q:

Xbox 360 de-friending someone

How would I go about doing this? I can't find anything useful in the Xbox 360's wonderfully informative menus.

A:

When you select a friend's gamertag and the menu pops up ("Invite to Party", etc.), one of the options near the bottom is "Remove Friend":

(Source: http://support.xbox.com/xbox-live/social/chat-managing-friends)

A:

I'm not sure how to do this on the console, but I know that you can remove friends from xbox.com. Log in using the Windows Live ID associated with your GamerTag, and go to the Friends Center. There is a "Remove" button by each person on your Friends List that you can use to remove them.


Q:

Rename table with a strange name

I have attempted to install an extenxion in Joomla, but there was a problem with the installation and the name of the tables are really weird.  The name is like #__table1.
I have problems because of "#" character.  I have tried with something like this, it doesn't work.  How should I proceed?
RENAME TABLE CHAR(35) + '__table1' TO xxxxx_table1, CHAR(35) + '__table2' TO xxxxx_table2;

A:

Have you tried just using backticks:
RENAME TABLE `#__table1` to xxxxx_table1, `#__table2` to xxxxx_table2;

I did not test the RENAME command explicitly, but it seems possible to have a table name with a # sign, so long as we put backticks around the table name.
Side note, as you probably already figured out, you should avoid table and column names with strange symbols, or MySQL reserved keywords.


Q:

Adding touch sensitivity to Grub 2 boot loader?

I would like to know what libraries exist in Ubuntu 13.04 that would allow integration with Grub2 and more details on it  (i.e. language, development stage, developers, etc.) or if this cannot be done, why?
I also thought it may be possible to use the native device code in the Surface Pro architecture but have no experience on how to even start.  If this is possible please let me know, please!

Edit: March 14, 2013 @ 5:40PM PST
I have been searching hard and have found the following packages under Ubuntu 13.04:

muTouch  ( I believe this came from uTouch, an older package that Ubuntu used to use. )
libfile-touch-perl
tslib
pymt
touchegg
libframe6

A:

I was able to ask Stephen Webb who currently leads the Unity Technical Team about touch input. I contacted him because he used to be the lead developer on the uTouch-geis package which was split into three different packages Frame, Geis, and Grail.  These are the primary touch screen controls and he is also heavily involved in other multi-touch projects. I asked him about learning more about touch device input and my idea.  Here is what he had to say:

I want to have Grub2 register a single tap event, no more (multi touch not needed-I think).  Purpose would be to select from the boot menu.

You're going to have a challenge getting touch to work from boot
  loader code.
Many (but not all) touch input devices have device drivers that work
  to the Microsoft HID protocol.  You'd need to replicate that driver
  technology into GRUB2, and then figure out how to map that into
  something GRUB2 would understand as input.  Sounds like work.

Is there any resources you can lead me to that would help me understand how touch devices work?

That's complicated.  There's a lot of different technologies,
  connected to the host in different ways, talking different protocols,
  delivering different data.
There's some good documentation here.

Are there any single tap libraries you can suggest or multi touch one? Do you have any other suggestions on how to move forward?

Well, in the Linux stack there's the firmware in the touch processor,
  which feeds data to the device driver in the kernel, which translates
  into the evdev protocol, which is read by the x.org driver and
  converted into the XI2 protocol, or if there's nothing looking for XI2
  touch events, then converts that into an XI mouse event, and an X11
  event gets sent to the client.  All you have at the boot loader level
  is direct input from the touch processor.

I asked a varient of this question over at askubuntu and posted this answer there aswell.


Q:

display multidimentional array result in table with 1 column from database

I need help to display the result of my array in a table while filling the Description column with data from Mysql table base on product_ID on each line. Description now show the same Product description for each product_ID. it is not callind the description base on product_ID on the line.
<?php

foreach($_SESSION["cart_array"]as $item){
$i++;
$item_id=$item['part_id'];
$sql = mysqli_query($con,"SELECT * FROM   product_description
     WHERE product_id='$item_id' LIMIT 1");
While($row=mysqli_fetch_array($sql)){
$product_name=$row["name"];
}
}
  ?>

      Item ID
      Description
      Quantity
      Unit Price

<?php foreach($_SESSION["cart_array"]as $item): ?>

          <?php echo $item['part_id'] ?>
          <?php echo $product_name ?>
          <?php echo $item['quantity'] ?>
          <?php echo $item['price'] ?>

<?php endforeach; ?>

A:

You probably want this:
While($row=mysqli_fetch_array($sql)){
    $product_name[$row['part_id']] = $row["name"];
}

<?php echo $product_name[$item['part_id']] ?>

so that you're building an ARRAY of product names. As is, your loop fetches all of the names, but trashes the previously retrieved ones.


Q:

Question about URL friendly links

I am trying to get my urls to look like this:
example.com/posts/id_of_post/title_of_post
I have this in my controller:
match ':controller/:id/:link', :controller => 'posts', :action => 'show'

Say I have a list of posts.. how can I link to them?
<%= link_to 'Show', post %>

Just gives the usual /posts/id
On another note, at the minute I am making a url-friendly link when a post is created and storing it in the database. Would it be better to create on the fly? Is that possible/better?
I saw this in an answer to another question:
def to_param
  normalized_name = title.gsub(' ', '-').gsub(/[^a-zA-Z0-9\_\-\.]/, '')
  "#{self.id}-#{normalized_name}"
end

That would work if I could change the - to a /. Possible?

A:

This is what I did:
I added this to my post#create:
@post.link = (@post.title.parameterize)

I will give the user the option to edit the title for up to 5 mins after posting.
My route:
match "/posts/:id/:link" => "posts#show", :as => "story"

and my index view for posts
<%= link_to 'Show', story_url(post, post.link) %>


Q:

select range & copy/paste to notepad - Almost done

After a lot of work and testing (very pathetic indeed), I finally managed to select a range in worksheets, then copy/paste it in Notepad. The file shall be thereafter readen by another app. Unfortunately, the app reject the file and there is no way for me to debug why. The only message I have is an error occuring at last line.
Surprisingly, when I copy-paste to notepad by hand, it works. As far as my eyes can see, both txt files (the one writen with my sub() and the one from CP by hand) are exactly the same. I guess my eyes are wrong. I suspect there is at the end of last line or below last row maybe some white space I can not see. The only part of code I do not fully understand is, according to me, the place of the current issue.
Find below part of my code:
[code]
' RngSelect is a Variant and effectively a range of cells
' Txt is a Variant
' LastRow is a Long equal to last row number of my range

With RngSelect
For Lg1 = 1 To LastRow
    Txt = Txt & vbCrLf & Join$(Application.Transpose(Application.Transpose(.Rows(Lg1).Value)),vbTab)   ' copy each row
Next
End With

Open FilePath For Output As #1
Print #1, Mid$(Txt, Len(vbCrLf) + 1)
Close #1

RngSelect = Null
Txt = Null

End Sub

If it can help, my file to be imported by the other app can be in a csv format. Currently, my delimiter is Tab.
Thank you for help.

A:

Following this post, I finally managed to erase the last blank line at the bottom of my text . The the correct line now is : Print #1, Mid$(txt, Len(vbCrLf) + 1) ;
I then had to modify my LastRow, as it is the row number on my spreadsheet but not the last row number on my text file.
I shall now find a way to append the text in the text file.


Q:

script with date work on Linux but not on AIX

I wrote a script to that works fine on Linux but fails on AIX 7.2.
My script uses the command date with -d.
The purpose of this script is to get the last day that is not a Saturday, Sunday or a holiday. To validate if a day is a holiday I perform a query passing a date in the format YYYY-MM-DD.
The script is this:
D_MINUS_ONE=

GetLastDay()
{
        current_day=""
        day_of_week=$(date -d "$1 -1 days" +'%w')
        if [ $day_of_week -eq 0 ]
        then
                current_day=$(date -d "$1 -3 days")
        else
                current_day=$(date -d "$1 -1 days")
        fi
        db2 -x "SELECT COUNT(*) FROM HOLIDAY WHERE DT_HOLIDAY='$(date -d "$current_day" +'%Y-%m-%d')'" | read lines
        if [ lines -gt 0 ]
        then
                GetLastDay $(date -d "$current_day" +'%Y-%m-%d')
        fi
        D_MINUS_ONE=$(date -d "$current_day" +'%Y-%m-%d')
}

GetLastDay $1

echo $D_MINUS_ONE

A:

The -d is a GNU date extension (busybox and ast-open date also have one though work differently).
AIX comes with ksh93 though, so no need for GNU date to get the previous working day:
day=2016-01-01
previous_working_day=$(D=$day ksh93 -c '
  printf "%(%F)T" "$D, $(($(printf "%(%w)T" "$D") == 1 ? 3 : 1)) day ago"')


Q:

How do I show unscoped models in Rails Admin?

I needed this myself, so here it is QA-style:
By default, Rails Admin shows a model's default_scope. How do I get it to show every model completely unscoped?

A:

Approach 1
If you only need to list the records you can use the scopes method to control which records are returned. The first array element is the default, so if you add the following to your initialiser:
list do
  scopes [:unscoped]
end

you will see all records.
Approach 2
If you want to do more than list models you can create a dummy rails admin model. For example, assuming you have a Post model with a boolean archived flag:
class Post < ActiveRecord::Base
  default_scope { archived: false }
end

You can create a dummy model to use in rails_admin like so (in app/models/rails_admin)
class RailsAdmin::Post < ActiveRecord::Base
  self.table_name = "posts"
end

You then configure rails_admin to use RailsAdmin::Post and all of the Posts will be unscoped.

A:

Add this monkey patch to your rails admin initializer:
### Monkey pactch for unscoped records in admin panel
require 'rails_admin/main_controller'
module RailsAdmin
  class MainController
    alias_method :old_get_collection, :get_collection
    alias_method :old_get_object, :get_object

    def get_collection(model_config, scope, pagination)
      old_get_collection(model_config, model_config.abstract_model.model.unscoped, pagination)
    end

    def get_object
      raise RailsAdmin::ObjectNotFound unless (object = @abstract_model.model.unscoped.find(params[:id]))
      @object = RailsAdmin::Adapters::ActiveRecord::AbstractObject.new(object)
    end
  end
end

Taken from https://github.com/sferik/rails_admin/issues/353.

A:

I have a solution similar to Charles' above but that monkey patches the model layer rather than the controller layer. This might be a bit more stable across Rails Admin releases, but is ActiveRecord-specific and doesn't affect Mongoid, though the principle would be easily applied to the other adapter.
Again, put it in the rails admin initializer.
#
# Monkey patch to remove default_scope
#
require 'rails_admin/adapters/active_record'
module RailsAdmin::Adapters::ActiveRecord
  def get(id)
    return unless object = scoped.where(primary_key => id).first
    AbstractObject.new object
  end
  def scoped
    model.unscoped
  end
end


Q:

Is there ever a valid reason to have a static method inside a non-static class?

The title is pretty much my entire question.
I'm doing a code review for an off-shore developer who has several static methods inside a non-static class. Before I challenge the developer and mark this as "needs changing", I just want to make sure.
I understand the purpose of a static class: It can not be instantiated and can be used directly. But I can't see any reason to have a static method in a non-static class.  Is there any valid use-case for this?
The methods in question are all private and are called from non-static methods.
Here's an example:
    public ViewResult ClaimDetails(ClaimDetails claim)
    {
        if (claim.ClaimNumber != 0)
        {
            claim = Get_ClaimDetails(claim);
        }
        return View("ClaimDetails", claim);
    }

    private static ClaimDetails Get_ClaimDetails(ClaimDetails claim)
    {
        ClaimsRepository claimsRepository = new ClaimsRepository();
        _claimDetails = new ClaimDetails();
        _claimDetails = claimsRepository.GetClaimDetails(claim.ClaimNumber);
        return _claimDetails;
    }

A:

There are a few things that would raise an eyebrow with me, but the method signature is fine.
static is a keyword that makes sure the method does not use instance members. That's great. It clearly signals this to other developers. I would have argued for the opposite side: a method should be marked static, except when needed otherwise.
Many tools and even Visual Studio itself would flag it if you did not mark it static: CA1822: Mark members as static.
Quoting Microsoft:

Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at run time for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.

So to summarize it: it's perfectly fine as it is.

Reading all the additional comments: it seems the real problem is that an injected repository already exists and the whole method should scrapped and replaced by the line claim = this.injectedClaimsRepository.GetClaimDetails(claim.ClaimNumber);. But that's a whole other problem. The keyword static is perfectly fine if used correctly, the posted code did not show it wasn't.


Q:

How to use CXF soap servlet aside spring REST servlet?

I'm providing a soap webservice with java-first approach, thus using CXF for this. To make it publishing with spring-boot, I have the following dispatcher servlet:
@Bean
public ServletRegistrationBean dispatcherServletRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(new CXFServlet(), "/services/*");
    registration.setName(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
    return registration;
}

This works fine, but I now want to offer a REST service aside. The rest service should NOT be published by cxf, but by the default spring mapping:
@RestConstroller
@RequestMapping("/rest/content")
public class MyServiceRest extends SpringBeanAutowiringSupport {

}

The result of this:

localhost:8080/app-name/rest/content results in HTTP 404.
localhost:8080/app-name/services/rest/content shows a spring message "No service was found."

So, somehow the latter is inside the context of the CXFServlet, and the REST service is not found.
What do I have to change to make this setup work?
By the way: when I remove the ServletRegistrationBean, the rest service works as expected. But that's not an option as I have to offer the soap service alongside.

A:

Your bean named dispatcherServletRegistration is replacing Spring Boot's default DispatcherServlet so your left with just a CXFServlet and no DispatcherServlet in your application.
Update your bean to register the CXFServlet to something like this:
@Bean
public ServletRegistrationBean cxfServletRegistration() {
     return new ServletRegistrationBean(new CXFServlet(), "/services/*");
}


Q:

KeyError: 2 When using large values

So I had to write a program to sort the SAMPLE ID NO's of plants according to their heights into a list (ascending order of heights), I made a code and it works only for small values. When I put large values, it shows:
Traceback (most recent call last):
  File "C:/Python34/plant_hieght_id.py", line 15, in <module>
  del d[int(w[0])]
KeyError: 2

My code can be found at: http://pastebin.com/embed_js.php?i=TXQ94tUy

A:

I had to write a program to sort the SAMPLE ID NO's of plants
  according to their heights into a list (ascending order of heights)

So if d contains the mapping of ids to heights and you want to obtain a sequence of ids sorted by ascending order of height you want to do:
e = sorted(d, key=lambda k: d[k], reverse=True)

Iterating over a dictionary iterates over the keys so sorted(d) is the same as sorted(d.keys()).
By specifying key=lambda k: d[k] you can customize how the comparisons are performed. Here the comparisons are done on the values d[k] instead of the keys
Using reverse=True the sorting is in descending order. (In your question text you say ascending order but the code you provide doesn't do that. If it's really ascending that you want just remove the reverse=True parameter)

The problem with your original code is that:
w=list(d.fromkeys(str(q)))

The fromkeys methods accepts an iterable and creates a new dictionary with values set to that iterable.
In this case q is a number, suppose it is 123. str(q) is the string "123".
So d.fromkeys(str(q)) is the dictionary {'1': None, '2': None, '3': None }.
You the set w to the list of the keys. So w is ['1', '2', '3'].
In the end d[int(w[0])] tries to delete the key 1. But the code provides no guarantee that this key exist!
When you entered the values in your previous loop you may not have inserted any 1 key!
From the code I guess that you want to obtain the maximum value and remove it.
If you wanted to remove the maximum element you should have done:
key, val = max(d.items(), key=lambda x_y: x_y[1])
del d[key]

here max finds the (key, value) pair inside the dictionary with the maximum value and then deletes it.


Q:

Perl and PostgreSQL escaping $

I have an SQL statement executed from perl.
$my_sql = qq (
            SELECT 1 AS ....
            );

Then I do
my $sm = $dbh->prepare($my_sql);
   $sm->execute;

The issue is that my SQL has regex like this in many places.
value ~ '^[1-9][0-9]?/[1-9][0-9]?/[1-9][0-9]{3}$':

So I get errors when I execute the perl script because of these '$'.
Use of uninitialized value $' in concatenation (.) or string at
DBD::Pg::st execute failed: execute called with an unbound placeholder at

How can I avoid these errors and make the SQL statement work?

A:

qq(something) is just another way to say "something" while q(something) means 'something'.
The difference between "this" and 'this' is interpolation, which is enabled only inside double quotes.
my $foo = 123;
print "<< $foo >>";  # prints << 123 >>
print '<< $foo >>';  # prints << $foo >>

So, since $ is not special symbol inside '', just change qq to q.


Q:

Haskell filtering data

I want to be able to filter the below data so I can find specific data for example if I wanted to find an item with only apples it would look similar to this output: [("apple","crate",6),("apple","box",3)]
fruit :: [(String, String, Int)]
fruit = [("apple", "crate", 6), ("pear", "crate", 5), ("mango", "box", 4),
("apple", "box", 3), ("banana", "box", 5), ("pear", "box", 10), ("apricot",
"box", 4), ("peach", "box", 5), ("walnut", "box", 4), ("blueberry", "tray", 10),
 ("blackberry", "tray", 4), ("watermelon", "piece", 8), ("marrow", "piece", 7),
 ("hazelnut", "sack", 2), ("walnut", "sack", 4)]

first :: (a, b, c) -> a
first (x, _, _) = x

second :: (a, b, c) -> b
second (_, y, _) = y

third :: (a, b, c) -> c
third (_, _, z) = z

A:

A couple of alternatives:
filter ((=="apple") . first) fruit
[ f | f@("apple",_,_) <- fruit ]

The first one exploits your first projection, checking whether its result is equal to "apple".
The second one instead exploits list comprehensions, where elements that fail to pattern match are discarded.
Perhaps an even more basic approach is using a lambda abstraction and equality.
filter (\(s,_,_) -> s == "apple") fruit


Q:

Cakephp - get user id in controller when using Auth

It seems like a two-step process to get this,
    $u = $this->Auth->user();
    $uid = $u['User']['id'];

Isn't there a variable set somewhere once a user is logged in? (Sorry for the dumb question.)

A:

I think you can do $uid = $this->Auth->user('id'); - check the api: http://api.cakephp.org/class/auth-component#method-AuthComponentuser

A:

In CakePHP there are several ways to get the user id from the session, here are a few examples
To get the session user id within the controller use:
$uid = $this->Auth->User('user_id');

To get the session user id within a view, use: ( Not Recommended, I would set this in the controller)
$uid = $this->Session->read('Auth.User.id');

To get the session user id within a model, use: (Not Recommended, but a solution)
$uid = CakeSession::read('Auth.User.id');

I don't recommend the above to get the session user id from within the model, I would pass it via the controller, use:
$this->Model->function($uid);

You can also get the session user id via pure php, use: (Althought using Cake you should stick with the conventions)
$uid = $_SESSION['Auth']['User']['id'];

And there are more approaches, this is just a few...

A:

Try this:
$this->Auth->user('id')


Q:

How to make Facebook/Warp output into a string?

OK, so this is basically what I need :

I'm trying to integrate Warp (https://github.com/facebook/warp) in my D project
I need to get the output (of the pre-processing) into a string, and not into a file (as it currently is)

I've had a good look into the sources, but not being a D guru, I thought I might be missing something obvious.
The key probably is in main.d :
            auto foutr = fout.lockingTextWriter();      // has destructor

            context.localStart(sf, &foutr);
            context.preprocess();
            context.localFinish();

With context.localStart() expecting a alias typeof(File.lockingTextWriter()) R; as a second param (the output stream?).
However, I simple cannot spot that anywhere in the documentation.
Any ideas?

UPDATE
I think I'm very close; I'll post a complete solution once I'm 100% sure. But this is what I spotted in context.d (unittests are a great place to find useful code, for sure! lol)
version (unittest)
{
    void testPreprocess(const Params params, string src, string result)
    {

        uchar[100] tmpbuf = void;
        auto outbuf = Textbuf!uchar(tmpbuf);

        auto context = Context!(Textbuf!uchar)(params);

        // Create a fake source file with contents
        auto sf = SrcFile.lookup("test.c");
        sf.contents = cast(ustring)src;

        context.localStart(sf, &outbuf);

        context.preprocess();

        context.expanded.finish();
        if (outbuf[] != result)
            writefln("output = |%s|", outbuf[]);
        assert(outbuf[] == result);
    }
}

version (all)
{
unittest
{
    const Params params;
    testPreprocess(params,
"asdf\r
asd\\\r
ff\r
",

`# 2 "test.c"
asdf
# 3 "test.c"
asdff
`);
}

A:

I haven't actually looked at this code, but lockingTextWriter is what D calls an output range.
It's simply a struct with a method called put that accepts a string as an argument. So, you might be able to get the info as a string by doing this:
struct StringSink {
    string result;
    void put(in char[] s) { result ~= s; }
}

StringSink sink;
context.localStart(sf, &sink);
.....

string result = sink.result;

or something along those lines.


Q:

Big database project on ASP.NET MVC

I'm working on really nice project in ASP.NET MVC, where comapnies can generate some pdf documents, save some data etc. I have a piece of project already. [no important]
Programist will add Company with one AdminUser, AdminUser[Boss of company or smth like that] will add next users with roles - 'worker' etc.
So there is problem. I have >10 tables, one company can easly create 50 rows in each table by one month. So what is better add to few tables "CompanyId" and filtr everything, or create new database with 10 tables for each company?
For start i want hmm ~20 companies. But next for example 100-1000 companies.
I think that second solution is better, but how to do it? At last can you direct me to good books/articles about it?

A:

Under almost all circumstances, you want to store the data in a single set of 10 tables.  A load of 50 rows/month growth is really nothing in a database.  A load of 50*10 rows/month is really nothing.
Why do you want them in a single set of tables?

You can readily query across all the tables to see what is happening across your business.
You can set up the tables once and forget about them.
You can more easily update the software and install fixes.  You only need to do this once, not once per client.
You don't have the danger of different clients getting out of synch.
Tables are more efficient when they have lots of data rather than when they have little data.

There are circumstances where you would want a separate database for each client, with their own set of tables:

Security restrictions require that you physically separate the data.
Each client has a bespoke application, so you expect different clients to be using different versions.
Clients have to access different versions of the database software for some reason.
You need to be sure that you can separate clients for performance reasons.

There are no doubt more reasons on both sides.  These are just some I can think of quickly.


Q:

How can I export an FASM variable to VC++ Express 2012?

I wrote some assembler modules and used constant variables to define their size in FASM.
How can I use these variables in VC++ after linking with an FASM object file?
For example, if my assembler code is like so:
start: //function declaration, exported
xor eax, eax
inc eax
retn
end_func:

The size is end_func - start
How can I export the size of end_func - start into VC++?

A:

You can export a variable with the public directive on the FASM side, and import it into your C++ code with extern.
Here's a short example:
// --- test.asm ---
format MS COFF

public counter as '_counter'

section '.data' data readable writeable
counter dd 0x7DD

// --- example.cpp ---
#include <iostream>

extern "C" long int counter;

int main() {
    std::cout << "Hello " << ++counter << "!" << std::endl;
    return 0;
}

// --- Compile, Link and Run ---
> fasm test.asm
> cl /EHs example.cpp test.obj
> example.exe

// --- Output: ---
Hello 2014!

The example uses the MSVC cl.exe compiler directly on the command line for illustrative purposes, however in your case it should be trivial to add the fasm .obj output files to link with your code in the VS link project settings.


Q:

Music Player for Linux with ability to read and write custom ID3 Tags

On Windows I got used to foobar and something I really like is the tagging of files with custom tags like rating, first listened, play counter, bpm and so on. And displaying these tags in a (preferably sortable) grid.
Which player for Linux that supports custom tags is recommendable?
My current foobar on Windows:

The player should be able to show tags I have added to the tracks. And editing the custom tags would be even better :-)

A:

The music player Quod Libet (GitHub · Wikipedia) comes with the tag editor Ex Falso (Wikipedia). Both are free/libre software, available cross-platform, and gratis.
Inline editing is not possible, but when right-clicking a track in Quod Libet and selecting "Edit Tags", you can open Ex Falso, which then has this track pre-selected (or press: Alt+Enter). You can add custom tags with Ex Falso. See their documentation: Editing Tags
Quod Libet already comes with a rating feature (the ratings can get saved in the files, but not as visible meta tag, I think because they can be different per user), but nothing stops you from adding your own rating tag (however, then you would have to use Ex Falso for setting the rating, which is not as comfortable as setting the rating inline).
As explained in my answer to a Super User question, you can add columns that show values from your custom tags. See their FAQ entry: How do I add custom / unusual tags to the columns in the song list? (as far as I know, it’s also possible to show multiple tags in the same column, but I didn’t test it yet)
Searching for custom tag values is also possible. See in their documentation: Searching a Specific Tag

I recommended Quod Libet as iTunes alternative, for huge music collections, and for saving (and searching in) lyrics.


Q:

Making a GET rest call for flickr api from xcode

I'm trying to make a GET call using flickr.photos.getInfo method from an app. Goal is to get info about a photo using it's id.
my method:
+(NSDictionary*)photoForId:(NSString *)photoID
{
    NSLog(@"photo id = %@", photoID);
    NSString *request=[NSString stringWithFormat:@"http://api.flickr.com/services/rest/flickr.photos.getInfo&photo_id=%@&format=json&nojsoncallback=1&extras=original_format,tags,description,geo,date_upload,owner_name&page=1&method=flickr.photos.search", photoID];

        NSLog(@"output=%@",[self executeFlickrFetch:request]);
    return [[[self executeFlickrFetch:request]valueForKey:@"photos.photo"]lastObject];

}

executeFlickrFetch method:
+ (NSDictionary *)executeFlickrFetch:(NSString *)query
{
    query = [NSString stringWithFormat:@"%@&format=json&nojsoncallback=1&api_key=%@", query, FlickrAPIKey];
    query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  NSStringFromSelector(_cmd), query);
    NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;
    return results;
}

Right now this call is returning null. I know execute fetch works because it is fetching photos by photographer, or place. Just need to figure out the photo id.

A:

this is the correct request:
NSString *request=[NSString stringWithFormat:@"http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&photo_id=%@&format=json&nojsoncallback=1&extras=original_format,tags,description,geo,date_upload,owner_name&page=1", photoID];


Q:

Tensorflow : result of training data(using sigmoid) came out reversely

I tried to train my data using 'Gradient Descent Algorithm' to minimize cost value,
and strangely enough, result came out differently depending on the number of steps.
Below is my training code:
import tensorflow as tf
X = tf.placeholder(tf.float32, shape=[None, 2], name="X")
Y = tf.placeholder(tf.float32, shape=[None, 1], name="Y")
W = tf.Variable(tf.random_normal([2, 1]), name="weight")
b = tf.Variable(tf.random_normal([1]), name="bias")

hypo = tf.sigmoid(tf.matmul(X, W) +b)

cost = -tf.reduce_mean(Y*(tf.log*(hypo)) + (1-Y)*(tf.log(1-hypo)))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-3)
train = optimizer.minimize(cost)

#### Saving model
SAVER_DIR = "model"
saver = tf.train.Saver()
checkpoint_path = os.path.join(SAVER_DIR, "model")
ckpt = tf.train.get_checkpoint_state(SAVER_DIR)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
for step in range(4201):
    cost_val, hy_val, _ = sess.run([cost, hypo, train], feed_dict={X:x_data, Y=y_data})

saver.save(sess, checkpoint_path, global_step=step)

And restore model:
saver = tf.train.import_meta_graph('./model/model-4200.meta')
saver.restore(sess,'./model/model-4200')

result = sess.run(hypo, feed_dict={X: x_data_test})

fig, ax = plt.subplots()
ax.plot(Julian_test,y_data_test,'ro-') # Correct answer. all items are one of the two:0 or 1.
ax.plot(Julian_test,result,'bo-')      # Result of training. Predict answer within
plt.show() #                            sigmoid function, so all items are in range of 0 ~ 1.

As figure is showing, the result of sigmoid is reverse.
But, when I changed the number of steps to 5000, (in my above code, I only changed step.)
result came out correctly.

I can't understand why it makes defference. Did I miss something? Need help indeed!

A:

in simple terms by increasing the steps you are allowing your tensorflow code/model to see the data multiple times, hence giving it the capabilities to learn more insights about the data. and generalize its representation.
E.G
Lets say you give your model 2000 steps and at the end of 2000 steps it finds a minimum and your model stops there. but what if the minimum cost that the model has find till now is not the global minimum, we cant say cause we restricted it to 2000 steps. so lets say you increase the steps to 20000 and model now finds another minimum which gives more accurate results.
But you need to make sure that your model does-not overfit i.e giving accuracy on your training data but not on your validation set. (So make sure not to increase num steps by too much).


Q:

Can Stellar-core be packaged in a container system such as Docker?

I want to incorporate Stellar-core and horizon into my private infrastructure using Docker.  Can Stellar-core be packaged in a container system such as Docker?

A:

Yes, Docker provides a simple way to incorporate stellar-core and horizon into your infrastructure so long as BUCKET_DIR_PATH, TMP_DIR_PATH, and the database are stored on persistent volumes.
First, decide whether you want your container to be part of the public, production Stellar network (referred to as the pubnet) or the test network (called testnet) that is recommended while developing software because you need not worry about losing money on the testnet. You'll provide either --pubnet or --testnet as a command line flag when starting the container to determine which network (and base configuration file) to use.
Next, you must decide whether you will use a docker volume or not. When not using a volume, the container is in ephemeral mode, that is, nothing will be persisted between runs of the container. Persistent mode is the alternative, which should be used in the case that you need to either customize your configuration (such as to add a validation seed) or would like to avoid a slow catch-up to the Stellar network in the case of a crash or server restart. Persistent mode is recommended for anything besides a development or test environment.
Finally, you must decide what ports to expose. A container that exposes no ports isn't very useful, so it's recommended at a minimum you expose the horizon http port.

A:

Yes it is possible.
You could use the official docker image provided by Stellar as starting point.
Github source here

A:

I created a few docker images for stellar including one with core and horizon.
https://github.com/StellarKit


Q:

foley prop needed: a stack of cash

need a prop for the handling of cash about yeah big:

Since, you know, I don't have a stack of cash that size on me.  on screen this cash is pulled out of a counting machine, patted flat and placed on a table.
I'm cutting up an old book now, but any other thoughts would be appreciated.

A:

The cut book ended up working out perfectly.  I needed a lot of bills (several hundred), and I needed the paper to sound both thick, non-laminated, and a little worn, so the book pages gave me the depth and almost the texture I needed.
To finish the trick I took a few real bills and put them on either side of the stack, and took about 15 book made bills, crumpled them, opened them back up and put them inside the rest of the stack in intervals.
foley went very quickly, and with a little eq they sounded exactly like they looked.
and now I have a new prop built.  :)
thx for the help.


Q:

Appium Android click on element in WebView crashes code, but is executed in the emulator

I am developing Appium tests for an Android app. The problem happens during the login to facebook which works through a WebView. The login to facebook is necessary for the app login and the app registration. The login to facebook is in both cases (app login and app registration) the same, so I execute in both cases the same method:
private void logInAtFacebook(String email, String password) {
    findElementWithTimeout(By.className("android.webkit.WebView"), 10);
    Set<String> contextHandles = driver.getContextHandles();
    for (String s : contextHandles) {
        if (s.contains("WEBVIEW")) {
            driver.context(s);
        }
    }

    findElement(By.xpath("//input[@name='email']")).sendKeys(email);
    findElement(By.xpath("//input[@name='pass']")).sendKeys(password);
    findElement(By.xpath("//button[@name='login']")).click();
    findElement(By.xpath("//button[@name='__CONFIRM__']")).click();

    driver.context("NATIVE_APP");
}

It is weird, that the app login with facebook works, but the app registration with facebook crashes. The second last line in the above method...
findElement(By.xpath("//button[@name='__CONFIRM__']")).click();

...doesn't return, but the button is clicked in the UI. In other words, the execution stops at this line, so that the next line...
driver.context("NATIVE_APP");

... is never executed. I am really confused. Why is the same code working for the app login, but not for the registration?!
Iv'e copied the logs from Android Studio:
First, the last lines before it crashes during app registration:
01-30 14:18:25.016 24439-24439/de.blabla W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.103 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.184 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.260 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.322 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.401 24439-24450/de.blabla  I/art: Background partial concurrent mark sweep GC freed 133(8KB) AllocSpace objects, 3(18MB) LOS objects, 13% free, 24MB/28MB, paused 9.861ms total 80.852ms
01-30 14:18:44.416 24439-24439/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:18:44.516 24439-24475/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df02443c260: ver 2 0 (tinfo 0x7df02440ce80)
01-30 14:18:44.633 24439-24439/de.blabla  W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 24439
01-30 14:18:44.807 24439-24475/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df02443c260: ver 2 0 (tinfo 0x7df02440ce80)
01-30 14:18:45.111 24439-24475/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df02443c260: ver 2 0 (tinfo 0x7df02440ce80)

And the same lines of the working app login:
01-30 14:21:17.179 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.464 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.573 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.640 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.644 25078-25089/de.blabla  I/art: Background partial concurrent mark sweep GC freed 156(6KB) AllocSpace objects, 2(12MB) LOS objects, 11% free, 30MB/34MB, paused 3.293ms total 143.091ms
01-30 14:21:30.717 25078-25078/de.blabla  W/art: Attempt to remove non-JNI local reference, dumping thread
01-30 14:21:30.843 25078-25112/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df024436640: ver 2 0 (tinfo 0x7df02440c900)
01-30 14:21:31.002 25078-25078/de.blabla  W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 25078
01-30 14:21:31.153 25078-25112/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df024436640: ver 2 0 (tinfo 0x7df02440c900)
01-30 14:21:31.564 25078-25112/de.blabla  D/EGL_emulation: eglMakeCurrent: 0x7df024436640: ver 2 0 (tinfo 0x7df02440c900)
01-30 14:21:31.721 25078-25248/de.blabla ... *no it continues the test as it should*

A:

I found an inconvenient workaround, but it works for now:
private void logInAtFacebook(String email, String password) {
    findElementWithTimeout(By.className("android.webkit.WebView"), 10);
    Set<String> contextHandles = driver.getContextHandles();
    for (String s : contextHandles) {
        if (s.contains("WEBVIEW")) {
            driver.context(s);
        }
    }

    findElement(By.xpath("//input[@name='email']")).sendKeys(email);
    findElement(By.xpath("//input[@name='pass']")).sendKeys(password);
    findElement(By.xpath("//button[@name='login']")).

    driver.context("NATIVE_APP");

    driver.findElementByAccessibilityId("Continue").click();
}

The problem had something to do with the click within the WebView, so I decided to go back to context "NATIVE_APP" before the last click on the "Continue-Button" happens.
I'm still hoping for a better way to fix this!


Q:

Searching and printing sections of file

I have a file in the following format-
-----------------------
key1 = val11
key2 = val21
key3 = val31
-----------------------
key1 = val12
key2 = val22
key3 = val32
------------------------

I need to query by giving "key2=val22", and print the complete section (key1, key2, key3) of the matching block.

A:

One of the possible ways is to do that using csplit:
csplit -s --prefix=mytempfile testfile '/-----------------------/+0' "{*}" \
    && cat `grep -l 'key2.*=.*val22' mytempfile*` && rm mytempfile*

-----------------------
key1 = val12
key2 = val22
key3 = val32


Q:

Rota's "lure of the algorithm"?

Quoting Gian-Carlo Rota (from the Foreword to Richard Stanley's Enumerative Combinatorics Volume I), "In mathematics, however, the burden of choice faced by the writer is so heavy as to turn off all but the most courageous. And of all mathematics, combinatorics is nowadays perhaps the hardest to write on, despite an eager audience... Shall the author yield to one of the contrary temptations of recreational math at one end, and categorical rigor at the other? or to the highly rewarding lure of the algorithm?"
Does anyone understand this last statement? What is the lure of the algorithm? Is it a reference to something particular?
I am sometimes quite happy to attain an elegant algorithm, but when it comes to writing I tend to leave the details of hard-to-formalize algorithms to the reader (e.g. "We omit the proof that this establishes the desired bijection."). And if there is a "lure", I cannot think of any example to substantiate Rota's slightly derisive tone. I admire authors who contribute algorithmic intuition to the literature. In Stanley's own book (Volume II) is an impeccable discussion of algorithms concerning the enumeration of rooted trees.

A:

I can only speculate about Rota's attitudes, but it's not obvious to me that this passage is meant to be derisive to algorithms.
I would think the lure is in the ability to exhibit constructions explicitly, and in the goal of making the construction itself as elegant and as general as possible. Doing so is a challenge to understand the construction as deeply as possible. This is, at least, why I am strongly drawn to algorithms.


Q:

how to make spring starter project(spring boot) for Java version 6 in eclipse?

i want make spring boot project in eclipse using project wizard.
select Spring - Spring Starter Project
can't select java 6 option.

Why is there no choice Java Version 6?
my eclipse and sts plugin version below:
Version: Luna Service Release 2 (4.4.2)
Installed STS Plugin:

can i display Java Version 6 in Project Wizard?
or make project for Java Version 8 first can migration to Java Version 6?

A:

Spring Boot 1.5 is the last release version which supports java 6.
For Spring Boot 2 you should have Java 8 or higher version.
So it is possible to run Spring Boot 1.5 on Java 6. See documentation reference guide.


Q:

Syntax error when using << but not when using +=

On ruby 1.8.7
Why this is ok:
string += method "value"

But this raise a syntax error:
string << method "remove reviewer"

Is the same behaviour in newer versions of ruby?

A:

You can explain this behaviour with the different Operator Precedence of << and =+ and method calls.
Ruby reads your first examples as:
string += (method "value")

but the second one as:
(string << method) "remove reviewer"

IMO it is a good practice to use parenthesize for method call even if Ruby does not need them in many case. This makes the code more readable and less error-prone:
string += method("value")
string << method("remove reviewer")


Q:

sort sum of matching fields in a large file

I have a large file (around 200 MB) and I need to extract
top 10 (and top n%) most aggregate values for tuples
for example I have a 2 column csv file:
c1 c2
----------
a,10
b,20
c,5
d,60
a,20
c,10
a,20
b,10

and I need top 2 records with maximum aggregate c2 values,
in this case i need this output:
a,50
d,60

As I said the file is too large (500000 long records)
and if I need top 1% or 10% of it I can't just simply use
something like this because it passes the number of unique a,b,c,d,...
while read line
do
Sum=$(awk -F, -v inp=$line '$1==inp{x+=$2;}END{print x}' $INPUT_File)
done < firstColumnFile

Note that firstColumnFile in here is just a temp file I put a,b,c,d,... in it...
my main file which must be processed is INPUT_File
How can I do this with bash, awk using a single pass through the file?

A:

You can do the aggregation with the following awk script:
$ awk -F, 'NR>2{a[$1]+=$2}END{for(k in a)print k","a[k]}' file
a,50
b,30
c,15
d,60

Tac on a sort and tail for only n valueS:
$ awk -F, 'NR>2{a[$1]+=$2}END{for(k in a)print k","a[k]}' file | sort -t, -k2 | tail -n 2
a,50
d,60


Q:

Getting values from an asp.net mvc dropdownlist

Can someone help me with getting values from a dropdownlist in asp.net mvc?
I can get values from textboxes,etc...but,how do I get these 2 things...

Getting Selected Item Value of the drop down list from the controller class
Getting all the list of items of the drop down list from the controller class

Thanks

A:

You can get the selected value from a drop down list the same way as you do for text boxes.
Using default model binding
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
  //MyList will contain the selected value
  //...
}

or from a FormCollection
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(FormCollection form) {
  string val = form["MyList"];
  //...
}

or from the request
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetValueExample(string MyList) {
  string val = Request.Form["MyList"];  //or
  val = Request["MyList"];
  //...
}

Where your drop down list is named "MyList".
<%= Html.DropDownList("MyList", MyItems) %>

or straight HTML
<select name="MyList">
  <option value="1">Item 1</option>
  <option value="2">Item 2</option>
</select>

The browser will only submit the selected value from the drop down list and not all the other values. To get the list of all the other items you should invoke the code that populated the list in the first place (assuming you used Html.DropDownList()).
Update
[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample() {
  ViewData["MyItems"] = GetSelectList();
  return View();
}

[AcceptVerbs(Http.Get)]
public ActionResult GetValueExample(string MyList) {
  //MyList contains the selected value
  SelectList list = GetSelectList(); //list will contain the original list of items
  //...
}

private SelectList GetSelectList() {
  Dictionary<string, string> list = new Dictionary<string, string>();
  list.Add("Item 1", "1");
  list.Add("Item 2", "2");
  list.Add("Item 3", "3");
  return new SelectList(list, "value", "key");
}

//...

<%= Html.DropDownList("MyList", ViewData["MyItems"] as SelectList) %>


Q:

How do I compile and link unit tests?

I have recently started trying to use TDD in one of my C++ projects. I am very new at this, and I have some very basic questions regarding to the way unit tests are compiled and used. I am using the Boost.Test library on Linux.

Is it common to compile a single large test program, containing all test suites, for all your units? How about splitting the tests into many smaller independent test programs?
How is linking handled (with make)? Every test program object must be linked with the object file(s) from my source program that contains whatever it is that's being tested. Is there a way to handle this automatically? To be more specific, is there anyway to write a Makefile so that make automatically determines what object files must be linked together to generate a certain unit test program?

Update: My code is organized in many .cpp/.h files, and is currently monolithic (no libraries). The unit tests are in a separate directory, usually in 1-to-1 relationship with the .cpp files from my source tree.
Update 2: Hoping that this will make my question less broad, here is an excerpt from the Makefile I am using:
$(TSTDIR)%.$(TEST): $(OBJDIR)%.$(TEST).$(OBJEXT) $(OBJDIR)%.$(OBJEXT)
    @mkdir -p $(@D)
    @$(CXX) -o $@ $^ $(TSTLIBS)

$(OBJDIR)%.$(OBJEXT): $(SRCDIR)%.$(SRCEXT) $(DEPDIR)%.$(DEPEXT)
    @mkdir -p $(@D)
    @$(CXX) $(CXXFLAGS) $(INCLUDES) -o $@ $<

$(TEST) is just a marker I am using to differentiate between my unit tests and other files. Note that I am currently linking all test programs with the object file that bears the same name. However this will break if symbols from another object file are also needed.
Update 3: This is an example of what I am talking about in the above paragraph.
MyOtherClass.h:
class MyOtherClass
{
public:
    int Foo();
}

MyOtherClass.cpp:
#include "MyOtherClass.h"

int MyOtherClass::Foo()
{
    return 0;
}

MyClass.h:
#include "MyOtherClass.h"

class MyClass
{
public:
    int Foo();

private:
    MyOtherClass moc_;
}

MyClass.cpp:
#include "MyClass.h"

int MyClass::Foo()
{
    return moc_.Foo();
}

TestMyClass.cpp would test if MyClass::Foo returns 0. Using my current Makefile, this will not compile, as the test program needs to be linked with both MyClass.o and MyOtherClass.o.

A:

I found this excellent answer that was given to a related question.
It's possible to solve the linking problem by using static or dynamic libraries. If the object files being tested are compiled into libraries, then when linking the unit test program, it will pull whatever dependencies it needs from the library.


Q:

Why is there no backup for wallet keys?

I've seen several responses from actives saying once a keystore is lost, all is lost.
This is absolutely unacceptable.
Having to find
C\USERS\\APPDATA\ROAMING\ETHEREUM\KEYSTORE

or wherever it is, by having to Google a post explaining the process,
is totally unacceptable.
The engineers behind this left mistake for a reason, knowing full well a Windows crash or drive failure, or that the average, non-expert with Ethereum, would eventually make this mistake and lost all their Ether in the process.
It's out there somewhere, locked up, but my guess is, someone on the inside of ethereum.org knows how to retrieve it.
A back door key to the vault, so to speak.
I want to know, specifically, who came up with this idea and why it has not been corrected. And secondly, where the lost Ether is.
Or who's since stolen it.

A:

I've seen several responses from actives saying once a keystore is lost, all is lost.

Correct.

The engineers behind this left mistake for a reason, knowing full well
  a Windows crash or drive failure, or that the average, non-expert with
  Ethereum, would eventually make this mistake and lost all their Ether
  in the process.

In my opinion, Ethereum, and cryptocurrencies in general, are still not for the non-expert. Without wanting to sound condescending, they're based on difficult stuff, and require the user to be rather more than computer literate.
The terms and conditions for the original Ethereum Crowdsale stated the following (in caps):
"WARNING: DO NOT PURCHASE ETH IF YOU ARE NOT AN EXPERT IN DEALING WITH CRYPTOGRAPHIC TOKENS AND BLOCKCHAIN-BASED SOFTWARE SYSTEMS"
At some point the infrastructure will presumably become more user-friendly, but I don't think we're there yet.

Back to the back-ups...
Backing-up to another on-disk location is not the best way to store currency.
See: What is the recommended way to safely store Ether?
By creating automatic back-ups you increase the attack surface. By copying the keystore files to a second location on your computer, you create another place they can be found. If it's on the same drive, then you've done nothing to negate drive crashes.
What happens if you forget automatic back-ups are turned on? Or you switch them off that one time for some reason and then forget to turn them back on again? What happens if the back-up location no longer exists? What happens when you change the back-up location, perhaps multiple times, and you end up with keystore files scattered all over the shop? etc., etc.
Backing up automatically would make users dumb. It would mean they no longer had to think critically about how they were storing their currency. It would lull them into a false sense of security.

It's out there somewhere, locked up...

Even if you lose the keys to your account, you can still check the ether exists using the account's address and any bog-standard chain explorer. You'll be able to see it - and see that no one else has moved/taken it - you just won't be able access it.

...but my guess is, someone on the inside of ethereum.org knows how to retrieve it.

All the code is open-source. If there was a backdoor then people - people with lots of money invested - would have probably found it by now.

And secondly, where the lost Ether is.

As above - it's exactly where those people left it.


Q:

Linq Cannot implicitly convert type

I m new to Linq syntax and getting an error

"Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo>' to 'System.Collections.Generic.IEnumerable<System.Reflection.MethodBase>'. An explicit conversion exists (are you missing a cast?)"

on the following line in my application
 IEnumerable<MethodBase> methods =
                    from p in defaultMembers.OfType<PropertyInfo>()
                    select p.GetGetMethod() into m
                    where m != null
                    select m;

Any ideas? thanks

A:

Problem is IEnumerable<T> is not covariant in .NET 3.5 (it is in .NET4+). That's why you can't assign IEnumerable<ChildClass> to IEnumerable<ParentClass>.
Change your variable declaration to exactly match the query results (using var and implicitly typed variable or specifying the correct type):
 IEnumerable<MethodInfo> methods =
                    from p in defaultMembers.OfType<PropertyInfo>()
                    select p.GetGetMethod() into m
                    where m != null
                    select m;

Or if you really need IEnumerable<MethodBase> add additional cast into your query:
 IEnumerable<MethodBase> methods =
                    from p in defaultMembers.OfType<PropertyInfo>()
                    select p.GetGetMethod() into m
                    where m != null
                    select (MethodBase)m;