C++ Pig Latin program I'm just wanting some input on to how others would approach this problem. I am learning and wish to gain insight on others techniques. Be as critical as you need. I want to learn. I feel this code is sloppy and the logic is confusing.

/*
    Pig Latin
    Write a program that reads a sentence as input and converts
    each word    to “Pig Latin.” In one version, to convert a word to
    Pig-Latin you remove the first letter and place that letter at the
    end of the word. Then you append the string “ay” to the word. Here
    is an example:
        English: I SLEPT MOST OF THE NIGHT
        Pig Latin: IAY LEPTSAY OSTMAY FOAY HETAY IGHTNAY
*/
#include <iostream>
#include <string>
using namespace std;

// takes a string argument and returns the pigLatin equivalent
string pigLatin(string);

int main()
{
    string mySentence;

    getline(cin, mySentence);
    mySentence = pigLatin(mySentence);
    cout << mySentence << endl;

    return 0;
}

string pigLatin(string word){

    //pigLatWord holds word translated in pig latin.
    //pigLatSentence holds entire translated sentence.
    string pigLatWord, pigLatSentence = "";
    int length = 0, index = 0;

    while (word[index] != '\0'){
        // .find returns -1 if no match is found
        if (word.find(' ', index) != -1){
            length = word.find(' ', index);
            length -= index;//length - index = the number of characters in a word
            pigLatWord = word.substr(index, length);
            pigLatWord.insert(length, "ay");
            pigLatWord.insert(length, 1, word[index]);//first letter is inserted at the end of the string
            pigLatWord.erase(0, 1);// erase first letter in string
            index += length + 1;//adding one moves index from 'space' to first letter in the next word
        }
        else{
            pigLatWord = word.substr(index);
            length = pigLatWord.length();
            pigLatWord.insert(length, "ay");
            pigLatWord.insert(length, 1, word[index]);
            pigLatWord.erase(0, 1);
            index = word.length();
        }

        pigLatSentence += (pigLatWord + " ");
    }
    return pigLatSentence;
}

See at @Caridorc first.

Use the full power of the stream.

The standard stream operators will read a word at a time for you.

std::string word;
while(std::cin >> word)
{
     // DO STUFF.
}

The above will read a file. If you just want to read a line. Read a line then use string stream.

// Read a line
std::string line;
std::getline(std::cin, line);

// convert line to stream
std::stringstream linestream(line);

// Loop over it one word at a time.
std::string word;
while(linestream >> word)
{
     // Operate on word.
}

DRY your code

Both sides of your if statement are doing the same thing. The difference is handling the last word (one not terminated by a space). You should move common code outside the if statement just leave the non common code in the if statement.

    if (<test>)
    {
    }
    else
    {
    }

    // This all seems common across the two if statements.
    pigLatWord = word.substr(index);
    length = pigLatWord.length();
    pigLatWord.insert(length, "ay");
    pigLatWord.insert(length, 1, word[index]);
    pigLatWord.erase(0, 1);
    index = word.length();

Declaration when needed.

Put your variable declarations as close to the point of use as you can. This way you don't need to look for their type very far (it is where the code is). They only get constructed when you need them (and destroyed as soon as possible) so preventing excessive use of space and not costing anything if you don't need them.

// These could be moved to the other side of the if.
// As pigWord is only used after the loop (in my new version)
string pigLatWord;

Declare one variable per line.

string pigLatWord, pigLatSentence = "";
int length = 0, index = 0;

Humans need help in reading code. Don't make it hard for them. Declare one variable per line. This also helps when refactoring code later. You will only move the variables you need and source control tools will find it easier to do a diff on the change.

Pass by const reference.

If you do not plan on modifying the input pass by const reference to prevent a copy.

string pigLatin(string const& word){
             //        ^^^^^^

Design.

If I was actually going to write this I would encapsulate the concept of a Pig Latin word in a class. Then you can localize the change in a single well named class. You can then make use of standard routines to help read/print.

class PigLatinWord
{
    // STUFF
};

int main()
{
    // Copies std::cin to std::cout converting to PigLatin
    // on the copy to the output stream.
    std::copy(std::istream_iterator<std::string>(std::cin),
              std::istream_iterator<std::string>(),
              std::ostream_iterator<PigLatinWord>(std::cout, " ")
             );
}


Efficient implementation of aggregating test/train data Here is a short python snippet to ingest train data:

x_train = []
y_train = []

for x,y in train:
    x_train.append(x)
    y_train.append(y)

x_train = np.asarray(x_train)
y_train = np.asarray(y_train)

The variable train is a list of 60000 (x,y) tuples.

How about:

x_train, y_train = np.hsplit(np.asarray(train), 2)

Which uses only numpy functions and should be a bit faster than your implementation using intermediate lists.


Self-contained poll application I am working on a small and self-contained poll application, not unlike Straw Poll whereby one user can submit a poll and other users can vote (but only once).

I am building this little application in the open, using Angular for the front-end and Web Api for the back-end. I am using Fluent Validation to validate incoming models.

Using an action filter and Fluent Validation I have managed to remove all basic model validation from my controller.

I need to carry out some more advanced validation after I load the poll from the database. My action method has become overrun by such validation logic as you can see:

public IHttpActionResult Put(int pollId, VoteInput voteInput)
{
    var poll = _session.Load<Poll>(pollId);
    var voterIp = Request.GetOwinContext().Request.RemoteIpAddress;

    if (poll == null)
    {
        return BadRequest("you cannot vote on a poll that does not exist.");
    }

    if (poll.VoterIps.Contains(voterIp))
    {
        return BadRequest("you cannot vote on this poll because you have already voted.");
    }

    if (voteInput.Options.Length > 1 && !poll.MultiChoice)
    {
        return BadRequest("you cannot vote for more than one option. noob.");
    }

    foreach (var option in poll.Options.Where(option => voteInput.Options.Contains(option.Id)))
    {
        option.Votes += 1;
    }

    poll.VoterIps.Add(voterIp);
    _session.SaveChanges();

    return Ok();
}

I would very much like to remove some, if not all of this validation logic from the controller.

I have a really sound infrastructure - I am using Fluent Validation and a DI Framework - but owing to my inexperience with said technologies, I cannot think of a clean way to extract the validation logic.

What are some ways I can reduce or eliminate the validation in my controller?

I cannot think of a clean way to extract the validation logic.

All validation logic should be in an appropriate "validation service" class as @meWantToLearn said.

I assume something like this is possible in FluentValidation:

public class PollVoteValidator : AbstractValidator<Poll,VoteInput>

If not then make a simple class that contains both of these and then create a validator for that:

public class PollInput {
    public Poll {get; set;}
    public VoteInput {get; set;}
}

public class PollVoteValidator : AbstractValidator<PollInput>

Validation Separation of Concerns

Validations such as if (poll == null) belong in a PollValidator class and if (poll.VoterIps.Contains(voterIp)) in a VoterIpsCollection class.

Even if you want to check for null method arguments up front (and that will simplify downstream control logic), the above still applies.

Validation Coordination

The PollVoteValidator would coordinate everything perhaps, with logic, somewhere, like this:

public class PollVoteValidator {
    public ValidateResults Validate (poll, voteInput) {
        var pollValidateResults = myPollValidator.Validate(poll);
        var voteInputValidateResults = myVoteInputValidator.Validate(voteInput);
        // I hope poll is not null!
        var voterIpsCollectionResults = myVoterIpsCollectionValidator.Validate(poll.VoterIps);

        if(/* validations above pass */)
            pollVoteValidatorResults = mypollVoteValidator.Validate(poll, voteInput);

        // consolidate validation results as desired (error messages)
        // for return to the caller

        return pollVoteValidatorResults;
    }
}

One More Thing

This: var voterIp = Request.GetOwinContext().Request.RemoteIpAddress; seems "orphaned" from an OO perspective. voterIp feels like a Voter class property, so maybe you should instantiate a Voter; this implies a "validation service" class for Voter.

The above Voter class stuff may seem like overkill, but there is no OO principle that says "if something seems simple, ignore OO principles".


go-pg efficient multi table/row insert What is an efficient way to write this raw PostgreSQL query using in go? I'm using go-pg but something with just the pg library should translate well to go-pg.

Table:

companies:
  - id string, primary key
  - name string, not null

services:
  - id string, primary key
  - company_id string, not null, foreign key (company.id)
  - name string, not null

Query:

WITH company AS ( INSERT INTO companies(id, name) VALUES('1', 'acme') RETURNING id)
INSERT INTO services(id, company_id, name) VALUES
('1', (select company.id from company), 'cool service'),
('2', (select company.id from company), 'cooler service');

This is what I came up with. It's very hacky and I feel there is a more "idiomatic" way of doing this.

type Company struct {
    ID string
    Name string
    Services []*Service
}

type Service struct {
    ID string
    CompanyID string
    Name string
}

c := &Company{
    ID: uuid.NewV4().String(),
    Name: "test comp",
}

s := []*Service{
    &Service{
        ID: uuid.NewV4().String(),
        Name: "test svc",
    },
}

c.Service = s

values := []interface{}{
    c.ID,
    c.Name,
}

q := `
    WITH company as (INSERT INTO companies(id, name) VALUES ($1, $2) RETURNING id) INSERT INTO services(id, company_id, name) VALUES
`

var i int = 3
for _, row := range c.Services {
    q += fmt.Sprintf("($%d, (select company.id from company), $%d),", i, i+1)
    values = append(values, row.ID, row.Name)
    i += 2
}

q = strings.TrimSuffix(q, ",")

stmt, err := DB.Prepare(q)
if err != nil {
    return err
}

if _, err := stmt.Exec(values...); err != nil {
    return err
}

I'm somewhat new to using go's sql library and I know I have to be missing something. I saw the pg library allows for bulk imports  but it's a bit confusing how I would do that in my case where I need to populate two separate tables the and the bulk import occurs on the second table.

It doesn't seem that the pq library has a query builder or a specific type. So building a query in an idiomatic and readable way should be done as you would do for a normal string, and that is using the text/template package. This will allow you to get rid of many code smells:

the line containing your query is long and not easily readable, maybe skip more lines
you can write the skeleton to your query once, instead of using successive appends — this is also more efficient if you have many services
the call to strings.TrimSuffix can be avoided using a simple condition in your template
you can replace (select company.id from company) directly by its value, that you previously computed in your Go code
and you can get rid of the []interface{} variable that you pass to Prepare & Exec, just do all the substitution logic in the go code.

Various unrelated things:

Don't write var int i = 3, write simply i := 3.
I'm not sure why Company and Service have to be exported, since you seem to only use them to build a query.
When doing successive += operations on a string, consider using a buffer instead, see this question. (But here, it's moot, since using a template is more idiomatic.)


Problem in calculating prime numbers in python I'm a noob in programming. I was asked to code a program that can calculate prime numbers. So i coded as provided below. But it prints all the Odd Numbers instead of Prime Numbers. I think the Value start is not being divided by all the integers in the range (2,Startnumber). It just prints all the odd numbers.

startnumber=int(raw_input("Enter a number: "))
start=2
while start<=startnumber:
    for divisor in range(2,startnumber):
        if start%divisor==0:
            break
        else:
            print start
            break
    start=start+1

There is no need to keep for loop in the while as while is doing the job of for,
assuming that your program tests whether the startnumber is prime or not.

using of break in else will terminate your loop once it checks that its not divisible by 2 [ the first divisor] . so break shouldn't be used there in else block as you want to test for numbers above 2.

We can while - else or for-else to solve your problem.
the code below shows the representation of your problem in while - else:

startnumber=int(raw_input("Enter a number: "))
start=2
while start<startnumber:

    if startnumber%start==0:
        print str(startnumber)+" is not a prime."
        break
    start=start+1
else:
    print str(startnumber)+" is a prime."

same code with for -else would be :

startnumber=int(raw_input("Enter a number: "))
start=2
for number in range(2,startnumber):

    if startnumber%start==0:
        print str(startnumber)+" is not a prime."
        break
    start=start+1
else:
    print str(startnumber)+" is a prime."


Drilldown navigation menu by replacing divs I made an attempt at a menu, that comprises of just replacing
s by showing and hiding. Kind of like a drill-down technique. I have the feeling that it is extremely long-winded. Can anyone offer a cleaner technique?

$(document).ready(function () {
    $('.first').show();
    $('.second, .all, .seventh, .sixth').hide();

    $('.first').click(function () {
        $('.first, .second').hide();
        $('.second').show();
        return false;
    });
});

$('.third').click(function () {
    $('.second').hide();
    $('.all, .seventh').show();
    return false;
});

$('.forth').click(function () {
    $('.second').hide();
    $('.sixth,.eighth').show();
    return false;
});

$('.fifth').click(function () {
    $('.fifth, .sixth').hide();
    $('.second').show();
    return false;
});

$('.nineth').click(function () {
    $('.seventh, .nineth').hide();
    $('.second').show();
    return false;
});

$('.eighth').click(function () {
    $('.sixth, .fifth').hide();
    $('.second').show();
    return false;
});
table {
    text-align:center;
    width:80%;
    cursor:pointer;
}
tr {
    width:50%;
    background:red;
}

Choose a Department

Technology

Vehicles

Headphones

Watches

Back

            Engine-Powered

            Human-Powered

Back

Top

By dropping in some generic classes and data attributes like so:

Choose a Department

Technology

Vehicles

menuContainer marks everywhere that's needs to be hidden or shown

menuItem marks everything links somewhere else in the menu

data-target is your link data

Now you can reduce your javascript to this:

$(document).ready(function () {
    $('.menuContainer').hide();
    $('.first').show();

    $('.menuItem').click(function () {
        var target = $(this).attr("data-target")
        if(target){
            $('.menuContainer').hide();
            $('.'+target).show();
        }
        return false;
    });
});


Change implementation from getting json from file to get it from API I used to get a JSON file with some configuration settings from the file system, using this class:

public class ConfigurationFileService : IConfigurationService
{
    private readonly IConfigurationManager _configurationManager;

    public ConfigurationFileService(IConfigurationManager configurationManager)
    {
        _configurationManager = configurationManager;
    }

    public Configuration GetConfiguration(int agentId)
    {
        var path = _configurationManager.GetAppSetting("pathToConfigurationFile");

        var Configuration = JObject.Parse(File.ReadAllText(string.Format(path, agentId)));
        return Configuration.ToObject<Configuration>();
    }
}

Now I will be getting that from an API (it will return exactly the same JSON), so I need to change the implementation of the IConfigurationService, I have done this so far.

public class ConfigurationApiClient : IConfigurationService
{
    private readonly HttpClient _client;

    public ConfigurationApiClient()
    {
        _client = new HttpClient();
        _client.BaseAddress = new Uri(""); //TODO Add base url
        _client.DefaultRequestHeaders.Accept.Clear();
        _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public Configuration GetConfiguration(int agentId)
    {
        return GetConfigurationAsync(agentId).Result;
    }

    private async Task<Configuration> GetConfigurationAsync(int agentId)
    {
        try
        {
            var response = await _client.GetAsync(""); // TODO add the url
            response.EnsureSuccessStatusCode();
            var Configuration = await response.Content.ReadAsAsync<Configuration>();
            return Configuration;
        }
        catch(HttpRequestException ex)
        {
            throw new ConfigurationException(string.Format("Exception when getting  settings for agent: {0}", agentId), ex);
        }
    }

The interface is very simple:

public interface IConfigurationService
{
    Configuration GetConfiguration(int agentId);
}

I am not sure about a couple of things:

The way I reuse the httpclient. I have seen that the recommendation is not to dispose it after each request, so I guess putting it in the constructor is a good option as the class itself will be injected.
The usage of one public method with the signature of the interface, that blocks the result of the asynchronous method (given that's the correct way of getting the result asynchronously).

public interface IAsyncConfigurationService : IConfigurationService{
    Task<Configuration> GetConfigurationAsync(int agentId);
}

public class ConfigurationApiClient : IAsyncConfigurationService
{
    //...
    public Configuration GetConfiguration(int agentId)
    {
        return GetConfigurationAsync(agentId).Result;
    }

    async Task<Configuration> IAsyncConfigurationService.GetConfigurationAsync(int agentId)
    {
        try
        {
            var response = await _client.GetAsync(""); // TODO add the url
            response.EnsureSuccessStatusCode();
            var Configuration = await response.Content.ReadAsAsync<Configuration>();
            return Configuration;
        }
        catch(HttpRequestException ex)
        {
            throw new ConfigurationException(string.Format("Exception when getting  settings for agent: {0}", agentId), ex);
        }
    }
}

With this, at least, you're able to try to do a cast to this interface
and call the assynchronous version.

If you are able to change the interface just a little bit and still have only the synchronous version, you could add an event, for when the configuration is ready:

public interface IConfigurationService
{
    void LoadConfiguration(int agentId);
    event EventHandler<ConfigurationArgs> ConfigurationLoad;
}

public class ConfigurationArgs{
    public Configuration Config{get;set;}
}

public class ConfigurationApiClient : IConfigurationService
{
    //...
    public event EventHandler<ConfigurationArgs> ConfigurationLoad;

    private void OnConfigurationLoaded(Configuration config){
        var handler = ConfigurationLoad;
        if(handler != null){
            handler(this, new ConfigurationArgs{
                Config = config
            });
        }
    }

    public void LoadConfiguration(int agentId)
    {
        GetConfigurationAsync(agentId).ContinueWith(e => {
            OnConfigurationLoaded(e.Result);
        });
    }

    async Task<Configuration> GetConfigurationAsync(int agentId)
    {
        try
        {
            var response = await _client.GetAsync(""); // TODO add the url
            response.EnsureSuccessStatusCode();
            var Configuration = await response.Content.ReadAsAsync<Configuration>();
            return Configuration;
        }
        catch(HttpRequestException ex)
        {
            throw new ConfigurationException(string.Format("Exception when getting  settings for agent: {0}", agentId), ex);
        }
    }
}

The semantic now is that you can call LoadConfiguration any number of times (because I guess it could change),
and have the result on the event handler.


Check if objects have coordinates Here's a function:

func checkIfObjectsHaveCoordinates() {
    PFQuery(className: "Products").findObjectsInBackgroundWithBlock {
        (objects: [PFObject]?, error: NSError?) -> in
        if error == nil && objects != nil {
            for object in objects! {
                if object["Latitude"] == nil || object["Longitude"] == nil {
                    self.convertObjectLocationToCoordinates(object)
                }
                object.pinInBackground()
            }
        } else {
            print(error)
        }
}

It checks if objects have a latitude or a longitude. If they don't, they will be passed to the convertObjectLocationToCoordinates function. Either way, I save them locally, and this is why I think my function should't have side effects. I feel like this code is hardcoded in some way:

if myObject["Latitude"] == nil || myObject["Longitude"] == nil || myObject["Latitude"] as! Float == 0 || myObject["Longitude"] as! Float == 0

Does this function look good to you?  Should I avoid side effects in my function?

What constitutes an effect and what constitutes a side-effect may be a matter of framing expectations.  The real problem, I think, is that the function name fails to convey what it actually does.  A more appropriate name might be something like pinProductsInBackgroundWithCoordinates(), because:

"check if objects have coordinates" only vaguely describes what this function is doing.  What if it does have coordinates — then what?  And if it doesn't, then what?
If the query succeeds, then wouldn't all of the objects end up having coordinates?
It looks like .pinInBackground() is going to be called for all of the objects.

If you take my naming suggestion, then pinning products is the effect, and ensuring that they all have coordinates is the side-effect.  That's much better than checkIfObjectsHaveCoordinates(), in which case both actions would be considered side-effects.

I'm not quite comfortable with the error handling.  I think that rearranging it would clarify both branches of the conditional.

if error != nil {
    print(error)
} else if objects != nil {
    for object in objects! {
        …
    }
}


Prompt user for some numbers, then print the max and min The function of this program is repeatedly prompting a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. Suppose all input is proper, so we do not need to check whether the input value is illegal or not.

largest = None
smallest = None

while True :
    num = raw_input("Enter a number: ")
    if num == "done" :
        break
    try :
        num = int(num)
    except :
        print "Invalid input"
        continue
    if largest is None :
        largest = num
    elif largest < num :
        largest = num
    if smallest is None :
        smallest = num
    elif num < smallest :
        smallest = num

print "Maximum is", largest
print "Minimum is", smallest

It's a shame python doesn't have a do..while loop, which would have been a better fit for the occasion.

You do plenty of branching. For every valid input, you check if the extreme values so far are still None. If you think about it, this will only be the case the first time a valid value is entered. It's not very plausible to keep on performing that check and it needlessly bloats the code.

To find maximum and minimum efficiently, use max() and min() and initialise your variables with appropriate values, that make the initial case blend in with the rest of the operation. +/-Infinity are good candidates for such values. Everything is bigger than -infinity, which makes it ideal as a starting value for the largest number. Here's what your code would look like with those changes applied:

largest = -float('inf')
smallest = float('inf')

while True :
    num = raw_input("Enter a number: ")
    if num == "done" :
        break
    try :
        num = int(num)
    except :
        print "Invalid input"
        continue

    largest = max(num, largest)
    smallest = min(num, smallest)

print "Maximum is", largest
print "Minimum is", smallest


Set / verify password using REST API I have limited experience with both making REST APIs and implementing security features, so I figured it'd be worth running this code through some other people's eyes before making it live.

My main questions are around the use of REST - e.g. are there better ways to implement my methods that return bools?

(Assume the "drivers" are keyed in the DB by Name)

public class Driver
{
    public string Name { get; set; }
    public string Pass { get; set; }
}

[HttpPost]
[RequireHttps]
[ActionName( "GetPasswordExists" )]
public HttpResponseMessage GetPasswordExists([FromBody] Driver driver)
{
    HttpResponseMessage response;
    try
    {
        bool passExists = false;
        // db operations
        response = Request.CreateResponse(HttpStatusCode.OK, passExists);
    }
    catch (Exception)
    {
        response = Request.CreateResponse(HttpStatusCode.BadRequest);
    }
    return response;
}

[HttpPost]
[RequireHttps]
[ActionName("SetPassword")]
public HttpResponseMessage SetPassword([FromBody] Driver driver)
{
    HttpResponseMessage response;
    try
    {
        string hash = System.Web.Helpers.Crypto.HashPassword(driver.Pass);
            // db operations
            response = Request.CreateResponse(HttpStatusCode.OK);
    }
    catch (Exception)
    {
        response = Request.CreateResponse(HttpStatusCode.BadRequest);
    }
    return response;
}

[HttpPost]
[RequireHttps]
[ActionName("VerifyPassword")]
public HttpResponseMessage VerifyPassword([FromBody] Driver driver)
{
    HttpResponseMessage response;
    try
    {
        bool valid = false;
        string hash = null;
        // db operations
        valid = System.Web.Helpers.Crypto.VerifyHashedPassword(hash, driver.Pass);
        response = Request.CreateResponse(HttpStatusCode.OK, valid);
    }
    catch (Exception)
    {
        response = Request.CreateResponse(HttpStatusCode.BadRequest);
    }
    return response;
}

Some quick remarks:

Keep your controllers lean and mean:

Move all of the processing (that you seem to have removed by using the comment // db stuff) to dedicated classes,
bind it all together using MediatR,
validate incoming data with FluentValidation.

There are plenty of examples that show you how to combine these two, e.g. this Stack Overflow question. Jimmy Bogard also has plenty of examples on his own blog, e.g. this post.

Microsoft also promotes this kind of structure:"Implement the Command and Command Handler patterns". (In this case in the context of CQRS, which is something that you also could look into.)
Don't needlessly abbreviate (why "pass" instead of "password"?).
Don't use exceptions to control your logic. An invalid password should IMHO not throw an exception, it's an expected result. Even worse it that you seem to be "eating" your exceptions and don't even log them.
WRT your app's logic, you might want to look at the logic in similar applications, e.g. "Simple API for Authentication, Registration and User Management". Also think about things like "how many times can a user try to log in and fail before his account gets locked?" in order to avoid hackers who'll try to access the system by going through large lists of often-used passwords.


Photo gallery layout I'm working on a photo website, the markup looks like this:

Photo 1

Photo 2

    ...

I've come up with some SCSS code that presents the images as expected (a justified strip of fixed height with a white line at the top and bottom. Here's the SCSS:

$background_color: #333;
$border_color: #EEE;

$thumbnail-height: 87px;

html, figure, img, div {
    margin: 0;
    padding: 0;
}
body {
    font-size: 100%;
    line-height: 1;
    margin: 1em;
    background: $background_color;
}
.gallery {
    text-align: justify;
    margin: 0 -4px -1px 0;
    padding: 1px 0 0 0;
    overflow: hidden;
    figure {
        position: relative;
        border-top: 1px solid $border_color;
        border-bottom: 1px solid $border_color;
        height: $thumbnail-height;
        display: inline-block;
        margin: -1px 4px 0 0;
        vertical-align: top;
        &:before {
            content: "";
            position: absolute;
            top: -1px;
            bottom: -1px;
            left: -9999px;
            width: 9999px;
            z-index: -1;
            border-top: 1px solid $border_color;
            border-bottom: 1px solid $border_color;
        }
        img {
            height: 100%;
            display: block;
        }
        figcaption {
            display: none;
        }
    }
}

There is a fiddle demo here.

This gives an acceptable layout on most modern browsers, but I'm not very proud of this code:

It's too complicated
It uses negative margins, that I view as a hack
It uses large :before pseudo-element that are trimmed by overflow: hidden, and that also needs a negative z-index

I would be grateful for any tips that would help improve that code.

First, I will start with the good:

Photo 1

It is excellent that you use the HTML5 tag figure instead of a plain old div.

You may just have removed this for brevity (many people do), but when you write HTML, you should build your page like this:

<!doctype html>

    <title>Your Title Here</title>

Photo 1

Photo 2

You can validate your HTML at the W3C validator (it validates once you provide the framework).

It does look clumsy the way you write out each figure.  If I were you, I would probably load the images and figcaptions in a separate file (maybe a JSON file?) and use JS to add them to the page.  This way, you just have to enter the new data in this file, and the webpage will load them right in the next it is loaded.


An implementation of maximum subarray finding algorithm in STL style I am reading Stroustrup now and I was very impressed with how flexible the STL library is thanks to iterators and generic programming. Along the way, I am also reading Cormen's book and decided to try to implement an algorithm for searching for the maximum subarray in the style of STL. I wrote in C++11. I would be very grateful to hear your opinion about this code.

template<typename For>
// Requires Forward_iterator<For>()
auto find_maximum_subarray (For begin, For end)
{
    typename std::iterator_traits<For>::value_type max_sum_subarr = *begin;
    typename std::iterator_traits<For>::value_type max_sum        = *begin;

    For subarr_begin = begin;
    For left = begin;
    For right = ++begin;

    for (; begin != end; ++begin)
    {
        if (max_sum_subarr > 0)
            max_sum_subarr += *begin;
        else
        {
            max_sum_subarr = *begin;
            subarr_begin = begin;
        }

        if (max_sum_subarr > max_sum)
        {
            left = subarr_begin;
            right = begin;
            ++right;
            max_sum = max_sum_subarr;
        }
    }
    return make_tuple (left, right, max_sum);
}

Do not rely on the client code to #include necessary headers. The client has no idea which headers your file requires. Spell them out explicity:

#include <iterator>
#include <tuple>

Are you sure you are using c++11? I am getting

error: 'auto' return without trailing return type; deduced return types
are a C++14 extension

In general, naked auto returns in an interface is a dubious idea. Again, think of the client. The client should not analyze your template to deduce what it actually returns. It is OK to have them in the helper functions not exposed to the client.
It took me a while to figure out why your code works correctly. The side effect of ++ in

For right = ++begin;

is very easy to miss.


Beginner code for a Rock, Paper, Scissors game in Python I am a beginner in Python and I wanted to see if I could get some feedback on my simple Rock, Paper, Scissors game. I do have previous experience in programming, as I started learning a few years ago but got happy feet and moved through the "basics" for a lot of different languages.

With that said, I plan on sticking with Python for a while until I have programmed a game that I find suitable (I am aiming to start small and end up maybe at a Mario clone).

My biggest issue with this program is that I find it very long-winded, and I am sure there is a way to shorten the code tremendously, I just do not know that solution yet. As well, I do plan on adding something to validate user input
but all I know so far are try and except clauses, which I am not sure if they could work.

# a simple game of rock, paper, scissors
import random

opponent = ["Rock", "Paper", "Scissors"]

player1Score = 0

opponentScore = 0

while (True):

    if (player1Score >=3):
        print("Player 1 Wins!!!!!!")
        print("Type 'new game' to play again. (Or type 'exit' to exit.)")
        newGame = input()
        if newGame == "new game":
            player1Score = 0
            opponentScore = 0
            continue
        if newGame == "exit":
            break

    if (opponentScore >=3):
        print("Your opponent Wins!!!!")
        print("Type 'new game' to play again. (Or type 'exit' to exit.)")
        newGame = input()
        if newGame == "new game":
            player1Score = 0
            opponentScore = 0
            continue
        if newGame == "exit":
            break

    print ("Player 1's turn." + " Please type 'Rock', 'Paper', or 'Scissors' to choose your move.")

    opponentMove = random.choice(opponent)
    player1Move = input()

    if player1Move == opponentMove:
        #print (opponentMove) // for debugging
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        print ("Tie!" + " Please go again.")
        continue

    if (player1Move == "Rock") and (opponentMove == "Paper"): # rock loses to paper
        opponentScore = opponentScore + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Paper") and (opponentMove == "Rock"): # paper beats rock
        player1Score = player1Score + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Paper") and (opponentMove == "Scissors"): # paper loses to scissors
        opponentScore = opponentScore + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Scissors") and (opponentMove == "Paper"): # scissors beats paper
        player1Score = player1Score + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Scissors") and (opponentMove == "Rock"): # scissors loses to rock
        opponentScore = opponentScore + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

    if (player1Move == "Rock") and (opponentMove == "Scissors"): # rock beats scissors
        player1Score = player1Score + 1
        print("Your opponent played: " + str(opponentMove) + ".")
        print("Your score: " + str(int(player1Score)))
        print("Your opponent's score: " + str(int(opponentScore)))
        continue

The code repetition could be cleaned up quickly by replacing your seven if blocks with something like:

print("Your opponent played: " + str(opponentMove) + ".")

if player1Move == opponentMove:
    print ("Tie!" + " Please go again.")
elif (player1Move == "Rock") and (opponentMove == "Paper"): # rock loses to paper
    opponentScore = opponentScore + 1
elif (player1Move == "Paper") and (opponentMove == "Rock"): # paper beats rock
    player1Score = player1Score + 1
elif (player1Move == "Paper") and (opponentMove == "Scissors"): # paper loses to scissors
    opponentScore = opponentScore + 1
elif (player1Move == "Scissors") and (opponentMove == "Paper"): # scissors beats paper
    player1Score = player1Score + 1
elif (player1Move == "Scissors") and (opponentMove == "Rock"): # scissors loses to rock
    opponentScore = opponentScore + 1
elif (player1Move == "Rock") and (opponentMove == "Scissors"): # rock beats scissors
    player1Score = player1Score + 1
else:
    print ("Invalid choice")

print("Your score: " + str(int(player1Score)))
print("Your opponent's score: " + str(int(opponentScore)))

This eliminates all of the continue statements.  Keeping with the same approach you have started, perhaps splitting into cases where player1 wins vs opponent wins is the next improvement:

if player1Move == opponentMove:
    print ("Tie!" + " Please go again.")
elif ((player1Move == "Rock") and (opponentMove == "Paper")) or
     ((player1Move == "Paper") and (opponentMove == "Scissors")) or
     ((player1Move == "Scissors") and (opponentMove == "Paper")):
    player1Score = player1Score + 1
elif ((player1Move == "Paper") and (opponentMove == "Scissors")) or
     ((player1Move == "Scissors") and (opponentMove == "Rock")) or
     ((player1Move == "Rock") and (opponentMove == "Paper")):
    opponentScore = opponentScore + 1
else:
    print ("Invalid choice")


Creating input when checking/clicking radio button I'm new to jQuery and played a bit with what can I do with radio button. I want to create ONLY one input type when I click the Notice radio button. I already using many way to achieve this, but this is the only way I can do this, you can see the following code.

HTML

<input type="radio" name="radio1" value="Immediate" /> Immediate

<input type="radio" name="radio1" id="others" value="Notice" /> Notice me in...

jQuery

$(function(){
    $("#others").click(function(){
        while($("#others").val()=="Notice")
        {
            var newElement = $(document.createElement('input')).attr({name:"noticeweeks", id:"noticeweeks"});
            newElement.appendTo("#inputplace");

            $("#others").val("Notice me in...");
        }
    });
});

With that jQuery, I changed the value of the radio button into "Notice me in...", so the while function will stop creating a new element since the value has been changed.

Are there any others way to achieve the same result?

There's no need to use a while loop, as you only want to add the element once, after which the condition won't hold anymore. That's what if is for.
There's a shorter way to create a new element

So I get to:

$(function() {
    $("#others").click(function() {
         if ($("#others").val() == "Notice") {
            var newElement = $('<input>')).attr({name:"noticeweeks", id:"noticeweeks"});
            newElement.appendTo("#inputplace");
            $("#others").val("Notice me in...");
        }
    });
});


Generic wrapper with variable number of arguments I had to write a generic wrapper that enables me to pass variable number of arguments for execution of some methods and repeat it up to a few times when it fails because of network connection problems.

What I came up is this class and a helper method. Well I can't say it's perfect - it is sufficient for my need, but is there anything that I could have done better ?

The main idea is behind command class

public abstract class Command<R, A1, A2, A3> {

    protected final SomeService someService;
    private Bundle<A1, A2, A3> bundle;

    public Command(SomeService someService) {
        this.someService = someService;
    }

    public void setBundle(Bundle<A1, A2, A3> bundle) {
        this.bundle = bundle;
    }

    public Bundle<A1, A2, A3> getBundle() {
        return bundle;
    }

    public abstract R execute(Bundle<A1, A2, A3> bundle) throws Exception;
}

I have to implement an execute method, which holds some logic which will be performed during runtime of the application. But, it may take up to three arguments and return any type.

An auxiliary class that helps to pass arguments to the Command class is the Bundle class.

public class Bundle<A1, A2, A3> {
    A1 arg1;
    A2 arg2;
    A3 arg3;

    public Bundle(A1 arg1, A2 arg2, A3 arg3) {
        this.arg1 = arg1;
        this.arg2 = arg2;
        this.arg3 = arg3;
    }

    public A1 getArg1() {
        return arg1;
    }

    public A2 getArg2() {
        return arg2;
    }

    public A3 getArg3() {
        return arg3;
    }

    public static <T1> Bundle<T1, Void, Void> bundleOf(T1 arg1) {
        return new Bundle<>(arg1, null, null);
    }

    public static <T1, T2> Bundle<T1, T2, Void> bundleOf(T1 arg1, T2 arg2) {
        return new Bundle<>(arg1, arg2, null);
    }

    public static <T1, T2, T3> Bundle<T1, T2, T3> bundleOf(T1 arg1, T2 arg2, T3 arg3) {
        return new Bundle<>(arg1, arg2, arg3);
    }
}

It creates a generic parameter container that is passed to the Commands
execute method.

Finally, the method that we currently need, must repeat some operation up to three times (because of often disconnects), so I came up with this methods based on some SO questions:

private <R, A1, A2, A3> R executeCommand(Command<R, A1, A2, A3> command) {
    R result = null;
    for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
        try {
            return command.execute(command.getBundle());
        } catch (Exception e) {
            logger.error("Exception during performing operation, retrying for the " + attempt + " time", e);
            sleepForNMinutes(attempt);
            loginToApp();
        }
    }
    return result;
}

Instantation of the Command class:

Command<Person, String, Void, Void> retrievePersonByNetwork;

retrievePersonByNetwork= new Command<Person, String, Void, Void>(someService) {
    public Person execute(Bundle<String, Void, Void> bundle) throws Exception {
        return this.someService.retrievePerson(bundle.getArg1());
    }
};

Execution:

Bundle<String, Void, Void> bundle = Bundle.bundleOf("userName");
retrievePersonByNetwork.setBundle(bundle);
Person person = executeCommand(retrievePersonByNetwork);

private <R, A1, A2, A3> R executeCommand(Command<R, A1, A2, A3> command) {
    R result = null;
    for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
        try {
            return command.execute(command.getBundle());
        } catch (Exception e) {
            logger.error("Exception during performing operation, retrying for the " + attempt + " time", e);
            sleepForNMinutes(attempt);
            loginToApp();
        }
    }
    return result;
}

You never set result outside the initial declaration.   So you could just get rid of the declaration and return null at the end.

You retry on any exception, but the only retry condition that you mention is a disconnect.  Why not create a DisconnectException and only catch that?  The current code will retry things like command being null or a divide by zero error, even though those will never succeed.

You sleep and log into the app after the final attempt.  Why?  What happens if the log in action fails?  What happens if the exception isn't caused by something that breaks the login session?

You sleep for 0 minutes after the first attempt.

You log that you are retrying for the 0, 1, or 2 time.  That's incorrect.  Particularly on the last time, when you don't retry.  The grammar also doesn't quite work.

private <R, A1, A2, A3> R executeCommand(Command<R, A1, A2, A3> command) {
    int attempt = 0;
    while (true) {
        try {
            return command.execute(command.getBundle());
        } catch (DisconnectException e) {
            logger.error("Exception while performing operation, attempt " + ++attempt, e);
        }

        if (attempt >= MAX_ATTEMPTS) {
            return null;
        }

        sleepForNMinutes(attempt);
        loginToApp();
    }
}

This version does give up using a for loop to track the attempts.  This allows us to move the end condition to the middle of the loop rather than the beginning.  This may or may not be what you want.  But if you do, this is one way you could do it.


Simple Report Data Class I'm trying to write a class to handle the collecting and calculating of some data. My intention is to have the controller instantiate the Report object, and a very simple view display it. I figured this would keep the controller thin and keep logic out of the views.

class Report
  def initialize(year_term_ids = [])
    @year_term_ids = year_term_ids
  end

  def gpas
    {}.tap do |gpas|
      %i(average minimum maximum).each do |method|
        gpas[method] = student_terms.send(method, :term_gpa).to_f.round(2)
      end
    end
  end

  def students
    student_statuses.merge(
      count: student_terms.count,
      dismissed: student_terms.dismissed,
      on_probation: student_terms.on_probation
    )
  end

  def year_terms
    @year_terms ||= load_year_terms
  end

  def student_terms
    @student_terms ||= load_student_terms
  end

  private

  def load_student_terms
    StudentTerm.where(year_term: year_terms)
      .includes(:student)
  end

  def load_year_terms
    year_terms = YearTerm.includes(student_year_terms: [ :student ])

    if @year_term_ids.empty?
      year_terms
    else
      year_terms.where(id: @year_term_ids)
    end
  end

  def student_statuses
    symbolize_hash(student_terms.map(&:student).group_by(&:status))
  end

  def symbolize_hash(hash)
    hash.keys.each do |k|
      hash[k.underscore.to_sym] = hash.delete(k) if k.is_a?(String)
    end

    hash
  end
end

The Report#gpas method is utilizing the tap method. This feels like too much magic for something so simple (Related: Should I Tap That Hash). It took me a bit to unravel what that method does, which is essentially:

def gpas
  {
    average: student_terms.average :term_gpa,
    minimum: student_terms.minimum :term_gpa,
    maximum: student_terms.maximum :term_gpa
  }
end

This looks much cleaner and immediately easy to understand -- and it's the same number of lines of code.

I haven't dealt with Ruby much in a few years, but prior to Ruby 2.2 the String#to_sym method was a source of memory leaks, because symbol objects never get garbage collected, and the to_sym method always returned a new Symbol object. The symbolize_hash method could be just such a memory leak. I'm actually wondering why you aren't using classes here instead of a Hash. You are creating these Hashes and then manipulating their data. This feels like you need some additional classes to push this behavior into.

There's also no benefit to checking for @year_term_ids.empty? before adding the "where" condition in load_year_terms. Just a simple:

def load_year_terms
  YearTerm.includes(student_year_terms: [ :student ]).where(id: @year_term_ids)
end

will suffice. In fact this feels like it should be a static method on the YearTerm class itself:

class YearTerm < ActiveRecord::Base
  def self.including_student_for(year_term_ids)
    YearTerm.includes(student_year_terms: [ :student ]).where(id: @year_term_ids)
  end
end

Then just call YearTerm.including_student_for(@year_term_ids) in your Report class.


Convert an image to 8-bit color I have a function that will take an image and then return that image in 8-bit color. Almost all of the code was taken from MSDN.

The code is quite short compared to all of the other methods I've seen for converting an image to 8-bit color. I'm just curious as to if this is the most efficient method?

private static Image ImageTo8bpp(Image image)
{
    var bitmap = new Bitmap(image);
    var imageCodecInfo = GetEncoderInfo("image/tiff");
    var encoder = Encoder.ColorDepth;
    var encoderParameters = new EncoderParameters(1);
    var encoderParameter = new EncoderParameter(encoder, 8L);
    encoderParameters.Param[0] = encoderParameter;
    var memoryStream = new MemoryStream();
    bitmap.Save(memoryStream, imageCodecInfo, encoderParameters);
    return Image.FromStream(memoryStream);
}

private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
    var imageEncoders = ImageCodecInfo.GetImageEncoders();
    return imageEncoders.FirstOrDefault(t => t.MimeType == mimeType);
}

The MSDN example is saving to a physical file, so the method incurs I/O - yours streams it to a MemoryStream, so it definitely feels more efficient.

I'm a bit (pun not intended) worried about the undisposed Bitmap and MemoryStream objects though, both of which implement the IDisposable interface, and I think some of the intermediate variables could be skipped - would this work?

using (var bitmap = new Bitmap(image))
using (var stream = new MemoryStream())
{
    var parameters = new EncoderParameters(1);
    parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 8L);

    var info = GetEncoderInfo("image/tiff");
    bitmap.Save(stream, info, parameters);

    return Image.FromStream(stream);
}

I'd be almost tempted to inline GetEncoderInfo too, unless it's reused elsewhere.

That would take this line:

    var info = GetEncoderInfo("image/tiff");

And turn it into...

    var info = ImageCodecInfo.GetImageEncoders()
                             .FirstOrDefault(info => info.MimeType == "image/tiff");

If the method is used in a number of places (hmm, well it's private so I doubt it), it could be interesting to turn the method (which is already static anyway) into an extension method:

public static Image To8bit(this Image image)


How can I make this jQuery code better so variables aren't repeated and the code is more efficient? It adds and removes classes from animate.css when mouse events occur. Though I hate how I had to write the same thing twice in both events.

var item = $('.work-item');

item.mouseenter(function(event) {
  var $this = $(this);
  var cover = $(this).find('.item-cover'),
      coverTitle = cover.find('.title');
      coverShortDescription = cover.find('.short-description'),
      coverSep = cover.find('.seperator');
  cover.removeClass('fadeOut').addClass('animated fadeIn');
  coverTitle.removeClass('fadeOutDown').addClass('animated fadeInUp');
  coverShortDescription.removeClass('fadeOutUp').addClass('animated fadeInDown');
  coverSep.removeClass('fadeOut').addClass('animated fadeInUp');
}).mouseleave(function(event) {
  var $this = $(this);
  var cover = $(this).find('.item-cover'),
      coverTitle = cover.find('.title');
      coverShortDescription = cover.find('.short-description'),
      coverSep = cover.find('.seperator');
    cover.removeClass('fadeIn').addClass('fadeOut');
    coverTitle.removeClass('fadeInUp').addClass('animated fadeOutDown');
    coverShortDescription.removeClass('fadeInDown').addClass('animated fadeOutUp');
    coverSep.removeClass('fadeInUp').addClass('fadeOut');
});

Any way to make this more efficient?

Have a look at the .hover() event and .toggleClass().

With those, you could do:

item.hover(function (event) {
  var hovering = event.type === 'mouseenter',
      cover = $(this).find('.item-cover'),
      title = cover.find('.title');
      description = cover.find('.short-description'),
      separator = cover.find('.seperator');

  // skip this by simply adding "animated" in the HTML to begin with
  $().add(cover, title, description, separator).addClass('animated');

  // toggle with a boolean argument to force one state or another
  cover.toggleClass('fadeOut', !hovering).toggleClass('fadeIn', hovering);
  title.toggleClass('fadeOutDown', !hovering).toggleClass('fadeInUp', hovering);
  description.toggleClass('fadeOutUp', !hovering).toggleClass('fadeInDown', hovering);
  separator.toggleClass('fadeOut', !hovering).toggleClass('fadeInUp', hovering);
});

But it might be nice to be more "declarative" by adding a little helper function:

item.hover(function (event) {
  var hovering = event.type === 'mouseenter',
      cover = $(this).find('.item-cover'),
      title = cover.find('.title');
      description = cover.find('.short-description'),
      separator = cover.find('.seperator');

  // toggle the enterClass if mouse is hovering, otherwise toggle leaveClass
  function setClass(selection, enterClass, leaveClass) {
    selection.toggleClass(enterClass, hovering).toggleClass(leaveClass, !hovering);
  }

  // skip this by simply adding "animated" in the HTML to begin with
  $().add(cover, title, description, separator).addClass('animated');

  setClass(cover, 'fadeIn', 'fadeOut');
  setClass(title, 'fadeInUp', 'fadeOutDown');
  setClass(description, 'fadeInDown', 'fadeOutUp');
  setClass(separator, 'fadeInUp', 'fadeOut');
});

By the way, it's "separator" with two a's, not two e's.


Plotting text from a dictionary with Matplotlib I have the following dictionary:

top = {'aaaa': {'☹': 7, '': 12, '': 6},
      'bbbb': {'': 2, '': 2, '': 2},
      'cccc': {'☹': 5, '': 3, '': 3},
      'dddd': {'': 8, '': 7, '': 3},
      'eeee': {'☺': 3, '': 5, '': 4},
      'ffff': {'☹': 5, '': 5, '': 5}}

Each 'aaaa' or 'bbbb' is the user's name, and his values is the emoji he is using the most.
I want to plot a decent looking graph to visualize.
After a few tries, this is my best work:

with the code:

import matplotlib.pyplot as plt

def top_emoji(top):
    fig, ax = plt.subplots(figsize=(8, 5))
    y = 9
    level = 0
    start = 9
    for name, dictionary in top.items():
        ax.text(start, y - level, name, fontsize=20)
        x = 3
        for emoj in dictionary.keys():
            ax.text(start - x, y - level, emoj, fontname='Segoe UI Emoji', fontsize=20)
            x += 1
        level += 1

    ax.axis([0, 10, 0, 10])
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.axis('off')
    plt.show()

Which is terrible in my opinion. Any recommendations for improvements will be much appreciated.

Your code might be a bit clearer without level & start, preferring to manipulate just x & y.

You might write a sorting helper function, and change the emoj loop to this:

    for x, emoj in enumerate(emoj_by_score(dictionary)):

You have some hard coded values that you could derive by inspecting the top input argument. On the whole, it doesn't seem so terrible. It is reasonably clear.


Pretty handling FileNotFoundException I have got a piece of code that initialize Scanner in two possible ways:

no argument constructor creates Scanner that uses stdIO (System.in) as source
contructor with String, which creates Scanner, that uses file as source, where String is a path to file

It looks like this:

public class InputMethod implements IInputMethod {

private final Scanner fileReader;
private final Scanner userInput = new Scanner(System.in);

public InputMethod(String[] args) throws FileNotFoundException {
    if (args.length == 1)
        fileReader = setFileAsSource(args[0]);
    else
        fileReader = setStdIOAsSource();
}

private Scanner setFileAsSource(String filename) throws FileNotFoundException {
        return new Scanner(new File(filename));
}

private Scanner setStdIOAsSource() {
    return new Scanner(System.in);
}
}

In main:

public static void main(String[] args) throws FileNotFoundException {
    IInputMethod input= new InputMethod(args);

    while (!input.getUserInput().equals("Exit")) {
        // awesome stuff
    }
    input.closeInput();
}

It works great, but it does not look pretty when it comes to exception handling. My dream would be creating a method, in which I will handle possible File-related problems and next one, that will do the job, just like good old Uncle Bob said.

Can anyone take a look at this and maybe suggest some minor changes, to make it clean and friendly?

Your design is slightly off, String args[] works great for terminal programs, but for passing arguments around it's really not efficient. There's no compile time checking to see if you're passing around things that make sense.

Look up Strategy Pattern; You want several independent classes each implementing the interface.

To handle the exception, split your code into two halves:

The first half prepares,

The second half executes.

Additionally, you should split up the responsibility of input source and user input. Right now you'd have to re-implement userInput for each InputMethod, which is unwanted.

By splitting up your code to each case, you'll have 1 specific case where you're still in your calling code (you haven't instantiated an InputMethod yet), but you know that you're going to read from a file. You can handle your exception there.

Your code would be structured like so:

public static void main(String[] args) throws FileNotFoundException {
    IInputMethod input = null;
    if(args.length == 1){
        input = makeFileInputMethod(args);
    } else {
        input = makeStandardInputMethod();
    }

    //make user input object

    while (!input.getUserInput().equals("Exit")) {
        // awesome stuff
    }
    input.closeInput();
}

In the makeFileInputMethod you could handle the exception. Then, in main, you could say "well, if input is still null, we didn't instantiate properly and we ought to shut down".


Comparing two partition functions in Python I have written a partition function in Python (my_partition_adv).  I have written this one after reading a similar function from a website.  The version of the partition function from the website is also given below (parititon_inplace).

As I am a beginner in Python, I want to know the following things:

My version looks certainly more readable than the  partition_in_place_with_additional_memory.
Are there any drawbacks for my version in terms of complexity that I am missing?
Are there any other drawbacks for my_partition_adv over partition_inplace?

def partition_inplace(A, start, stop, pivot_index):
    items_less_than = []
    items_greater_than_or_equal = []

    read_index = start
    while read_index <= stop:
        item = A[read_index]
        if item < pivot_value:
            items_less_than.append( item )
        else:
            items_greater_than_or_equal.append( item )
        read_index += 1

    write_index = start

    for item in items_less_than:
        A[write_index] = item
        write_index += 1

    for item in items_greater_than_or_equal:
        A[write_index] = item
        write_index += 1

    return len(items_less_than)

def my_partition_adv(A,p_val):
        less_than = []
        greater_than_or_equal = []

        for index, item in enumerate(A):
            if item < p_val:
                less_than.append(item)
            else:
                greater_than_or_equal.append(item)

        for index,item in enumerate(less_than):
            A[index] = less_than[index]

        for index,item in enumerate(greater_than_or_equal):
            A[len(less_than) + index] = greater_than_or_equal[index]

        return len(less_than)

These two functions are doing somewhat different tasks. The first one partitions a subrange of a list; the second one may only partition an entire list.

The use of enumerate is not justified in the first loop (index is not being used at all), and is quite suspicious in the second and third. Slices would achieve the same result more pythonically:

partition_point = len(less_than)
A[:partition_point] = less_than
A[partition_point:] = greater_than
return partition_point


DFS on a binary tree: marking nodes as visited I wanted to write depth first search reversal iteratively in Java. Can someone review my code? I'm not that much interested in naming of the variables, but in the structure of the code, i.e. I don't need to mark the nodes as visited when I traverse binary tree, right?

public static void dfs(TreeNode root){
        if(root == null)    return;
        Stack<TreeNode> res = new Stack<TreeNode>();
        res.push(root);
        while(!res.isEmpty()){
            TreeNode top = res.pop();
            System.out.print(top.val + " ");
            if(top.right != null)
                res.push(top.right);
            if(top.left!= null)
                res.push(top.left);
        }
    }

Recursive version:

public static void dfs(TreeNode root){
        if(root == null)    return;
        System.out.print(root.val + " ");
        dfs(root.left);
        dfs(root.right);
    }

I don't need to mark the nodes as visited, when I traverse binary tree, right?

Well, is your code working even though you are not doing this right now? Then yes, you don't need it.

See also this question for a theoretical discussion about marking nodes as visited, and this question for a practical reason to mark nodes (it's not needed for a simple search, but it is needed when looking for paths).

Naming

Even though you are not that interested, it is important. It makes your code more readable, which helps reviewers review your code. If you don't really care about your code, why should we?

In this case, it's not really that bad (there aren't all that many variables), but I wouldn't even know what res was short for (rest? Like the rest of the nodes?); even nodes would be better.

Formatting

Just like naming, correct formatting makes code easier to read and thus easier to maintain and review. Again, your code is very short, so it's not all that bad, but your spacing is off and you should use curly braces even for one-line statements.

Printing

Your code isn't really testable or practical as it doesn't return a result, but just prints something. You should return true (or the node) or false instead if your using it as a search, and return a string/list/etc if your using it to traverse the tree and collect the content of the nodes.


Comparing two arrrays I have two arrays:

first one is ip addresses from billing for blocking
second is ip addresses from firewall - already blocked

My task is, compare it, and if ip address new in billing list - block it (run a command) if ip address not in billing list  unblock it.

Current solutions is:

#billing->router
foreach $ip (@ipfw_ip) {
    if ( grep $_ eq $ip, @bill_ip ) {
    } else {
        `/sbin/ipfw table 11 add $ip`;
        print "$ip blocked\n";
    }
}

#router->billing
foreach $ip (@bill_ip) {
    if ( grep $_ eq $ip, @ipfw_ip ) {
    } else {
        `/sbin/ipfw table 11 delete $ip`;
        print "$ip unblocked\n";
    }
}

I hate 'grep' in the loops, and looking for better solution. Any advice?

UPD:
difference function from Set::Functional helps me.

for(difference (\@ipfw_ip, \@bill_ip)) {
     ..._;
}
sub difference(@) {
    my $first = shift;

    return unless $first && @$first;

    my %set;

    undef @set{@$first};

    do { delete @set{@$_} if @$_ } for @_;

    return keys %set;
}

You can use Set::Functional to make the code very short:

use Set::Functional 'difference';
for(difference [@ipfw_ip], [@bill_ip]) {
    `/sbin/ipfw table 11 add $ip`;
    print "$ip blocked\n";
}

Another advantage of the approach above is that you don't have to worry about duplicate entries in the two arrays.


Efficiently calculate the value of an arithmetic sequence I need to calculate the value for the following function:
$$f(n) = -1 + 2 - 3 + ... + -1^n$$
The time limit to calculate a given value of \$n\$ is less than 1 second. My approach does not meet that requirement at large sizes, for example \$f(1000000000)\$.
My code:
program A486;
uses wincrt, sysutils;

var
    n: LongInt;

function f(n : LongInt): LongInt;
var
    i : LongInt;
    //Result : LongInt;
begin
    Result:= 0;
    for i:= 1 to n do
        if i mod 2 = 0 then
            Result += i
        else
            Result -= i;
    //f:= Result;
end;

begin
    readln(n);
    writeln(f(n));
    //readkey()
end.

Is there a better way I can do this?

Seems trivial. Pair them, each pair is worth -1.
f(1000) =  1 - 2  +  3 - 4  + ... +  999 - 1000
        = (1 - 2) + (3 - 4) + ... + (999 - 1000)
        =   -1        -1    + ... +     -1
        = -500

Odd n left as exercise for the reader.
(I wrote this when the question title still said "1 − 2 + 3 − 4 + · · ·", can't be bothered to switch all signs now.)


Function to sort items with an array of keys I'm working on a function to sort two elements using several properties. I want to know if the function is well structured.

function comparePropsOfAWithB(a, b, props) {
    var prop  = props[0];
    var propA = a[prop];
    var propB = b[prop];

    if (propA === propB) {
        var array = props;
        array.shift();
        return props.length ? comparePropsOfAWithB(a, b, props) : false
    } else if (propA < propB ) {
        return true
    } else {
        return false
    }
}

This function is meant to be used alongside the sort method like this:

array.sort(function(a,b) { return comparePropsOfAWithB(a,b,["a","b","c"]) })

The intent of the function is to compare two objects using several values to determine if they are different. In the example, the key "a" will be tested, and if it fails, "b" will be tested until the last element of the array is reached.

That's not how the comparison function for Array.sort() works at all: it should return negative, zero, or positive.

Eating up all or part of the props argument (due to your array.shift() call) is bad practice.

The usage is cumbersome:

array.sort(function(a,b) { return comparePropsOfAWithB(a,b,["a","b","c"]) })

Wouldn't it be nicer to write a propertyComparator(…) function that returns a function?

array.sort(propertyComparator('a', 'b', 'c'))

Something like this:

function propertyComparator() {
    var props = arguments;
    return function(a, b) {
        for (var i = 0; i < props.length; i++) {
            var aProp = a[props[i]];
            var bProp = b[props[i]];
            if (aProp < bProp) return -1;
            if (aProp > bProp) return +1;
        }
        return 0;
    };
}


Find intersection of two arrays without duplicates A = [9, 1, 4, 2, 5] k unique integers
  B = [3, 1, 8, 7, 6, 5] n unique integers
  Intersection => [1, 5]

Find an algorithm that uses \$O(1)\$ space (the space used by the return variable is not considered) and runs as fast as possible to find the intersection of the arrays.

private static List<Integer> getIntersectionO1Space(List<Integer> a, List<Integer> b)
{

    List<Integer> intersection = new ArrayList<Integer>();
    mergeSort(a); //Time O(k log k), space O(1)

    for (Integer n : b) //O(n log k)
    {
        int r = Collections.binarySearch(a, n); //O(log k)
        if (r > -1)
            intersection.add(n);
    }
    return intersection;
}

So the total time complexity is \$O(\max(k,n) \log k)\$.

But my solution doesn't utilize the property that "no duplicate elements in the array". I wonder whether there is an algorithm that uses the property and runs faster.

Your solution doesn't have explicit instructions to use the property that no duplicate elements in the array, but it naturally benefits from it.
The binary search is slightly faster because it doesn't need to visit duplicate elements unnecessarily.
The iteration is faster too for the same reason.
Actually if there were duplicates it would be a lot tougher problem to solve.

The only way I see to make it faster won't be possible in \$O(1)\$ space:
instead of sorting the first list, you could put it in a hash set.
That way the binary search becomes a hash lookup, which is much faster,
but at the expense of doubling the memory usage of one of the lists.

When you have two lists of very different sizes,
I'm wondering if it can be said that making the shortest to be the first or the second will yield better performance in general.


Simple self-made encrypter The following code:

import random

def keygen():
    l = list('abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" ')
    random.shuffle(l)
    return l

def encrypt(x):
    key = keygen() #or a static key for consistency
    y = list('abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" ')
    z = dict(zip(y, key))
    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))
    print('key: '+ ''.join(key))
    print('content: '+ ''.join(l))

def decrypt(key, x):
    key = list(key)
    y = list('abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" ')
    z = dict(zip(key, y))
    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))
    print(''.join(l))

is just a simple self made encrypter that I made for fun, and works like so:

>>> encrypt('hello world how are you')
key: ^lps1|dv)({t&hk#w;=@!6bjrx$4 \[m~"q*i+:-a73?u/5zf%gc9}yn"8_oe]`2
content: v1ttk2bk;ts2vkb2^;12rk!
>>> decrypt('^lps1|dv)({t&hk#w;=@!6bjrx$4 \[m~"q*i+:-a73?u/5zf%gc9}yn"8_oe]`2', 'v1ttk2bk;ts2vkb2^;12rk!')
hello world how are you
>>>

This works pretty well, but I did see one time where there was a single letter that was misplaced. This could have just been due to me not copy/pasting the key in right for decoding, but I am not so sure. Basically does this code look sound? And are there any other methods of doing something like this in a more elegant way?

You should get out of the habit of printing results instead of returning them; if you return the function is reusable. Remember that you can return multiple values with:

    return ''.join(key), ''.join(l)

I would personally suggest returning a string directly from keygen.

You don't need to convert y to a list, and probably should name it better (eg. ascii). It would be better as a global constant.

encrypt and decrypt can be unified by making key optional and reversing the arguments when decrypting relative to encrypting; it's symmetric after all.

import random

ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key=None, backwards=False):
    if key is None:
        key = keygen()

    z = dict(zip(key, ASCII) if backwards else zip(ASCII, key))

    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))

    return key, ''.join(l)

Since keygen is so easy to call as

encrypt(x, keygen())

I wouldn't make key have a default. This gives the simpler:

import random

ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key, backwards=False):
    z = dict(zip(key, ASCII) if backwards else zip(ASCII, key))

    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))

    return key, ''.join(l)

Looking at

    l = []
    for match in list(x):
        l.append(match.replace(match, z[match]))

we have a lot of inefficiencies. You should just do

    for match in x:

and then

        l.append(z[match])

since the replace is a no-op.

This can be a list comprehension:

    l = [z[match] for match in x]

This is now just

import random

ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key, backwards=False):
    z = dict(zip(key, ASCII) if backwards else zip(ASCII, key))

    l = [z[match] for match in x]
    return ''.join(l)

You can then replace some of the challenge with str.translate and str.maketrans:

import random

ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key, backwards=False, base_chars=ASCII):
    if backwards:
        base_chars, key = key, base_chars

    return x.translate(str.maketrans(base_chars, key))

The bug

There is a duplicate character in ASCII. This can, and does, break things

                                                                      ↓↓
ASCII = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()_-+={}[]|\:;?/~`"" '
                                                                      ↑↑

Personally, your best best is just to use string.ascii_lowercase + string.digits + string.punctuation, despite it being slightly different to the above. This gives

import random
import string

ASCII = string.ascii_lowercase + string.digits + string.punctuation

def keygen():
    l = list(ASCII)
    random.shuffle(l)
    return ''.join(l)

def cipher(x, key, backwards=False, base_chars=ASCII):
    if backwards:
        base_chars, key = key, base_chars

    return x.translate(str.maketrans(base_chars, key))

Of course, don't roll your own crypto.


CSS flexbox responsive grid system I'm using the flexbox for the first time for a responsive grid system. It seems to be working as far as I tested but want to make sure it works on others too and see ways to improve this.

Please see style.css for the grid system with flexbox on github.

*{
  box-sizing: border-box;
  -moz-box-sizing: border-box;
}
html, body{
  margin: 0;
}

/*
Layout with flexbox
*/
.container{
  max-width: 1200px;
  margin: 0 auto;
}
.container--small{
  max-width: 800px;
}
.row {
  display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
  display: -ms-flexbox;      /* TWEENER - IE 10 */
  display: -webkit-flex;     /* NEW - Chrome */
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
}
.col{
  -webkit-box-flex: 1;      /* OLD - iOS 6-, Safari 3.1-6 */
  -moz-box-flex: 1;         /* OLD - Firefox 19- */
  -webkit-flex: 1;          /* Chrome */
  -ms-flex: 1;              /* IE 10 */
  flex: 1;
}

/*
Extra Layout - 33%
*/
.col--30{
  -webkit-box-flex: 0 0 33.3333%;;
  -moz-box-flex: 0 0 33.3333%;;
  -webkit-flex: 0 0 33.3333%;;
  -ms-flex: 0 0 33.3333%;;
  flex: 0 0 33.3333%;;
}

/*
Media query
*/
@media (max-width: 768px) {
  .row > .col,
  .col--30 {
    -webkit-box-flex:  0 0 100%;
    -moz-box-flex:  0 0 100%;
    -webkit-flex: 0 0 100%;
    -ms-flex: 0 0 100%;
    flex: 0 0 100%;
  }
}

1/3 - #1

1/3 - #2

1/3 - #3

Here is my analysis:

Well formatted
Both backwards and forwards compatible
Has both block and inline comments

The only thing would be wary of is the margin: 0 on the html, body selector may not work as expected on newer iPhones to Safari's new behavior:
Out of the box, Safari displays your existing websites beautifully on the edge-to-edge display of the new iPhone X. Content is automatically inset within the display’s safe area so it is not obscured by the rounded corners, or the device’s sensor housing.
The inset area is filled with the page's background-color (as specified on the <body> or <html> elements) to blend in with the rest of the page. For many websites, this is enough. If your page has only text and images above a solid background color, the default insets will look great.
The first new feature is an extension to the existing viewport meta tag called viewport-fit, which provides control over the insetting behavior. viewport-fit is available in iOS 11.
The default value of viewport-fit is auto, which results in the automatic insetting behavior seen above. In order to disable that behavior and cause the page to lay out to the full size of the screen, you can set viewport-fit to cover. After doing so, our viewport meta tag now looks like this:

<meta name='viewport' content='initial-scale=1, viewport-fit=cover'>


Find the maximum profit if given an array of daily stock prices and allowed to buy and sell twice I am wondering about the correctness of this method:

We are given a function / algorithm findMaxProfit() that can find the maximum profit when given an array of stock prices, and buy and sell once, with time complexity O(n), additional space complexity O(1). The buy must occur before the sell (meaning no short sell is allowed).

findMaxProfit() will return the maximum profit, and the buy and sell point (as indexes into the array). Example: [3200, 6, 22] meaning max profit is 3200, and buy on day 6, sell on day 22. (day in the description is also 0 index based).

Any buy and sell can occur on the same day, meaning profit = 0.

Now, find the maximum profit if you are allowed to buy and sell at most twice, with the second buy occurring on or after the first sell, and with time complexity O(n), additional space complexity O(1).

I think one assumption is that we buy the same number of shares both times (let's say just 1 share). Otherwise, if the earned money from the first time can be used to buy stocks the second time, then it is not the dollar amount we are concerned with, but the percentage gain overall.

// this function just returns the max profit, no need to return the
// buy / sell point.  In JavaScript ES6

function findMaxProfitBuySellTwice(arr) {
  const [max1, a, b] = findMaxProfit(arr);

  return max1 + Math.max(findMaxProfit(arr.slice(0, a),
                         findMaxProfit(arr.slice(b + 1));
}

the a can be a + 1, while the b + 1 can be b, but with no use. The reason is let's say if you buy on day 6, then from day 5 to day 6, there will be no profit, or else the findMaxProfit() would have included day 5. Likewise, if findMaxProfit() says to sell on day 22, then from day 22 to 23, there is no profit, so we really don't need to start at day 22 but start at day 23.  slice() will return empty array if it is out of bound.

About the correctness of the code, because the Maximum Stock Profit Problem is interchangeable with the Maximum Subarray Problem. In fact, the number returned by the Maximum Stock Profit Problem and the number returned by the Maximum Subarray Problem should actually be exactly the same number.

So if we are asked to find the 2 subarrays that will add up to maximum, we could do the same as above: (1) find the maximum subarray first. (2) now slide this region out, and find the max for the remaining two regions. (3) just add up the max from step (1) and the maximum of the 2 numbers from step (2).

It seems the correctness of doing this to the Maximum Subarray Problem is more obvious: the 2 maximum subarrays are just finding the max first, and then disregard this region, and find the max of the remaining 2 sets of data.

Note that the Maximum Stock Profit Problem and the Maximum Subarray Problem should be able to convert to each other, say, from the stock problem to the subarray problem by taking the difference between the daily prices (resulting an array with size 1 less in general):

function convertStockDataToMaxSubarrayData(arr) {

  var maxSubarrayData = [], i;

  if (arr.length <= 1) return [];

  for (i = 1; i < arr.length; i++) {
    maxSubarrayData.push(arr[i] - arr[i-1]);
  }

  return maxSubarrayData;
}

It seems the correctness of doing this to the Maximum Subarray Problem
  is more obvious: the 2 maximum subarrays are just finding the max
  first, and then disregard this region, and find the max of the
  remaining 2 sets of data.

That's actually wrong. Let the array be [2, -1, 4, 2, 3]. Your solution would take the whole array as the maximum during the first step (the sum is 11) and remove it, leaving an empty array, so it would return 11. But that's not correct. Two subarray [0, 1) and [2, 5) add up to 12, yielding an optimal solution.

It also implies that your solution to the stock selling problem is also incorrect (a counter example can be constructed in a similar manner).

You can use dynamic programming to solve the problem correctly. There's a constant number of states in each layer, so the extra space complexity is constant (the code is in python, but it should be easy to implement this algorithm in any other language):

def get_two_max(nums):
    """
    Returns the two maximums in the list.
    The list must contain at least 2 elements.
    """
    max1 = max(nums[0], nums[1])
    max2 = min(nums[0], nums[1])
    for num in nums[2:]:
        if num >= max1:
            max2 = max1
            max1 = num
        elif num > max2:
            max2 = num
    return max1, max2

def get_max_two_subarrays(nums):
    """
    Returns the maximum sum of two non-intersecting non-empty subarrays
    """
    if len(nums) < 2:
        # There're no two non-intersecting non-empty subarrays
        return None
    count_non_neg = sum(1 for num in nums if num >= 0)
    if count_non_neg < 2:
        # There is at most one positive element, so the optimal answer is
        # to take two largest elements of the array
        return sum(get_two_max(nums))
    # The state has the following meaning:
    # 0 - the first subarray hasn't started
    # 1 - the first subarray has started, but it's not over yet
    # 2 - the first subarray is over
    # 3 - the second subarray has started, but it's not over yet
    # 4 - both subarrays are over
    dp = [0] * 5
    for num in nums:
        new_dp = [0] * len(dp)
        for state in range(len(dp)):
            # Doesn't change the state. Adds the current element if one of
            # the subarrays is not over.
            new_dp[state] = max(new_dp[state], dp[state] + (num if state % 2 else 0))
            if state + 1 < len(dp):
                # Goes to the next state by opening/closing a subarray
                new_dp[state + 1] = max(new_dp[state + 1], new_dp[state])
        dp = new_dp
    # The answer is the value of the state when both subarrays are over
    return dp[-1]

If you have a solution and you're not sure if it's correct or not, you can do the following:

Implement a slow but obviously correct solution (in this case, it would just generate all subarrays, compute their sums and choose the best one).
Generate thousands of small test cases and compare the output of your solution and the naive one. It's quite likely that you'll a test case your code fails if it's actually wrong (that's exactly how I found a counterexample to your algorithm).


This has gone unanswered for a long time, and even though I haven't done any serious prolog coding, I would like to come with some general remarks which might be useful for you.

Style wise I would add spaces after commas, to increase readability. Other than that it looks clean enough, but some comments on what the different parts does, wouldn't hurt.

But my main point in this review is this: Device code structures after you have a need for it, and don't create structure first and then ask for a need of it.

You've done it the other way around, which is kind of strange, but could be a good learning experience for you. Could it be useful for some cases? Who knows. In general, most likely not, as normally you have the use case first, and then code a solution to it.


How to pass pre-generated values to an anonymous function to speed up a fit? In Matlab I am using the combination of fit and fittype function (from the curve fitting toolbox) to fit a signal using an anonymous function.

My issue is that, this anonymous function use the integral function of matlab, and this is extremely time consuming. I am therefore trying to get rid of this function inside the anonymous function.

An amazing improvement would be to pre-calculate these integral and pass it to the fit function, but I do not know how to do this.

I tried to define the vector that contain these integration values and pass it to the fit by defining it as 'dependent' or 'problem' variable in fittype but that did not do the trick. I also tried concatenating the coordinate and the result of this integral. When doing a two column vector it tried to fit a surface (which it is not the case). When concatenating in a one column vector it complain that the data set and the coordinate system should be the same size.

As an alternative I also tried using sum and trapz instead of integral but fittype told me that then the function did not fulfill the criteria of an anonymous function.

I am running short on ideas and on ways to ask search engines for new ideas and would welcome all new point of view on how to solve this.

For curious peoples here is the original anonymous function I am using:

function [ y ] = zeusEquation(varargin)
    psi0=varargin{1};% in radian
    a1 = varargin{2};% parameter to be fitted
    a2 = varargin{3};%parameter to be fitted
    a3 = varargin{4};% average of background signal/ offset in gray level
    a4 = varargin{5};% slope on the signal background
    a5 = varargin{6};% decentering of the signal (in meter)
    a6 = varargin{7};% width of the signal in radian
    x = varargin{8};%Coordinate system in meter!!!!
    y = zeros(size(x));

    %fundamental bloc equation needed
    sinIntegral = @(t) 2.*sin(t)./(pi.*t);
    u = @(f, e, x) f.*abs(x-e);

    %Actual signal calculation
    for i = 1:max(size(x))
        if u(a6,a5,x(i))~=0
            y(i) = a3...
             +a4.*(x(i)-a5)...
             +(1-integral(sinIntegral,0,u(a6,a5,x(i))))...
             .*(a1.*sign(x(i)-a5).*sin(psi0)-...
             (1-a2).*integral(sinIntegral,0,u(a6,a5,x(i))).*(1-cos(psi0)));
        else
            y(i) = a3+a4.*(x(i)-a5);
        end
    end
end

Note: I cross asked this question on mathwork.

A named function is declared like this:

function out = function_name(in)

If it is written in a file of the same name, and the file is on the MATLAB path, then it is accessible from the base workspace and any function you call. If it is written as a local function (an additional function in a file defining a different function) then it is only accessible to the other functions in that file. If it is in a sub-directory called private, then it is only accessible to the functions defined in the parent directory.

An anonymous function is defined as like this:

function_handle = @(p) p

Here, function_handle is a variable that contains the anonymous function. In other languages this is called a lambda. This lambda can capture variables from its environment:

data = 1:10;
function_handle = @(p) p.*data

function_handle now contains a copy of data. Changing data or clearing it after creating the anonymous function won't affect the copy of data inside it.

The interesting thing for you here is that a named function can also capture data. This is true only for nested functions (which we didn't mention above). The difference between a nested function and a local function is one measly end statement, it's easy to miss it. This is a local function:

function out = main(in)
% code ...
function r = local(p)
% code ...

This is identical to:

function out = main(in)
% code ...
end
function r = local(p)
% code ...
end

The end statements ending a function are optional.

This is a nested function:

function out = main(in)
% code ...
   function r = nested(p)
   % code ...
   end
end

Here the end statements are mandatory. nested is inside main. nested also has access to variables declared in main. For example, nested can use in.

main can also create a function handle of nested and return it. This function handle then will point at the nested function, and capture its environment. Much like an anonymous function:

function out = main(in)
   data = integral(in,0,1);
   out = @r;
   function r = nested(p)
      r = p .* data;
   end
end

Now, calling main returns a handle to the function nested, which has captured data computed in main. You can use this to create a function handle that you can pass to fit. nested would be your zeusEquation, and main would simply package it with the precomputed integral.

Code review

There are a few things to note about your code:

You compute sin(psi0) and 1-cos(psi0) repeatedly inside your loop. psi0 is a constant within this loop, and consequently you should compute these values once outside of the loop.
You compute integral(sinIntegral,0,u(a6,a5,x(i))) twice for each x(i). This being an expensive function, you should compute it only once and re-use the result.
for i = 1:max(size(x)) is long-hand for for i = 1:length(x). This only works correctly in your loop if x is a vector. In this case, you can use numel(x) instead of length(x). numel is faster.

These three points above lead to:

sinpsi0 = sin(psi0);
cospsi0_1 = 1-cos(psi0);
for i = 1:numel(x)
   if u(a6,a5,x(i))~=0
      int = integral(sinIntegral,0,u(a6,a5,x(i)));
      y(i) = a3 + a4.*(x(i)-a5)  ...
                + (1-int) .* (a1.*sign(x(i)-a5).*sinpsi0 ...
                              - (1-a2).*int.*cospsi0);
   else
      y(i) = a3 + a4.*(x(i)-a5);
   end
end

integral must be called with scalar limits, but other components can be computed vectorised. It would be possible to compute only the integral within the loop, and the rest without a loop.

This leads to:

int = zeros(size(x));
for i = find(u(a6,a5,x)~=0)
   int(i) = integral(sinIntegral,0,u(a6,a5,x(i)));
end
y = a3 + a4.*(x-a5)  ...
       + (1-int) .* (a1.*sign(x-a5).*sin(psi0) ...
                     - (1-a2).*int.*(1-cos(psi0)));

This should be faster, but I haven't tested it. (I assume a1 and the like are all scalars?)
You define your functionzeusEquation using varargin, then proceed to unpack the varargin cell array with the assumption that all your input arguments are there. This is correct in your situation of course, but you might as well do:

function y = zeusEquation(psi0,a1,a2,a3,a4,a5,a6,x)

In this way, if zeusEquation is called with fewer (or more!) arguments, you'll get a sensical error message, rather than an "index out of bounds" error.