Find longest sequence of zeroes in a binary representation of an integer I am aware this problem has been asked before but in java e.g Printing longest sequence of zeroes. This is a similar problem but in C#. A brief explanation of the problem is  to find the longest sequence of zeroes in a binary representation of an Integer. For instance, the Integer 529 in binary gives 1000010001  and the longest sequence of zeroes is 4. So far I have achieved this using the following code

using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static int Solution(int N)
    {
        List<int> occurenceCount = new List<int>();
        int Counter=0,value;

        if(N == 0)
        {
            Console.WriteLine(0);
            return 0;
        }

        else{
            string binaryRep = Convert.ToString(N,2);

            // find the first occurence of 1
            int FirstIndex = binaryRep.IndexOf("1");

            // find the last occurence of 1
            int LastIndex = binaryRep.LastIndexOf("1");

            for(int i = FirstIndex; i<LastIndex+1;)
            {

                value = i;

                while(binaryRep[value++] != '1' )
                {
                  Counter = Counter+1;
                }
                occurenceCount.Add(Counter);
                i= value;
               Counter=0;
            }
        return occurenceCount.Max();
        }
    }
    static void Main()
    {
       Console.WriteLine(Solution(1041));
    }
}

Brief description of the code: If the Integer passed is 0, then 0 is returned else the longest sequence. The convert.ToString() gives the binary representation. To improve the performance, I keep track of the index of the first 1 and the last index of 1  and use this in the for loop. In the while  loop, once a 0 is encountered in between two 1's then a counter is incremented until a 1 is encountered and later on added to the List.
I would appreciate if any one can tell me how to improve on this.

Unless performance is somehow critical, you'd do far better by just making use of String.Split on '1' after getting a binary representation. Then you can search for the longest string in that array. The current implementation is very low level and hard to easily understand.

A programmer who sees the code as it is now would have to invest time to understand how it works, whereas relying on (even if slower) a few library calls can make an algorithm easier to understand for programmers, thus being of more value than the faster, low level algorithm. It's also faster to write such things and less likely to contain bugs because most of the actual work is done by the standard libraries, which are thoroughly tested by other programmers.


Custom delete method refactoring I'm new to Ruby and don't know all the methods, so I was thinking there would probably be and easier way to do something like this. I'd love any input on how to refactor this.

   define_singleton_method(:delete) do |id|
        revised_words = []
        @@words.each do |word|
          if word.id() != id
            revised_words.push(word)
          else
            Definition.delete_by_word_id(id)
          end
        end
        @@words = revised_words
      end

Some notes:

An array is not the best data structure to store the words, operations will be O(n). Better a hash {word_id => word}
Use 2-space indentation.

Then you can write:

define_singleton_method(:delete) do |id|
  if @@words.delete(id)
    Definition.delete_by_word_id(id)
  end
end


iOS Body-Mass-Index (BMI) app This is "homework" from a Swift course, which I'm currently taking. A mockup and the image-assets are provided by the instructor. We are supposed to create the layout and to write some appropriate code.

Here's the code of my ViewController:

import UIKit

class ViewController: UIViewController {
    // MARK: Outlets
    @IBOutlet weak var nameText: UITextField!
    @IBOutlet weak var sizeText: UITextField!
    @IBOutlet weak var weightText: UITextField!

    @IBAction func clickHereButton(_ sender: UIButton) {
        let name = nameText.text!
        let size = Double(sizeText.text!)!
        let weight = Double(weightText.text!)!

        let bmi = weight / pow(size, 2)
        let bmiRounded = (round(bmi * 10) / 10)
        print(bmiRounded)

        let uac = UIAlertController(title: "BMI for \(name)", message: "Your Body-Mass-Index is \(bmiRounded)", preferredStyle: .alert)
        uac.addAction(UIAlertAction(title: "Okay", style: .default))
        self.present(uac, animated: true, completion: nil)
    }
}

What are your thoughts about my implementation? What would you have done differently and why?

You are doing double force-unwraps, twice. This is really just asking for trouble

As others have pointed out in their comments, there are a few edge cases you should guard against. Good thing is you can do both at the same time.

Additionally, you should avoid using shortened names for your variables. In Swift, we usually type everything out.

I've updated and annotated your code below, take a look;

@IBAction func clickHereButton(_ sender: UIButton) {

    // Start by ensuring we have actual values entered by the user
    guard let name = nameText.text,
          let sizeString = sizeText.text,
          let weightString = weightText.text else {
        return
    }

    // Then, ensure the values are valid Doubles
    guard let size = Double(sizeString),
          let weight = Double(weightString) else {
        return
    }

    // Finally, ensure that size > 0
    guard size > 0 else {
        return
    }

    // We now are 100% safe and can start calculating our BMI
    let bmi = weight / pow(size, 2)
    let bmiRounded = (round(bmi * 10) / 10)

    // Even though this var name is longer, it's clearer what it is.
    let alertViewController = UIAlertController(title: "BMI for \(name)", message: "Your Body-Mass-Index is \(bmiRounded)", preferredStyle: .alert)

    // You can use the `.init(_:)` shorthand when a specific type is required
    alertViewController.addAction(.init(title: "Okay", style: .default))
    self.present(alertViewController, animated: true, completion: nil)
}

The only other thing I would improve is to move your actual BMI calculations to a specific function that takes in the size and weight parameters.

For the rest, it's pretty much all good.


Custom ResponseModel for Spring Controller - ResponseEntity I created a custom responseModel to have a standard json responseModel for some of my different RestController.

Superclass TransactionResponseModel:

public class TransactionResponseModel {

    private HttpStatus httpStatus;
    private Double amount;
    private String transactionId;
    private String message;

    public SvsTransactionResponseModel() {
        super();
    }

    public SvsTransactionResponseModel(HttpStatus httpStatus, String message) {
        super();
        this.httpStatus = httpStatus;
        this.message = message;
    }
   //public getter/setter
}

Class BalanceInquiryResponseModel:

public class BalanceInquiryResponseModel extends SvsTransactionResponseModel {

    private final BalanceInquiryResponse balanceInquiryResponse;

    public BalanceInquiryResponseModel(BalanceInquiryResponse balanceInquiryResponse) {
        super();
        this.balanceInquiryResponse = balanceInquiryResponse;
        if (this.balanceInquiryResponse != null && this.balanceInquiryResponse.getBalanceInquiryReturn() != null) {
            setAmount(this.balanceInquiryResponse);
            setMessage(this.balanceInquiryResponse);
            setTransactionId(this.balanceInquiryResponse);
            setHttpStatus();
        }
    }

    private void setAmount(BalanceInquiryResponse balanceInquiryResponse) {
        if (balanceInquiryResponse.getBalanceInquiryReturn().getBalanceAmount() != null) {
            setAmount(balanceInquiryResponse.getBalanceInquiryReturn().getBalanceAmount().getAmount());
        }
    }

    private void setTransactionId(BalanceInquiryResponse balanceInquiryResponse) {
        setTransactionId(balanceInquiryResponse.getBalanceInquiryReturn().getTransactionID());
    }

    private void setMessage(BalanceInquiryResponse balanceInquiryResponse) {
        if (balanceInquiryResponse.getBalanceInquiryReturn().getReturnCode() != null) {
            setMessage(balanceInquiryResponse.getBalanceInquiryReturn().getReturnCode().getReturnDescription());
        }
    }

    private void setHttpStatus() {
        setHttpStatus(HttpStatus.OK);
    }
}

The BalanceInquiryResponseModel expects a BalanceInquiryResponse Object for setting different attributes. Nearly all attributes for my BalanceInquiryResponseModel are coming from a thiry-party Object BalanceInquiryResponse. This third-party object has to many information and because of that I dont want to response this object to the caller but set instead all the necessary attributes manually.

In my Controller I just return a ResponseEntity<? extends SvsTransactionResponseModel>.

@PostMapping(value = "/balanceInquiry")
public ResponseEntity<TransactionResponseModel> getBalanceInquiry(
        @Valid @RequestBody BalanceInquiryModel balanceInquiry, Errors errors) {
    if (errors.hasErrors()) {
        return new ResponseEntity<>(
                new TransactionResponseModel(HttpStatus.BAD_REQUEST, errors.getAllErrors().toString()),
                HttpStatus.BAD_REQUEST);
    }
    BalanceInquiryResponse balanceInquiryResponse = null;
    //logic to get the balanceInquiryResponse.

    return new ResponseEntity<>(new BalanceInquiryResponseModel(balanceInquiryResponse), HttpStatus.OK);
}

For other controllers I will have the other responseModels extending TransactionResponseModel.

Is this a good approach for a custom responseModel?

Tech-Stack:

spring-boot

To start, I think what you have there looks pretty straight forward.  It also looks very neatly written.  From just what I can see here, it would appear the largest gain from your "base" model is that it removes extraneous data from traveling out to the user.  The largest loss (potentially), is that it utilizes inheritance and theoretically forces those 4 properties onto every inherited result.  That being said, here's some reasoning...

Disclaimer :) Inheritance may be the perfect solution for what you've got going here in the long run.  But from the limited view here, it feels heavy handed.  It should also be noted that I haven't written Java an about 9 years and I'm currently a C/F# programmer.

Two things stand out to me.  First, the use of properties and private fields.  This contract appears to be immutable.  Could the fields just become public and final and lose the setters?  It doesn't appear to do much except to protect inherited members from accessing those values directly.  It would also reduce the amount of code in the class (#1 reason).  I can't see from here what the benefit of them being private is.  The notion that an inherited class would have no real access to it's base class raises a red flag.

This leads to the second thing.  Consider removing the inheritance.  Inheritance is always great until it's not.  You contract is simple enough that it wouldn't suffer this problem today, but several inherited types later it might.  The challenge with inheritance (especially with data), is that it forces everything to be the same shape.  The upside, is that inheritance is never really required to solve a problem.  It's just something we do... just because, usually.

You could consider a setup like this (pseudo code):

public class TransactionResponseModel { ... }

public class BalanceInquiryResponseModel {
    public BalanceInquiryResponseModel(TransactionResponseModel transactionResponseModel, BalanceInquiryResponse balanceInquiryResponse) {
    ...
    }

    public final TransactionalResponseModel TransactionalResponse;
    public final BalanceInquiryReponse InquiryResponse;
}

Inheriting doesn't really force anything, because the next developer might simply choose not to inherit.  Here you get all the same shapes and data without the class coupling and hierarchy.  Which is, in my experience, totally worth it.  When the response model comes that doesn't fit the same shape as your base classes, you won't have to setup a new inherited structure, modify your current one, or even care for that matter.  New data, new shape, no problem.

There are lot's of articles available on the un-benefits of inheritance:

Gooooooooogle

Hope this information is helpful.


Find most frequent word in text file Write a function that a receives file name of a txt file, which contains unknown number of words of max length 10 each. Print the word with the most occurrences. Assume the input is correct and contains at least one word.

Code

#define MAX_CHARS 11

int mostFrequentWord(char* filename) {
  char ch;
  int i, j, k, occurrence, counter = 1, maximum = 0;
  char *index_max = NULL;
  char **arr;
  FILE *file = fopen(filename, "r");
  while((ch = fgetc(file)) != EOF) {
    if(ch == ' ') {
        counter++;
    }
  }
  rewind(file);
  arr = (char**) calloc(counter, sizeof(char*));
  for (k = 0; k < counter; k++) {
    arr[k] = (char*) calloc(MAX_CHARS, sizeof(char));
  }
  while ((ch = fgetc(file)) != EOF) {
    if (ch == ' '){
        i++;
        j = 0;
    } else {
        arr[i][j] = ch;
        j++;
    }
  }
  for (i= 0; i < counter; i++) {
    occurrence = 0;
    for (j = i; j < counter; j++) {
        if (!strcmp(*(arr + i), *(arr + j))){
            occurrence++;
        }
    }
    if (occurrence > maximum) {
        maximum = occurrence;
        index_max = *(arr+i);
    }
  }
  if (index_max != NULL){
    printf("The most frequent word is \"%s\" with %d occurrences.\n", index_max, maximum);
  }
  for ( i = 0; i < counter; i++ ) {
    free(arr[i]);
  }
  free(arr);
  return 0;
}

Example

Input (test.txt):

test one two test three test

Output:

The most frequent word is "test" with 3 occurrences.

One thing I think I'm missing (and not sure what's the way to do it) is to check the success of calling functions that use system resources.

Any review is appreciated.

Clearly employ contract requirements

"Write a function that ...  contains unknown number of words of max length 10 each." should echo in code someplace a 10 named something like "words of max length".  Use "size" for the size of the array.  With strings, best to use "length" in the context of the number of characters before the '\0'.

//#define MAX_CHARS 11
#define WORD_MAX_LENGTH 10
#define WORD_SIZE (WORD_MAX_LENGTH + 1)
...
// calloc(MAX_CHARS, ...
calloc(WORD_SIZE, ...

Use int with fgetc()

fgetc() returns values in the unsigned char range and the negative EOF.  These typical 257 different values will not distinctively fit in an 8-bit char.  With original code, should char be an unsigned char, your loop is infinite.

// char ch;
int ch;
...
while((ch = fgetc(file)) != EOF) {

Check return value of fopen() and calloc()

Should the open fail, detect it.

FILE *file = fopen(filename, "r");
if (file == NULL) {
  fprintf(stderr, "Unable to open file <%s>\n", filename);
  return 0;
}

Should the allocation of more than 0 bytes returnNULL,detect it.

arr = (char**) calloc(counter, sizeof(char*));
if (arr == NULL && counter != 0) {
  fprintf(stderr, "Out of memory\n");
  return 0;
}

Improve *alloc() style

Cast not needed.
Allocate to the size of the object, not the type.  Easier to code right, review and  maintain.

// arr = (char**) calloc(counter, sizeof(char*));
arr = calloc(counter, sizeof *arr);

Good use of sentinels in printing strings

 //                                v   v
 printf("The most frequent word is \"%s\" ...

Lack of bounds checking

Code should ensure i, j are not to big.

if (i >= counter) Handle_Error_Somehow();
i++;

if (j >= MAX_CHARS) Handle_Error_Somehow();
else {
  arr[i][j] = ch;
}

Missing fclose()

fclose(file);

Little bits.

I'd expect size_t counter, i, j, k for array indexing as size_t is neither too narrow nor too wide.  Be mindful it is an unsigned type.

Style: if (index_max != NULL){ is replaceable with if (index_max) {.  I find the the 2nd clearer.


Simple Text Prediction This is a simple implementation of text prediction using a list of keywords and UITextChecker.

This is working correctly, but I think I could have implemented better. My goal is to use a protocol oriented approach.

protocol KeywordSuggester {
    func suggestion(word: String) -> String?
    func loadKeywords() -> Set<String>
}

class EmojiKeywordSuggester: KeywordSuggester {
    var keywords: Set<String> = []
    let language = "en_US"
    private let textChecker = UITextChecker()

    init() {
        self.keywords = self.loadKeywords()
    }

    func suggestion(word: String) -> String? {
        var completions = (textChecker.completionsForPartialWordRange(word.fullRange, inString: word, language: language) ?? []) as! [String]
        let guesses = (textChecker.guessesForWordRange(word.fullRange, inString: word, language: language) ?? []) as! [String]

        completions.appendContentsOf(guesses)
        completions = completions.filter(self.keywords.contains)

        guard completions.count > 0 else { return nil }
        return completions[0]
    }

    func loadKeywords() -> Set<String> {
        //TODO: load CSV from file
        return ["happy", "smile", "nature", "mushroom", "eye", "poop", "icecream", "food", "grin", "face"]
    }
}

First of all, these two lines:

guard completions.count > 0 else { return nil }
return completions[0]

can be simplified as just this:

return completions.first

It does exactly the logic you've implemented, except that it's far more clear what the intent is.  Moreover, if ever you need to do this in the case that completions isn't a local variable, your approach is not thread safe.

Taking a look at the bigger picture, I don't understand the purpose of loadKeywords neither as part of the protocol nor as a method itself.

It appears that the only real reason that they exist is because they are used by the suggestion() method.  Since you haven't included the code that is actually using this protocol, I can only guess, but my best guess is that it's completely not needed.  Instead, I would take an approach like this with the protocol:

protocol KeywordSuggesterProtocol {
    func canSuggestForKeyword(keyword: String) -> Bool
    func suggestionForKeyword(keyword: String) -> String
}

Notice here, no optionals.

It potentially make sense for the protocol to simply be the second method and have it return an optional, simply returning nil where the first method would have return false.  But potentially, suggestionForKeyword might be an expensive operation (although I suppose it could be optimized).  So a protocol like this:

protocol KeywordSuggesterProtocol {
    func suggestionForKeyword(keyword: String) -> String?
}

could work as well.

The code that actually makes use of the protocol would look like one of the following two snippets (based on which protocol you're using):

class Foo {
    weak var suggester: KeywordSuggesterProtocol?

    // ...

    func someFuncThatNeedsKeywords(keyword: String) {
        var suggestedWord: String?
        if suggester?.canSuggestForKeyword(keyword) {
            suggestedWord = suggester?.suggestionForKeyword(keyword)
        }
    }

    // ...
}

... or ...

class Foo {
    weak var suggester: KeywordSuggesterProtocol?

    // ...

    func someFuncThatNeedsKeywords(keyword: String) {
        let suggestedWord = suggester?.suggestionForKeyword(keyword)
    }

    // ...
}

Hmm, the latter is probably better honestly.

As for your implementation, let's take a look at your initialization...

class EmojiKeywordSuggester: KeywordSuggester {
    var keywords: Set<String> = []
    let language = "en_US"
    private let textChecker = UITextChecker()

    init() {
        self.keywords = self.loadKeywords()
    }

    // stuff
}

First of all, language and keywords should be private.  But also, the loadKeywords method really isn't useful to us at all beyond initializing the keywords, right?  So, let's take this approach...

class EmojiKeywordSuggester: KeywordSuggester {
    private let keywords: Set<String> = {
        //TODO: load CSV from file
        return ["happy", "smile", "nature", "mushroom", "eye", "poop", "icecream", "food", "grin", "face"]
    }()

    private let language = "en_US"

    private let textChecker = UITextChecker()

    // init no longer necessary
}

Now, it may come a time when you actually want to implement loading the keywords from CSV, in which case, we'd want something like this:

class EmojiKeywordSuggester: KeywordSuggester {
    private let keywords: Set<String>
    private let language = "en_US"
    private let textChecker = UITextChecker()

    init?(csvFilePath: NSURL) {
        guard let loadedKeywords = loadKeywordsFromCSV(csvFilePath) else {
            keywords = []
            return nil
        }
        keywords = loadedKeywords
    }

    private func loadKeywordsFromCSV(csvFilePath: NSURL) -> Set<String>? {
        // logic to load from the URL (which could be a local file URL)
        // this can of course fail, and return nil
    }
}

It's a failable initializer that fails when we can't load the keywords from the file path.


C++ Minimalistic Unit Testing Library I was looking for a unit testing library for C++, and I found many. Unfortunately, I decided I didn't want to use any of them. I decided to make my own.

This is the result. I made heavy use of the preprocessor, and followed the convention of leading underscore to mean non-published. Everything is done in all-caps, to try to follow good conventions and to avoid name collisions.

Please note that this code is published under the MIT license.

unittest.h

#pragma once

#include <vector>
#include <iostream>

// Helper Macros
#define _STR_HELP(x) #x
#define _STR(x) _STR_HELP(x)
#define ESCAPE(...) __VA_ARGS__ // TEST_CASE(std::map<int, int>) would fail. Wrap in this Macro to not fail.

#define _FILE_LINE __FILE__ ":" _STR(__LINE__)

// Assertion Macros
#define _GENERATE_MESSAGE(test) _FILE_LINE " Failed " #test "." // Message in almost every assertion

/*
 * Assertions are intended to be used within a TEST_CASE macro. We return EXIT_FAILURE if we fail the assertion,
 * meaning that the TEST_CASE fails. Assertions can also be used straight inside the main function, in which case
 * the main function will exit. They are intended to be used within the TEST_CASE macro, so it's not recommended to do
 * that.
 */
#define _ASSERT(test, message)  if (!(test)) {\
                                    std::cerr << message << std::endl;\
                                    return EXIT_FAILURE;\
                                }
// One argument assertion. This generates a message to display.
#define _ASSERT_1(test) _ASSERT(test, _GENERATE_MESSAGE(test))
// Two argument assertion, which appends the user-defined message to the generated one.
#define _ASSERT_2(test, additional) _ASSERT(test, _GENERATE_MESSAGE(test) " " additional)

// Helper macro to get the correct assertion (out of _ASSERT_1 or _ASSERT_2)
#define _GET_ASSERTION(_1, _2, NAME, ...) NAME

// Public Macro for actually calling the ASSERT
#define ASSERT(...) _GET_ASSERTION(__VA_ARGS__, _ASSERT_2, _ASSERT_1)(__VA_ARGS__)
// More advanced macro than ASSERT; it tells the values of each of the arguments as part of the message.
#define ASSERT_EQ(a, b) {\
                            const auto& _VAL_1 = a;\
                            const auto& _VAL_2 = b;\
                            if (_VAL_1 != _VAL_2) {\
                                std::cerr << _FILE_LINE " Failed " #a " == " #b ". Actual Values:\n" \
                                    #a ": " << _VAL_1 << "\n" \
                                    #b ": " << _VAL_2 << std::endl;\
                                return EXIT_FAILURE;\
                            }\
                        }

/*
 * Convenience struct for storing test cases and all related data into a vector.
 */
struct _TEST_CASE
{
    const char *name;
    int (*function)();
    bool result;
};
std::vector<_TEST_CASE> _TEST_CASES; // All test cases are added to this global vector.

// Test Execution Macros
#define TEST_CASE(name, code) _TEST_CASES.push_back({ name, [](){ code; return EXIT_SUCCESS; }, false });

#define RUN_TESTS() std::cout << std::endl; \
                    for (_TEST_CASE& testCase : _TEST_CASES) {\
                        testCase.result = EXIT_SUCCESS == (*testCase.function)();\
                        if (!testCase.result) {\
                            std::cerr << "Failed test case " << testCase.name << "\n";\
                        }\
                    }\
                    std::cout << "Results: ";\
                    for (_TEST_CASE testCase : _TEST_CASES) {\
                        std::cout << (testCase.result ? '.' : 'F');\
                    }\
                    std::cout << std::endl << std::endl;

I decided I didn't want to use any of them. I decided to make my own.

That's a mistake.

and followed the convention of leading underscore to mean non-published.

A leading underscore followed by an uppercase letter is reserved identifier reserved for the implementation.

Please note that this code is published under the MIT license.

Also note that this code is not published under the creative commons license. See the bottom of the page. Everything published on any stack-exchange site is available under creative commons.
Design
There are a lot of missing features that I would expect in unit test framework.

Ability to run tests in isolation
Ability to run groups of tests.
Ability to set up state for tests
Ability to tear down state and reset the environment.
Some facility for mocking other classes.


Multiple accordion on a page I've written a simple accordion using zepto js lib.

Looking for advice on how to improve this better.

HTML

   Learn more

     blah

     blah

     blah

     close

   Learn more

     blah

     blah

     blah

     close

Javascript

$('.more').addClass('hide');
var learnMore = $('.learn-more'),
    close = $('.close');
learnMore.click(function() {
    $(this).hide().next('div').toggleClass('hide');
});
close.click(function() {
    $(this).parent().toggleClass('hide');
    $(this).parent().prev().show();
});

Working demo

http://jsfiddle.net/s5x9A/

How can I prevent the page from jumping when I click on the empty anchor tags?

There are a couple of inconsistencies which you could tidy up. You're toggling classes to show/hide the div but using show/hide directly on the triggers. You're using chaining in one onClick but not in the other. And you're using the class to reference the accordion contents in one case, but the element name in the other.

$('.more').hide();

var learnMore = $('.learn-more'),
    close = $('.close');

learnMore.click(function() {
   $(this).hide().next('.more').show();
});

close.click(function() {
    $(this).parent().hide().prev('.learn-more').show();
});

Fiddle

is one possible way of making everything consistent, although you may prefer to always toggle classes instead (or to add animations).


Cat program in x64 FASM I wrote cat program in x64 FASM and I would like to know if there is anything that can be improved.

This implementation of cat supports:

Reading from stdin.
Multiple arguments.

I checked few cases and program behaves exactly like original cat command.

Is there anything I could do to improve performance of this program? I compared it to original cat and my program is around 200ms slower on 512MB file.

Code:

format ELF64 executable 3
entry start

BUFSIZE equ 1048576

segment readable writeable
    fd dq 0
    buf rb BUFSIZE

segment readable executable

start:
    mov rbx, 1
    cmp [rsp], rbx
    je read
open:
    xor rsi, rsi            ;fd=open(pathname,flags)
    mov rdi, [rsp+rbx*8+8]
    mov rax, 2
    syscall
    mov [fd], rax
read:
    mov rdx, BUFSIZE        ;bytes_read=read(fd,buf,BUFSIZE)
    mov rsi, buf
    mov rdi, [fd]
    mov rax, 0
    syscall
write:
    mov rdx, rax            ;write(STDOUT_FILENO,buf,bytes_read)
    mov rsi, buf
    mov rdi, 1
    mov rax, 1
    syscall
    test rdx, rdx           ;if(bytes_read!=0) goto read
    jnz read
close:
    mov rdi, [fd]           ;close(fd)
    mov rax, 3
    syscall
    inc rbx
    cmp rbx, [rsp]          ;if(rbx<argc)
    jb open
exit:
    xor rdi, rdi
    mov rax, 60
    syscall

Linux has the sendfile system call, which copies data between file descriptors instead of copying the data to userspace and back to kernel space. That may be more efficient.

Your code looks very clean and organized. If you had used named constants instead of magic numbers, you might not even need some of the comments:

    mov rdx, tax
    mov rsi, but
    mov rdi, STDOUT_FILENO
    mov rax, SYS_write
    syscall

But I think even with these constants, the comments are still helpful, so I'd probably keep them anyway.

You should add error handling for stdout write errors, such as ENOSPACE.


Checking if there are no numbers from cellular services I have this piece of code, which raises an exception if there are no numbers from 3 services. I really don't like how it looks at the moment.

no_numbers = False
if use_verizon_sms:
  if not Api.check_avalible_credits():
    no_numbers = True
elif use_verizon:
  if not buy_verizon_number():
    no_numbers = True
else:
  if not check_count_numbers():
    no_numbers = True

if no_numbers:
  raise Exception("THERE IS NO AVAILABLE NUMBERS")

A shorter version looks even more ugly to me and less clear:

if (use_verizon_sms and not Api.check_avalible_credits()) or \
  (use_verizon and not buy_verizon_number()) or \
  not check_count_numbers():
  raise Exception("THERE IS NO AVAILABLE NUMBERS")

Do you have any ideas how to rewrite it?

Have a look whether you can extract the code into a function. It then may look like this.

def has_no_numbers():
  if use_verizon_sms:
    return Api.check_avalible_credits()

  if use_verizon:
    return buy_verizon_number()

  if check_count_numbers()
    return True

  raise Exception("THERE IS NO AVAILABLE NUMBERS")


Find the minimum number of coins I'm trying to learn dynamic programming and the most popular one is to find the minimum number of coins for the change. I come up with this but I just want to improve this code which I think it could be shorter in Python but I'm new to Python too.

import sys
coins = [1, 3, 5]
min_coin = [sys.maxint] * 20
min_coin[0] = 0

for min_of_i in range(20):
    for c in coins:
        if c <= min_of_i and (min_coin[min_of_i - c] + 1 < min_coin[min_of_i]):
                min_coin[min_of_i] = min_coin[min_of_i - c] + 1

print min_coin

This is already pretty short. Making it shorter doesn't seem a good objective, and risks hurting readability.
That being said, there are a few things you could do.

You could do this in one step:

min_coin = [sys.maxint] * 20
min_coin[0] = 0

Like this:

min_coin = [0] + [sys.maxint] * 19

While at it, why are there 20 elements? Your program will find the minimum number of coins up to 19, and I have a feeling that you actually want it for 20. In which case you would need:

min_coin = [0] + [sys.maxint] * 20

And then use range(21) in the loop. However, you shouldn't hard code this number, give it a name, like target_amount, and use that.

Speaking of names, many of the names in your code can be better:

min_coin is a list, so plural min_coins would be better
min_of_i is actually an amount

One more optimization is possible by flipping the order of the nested loops.
In the current code you need an if statement to skip the amounts that are too small for the coin.
If you make the loop over coins to be the outer loop,
then you can set a starting value for the inner value to make the if statement unnecessary.

def get_min_coins(coins, target_amount):
    n = len(coins)
    min_coins = [0] + [sys.maxint] * target_amount
    for i in range(1, n + 1):
        for j in range(coins[i - 1], target_amount + 1):
            min_coins[j] = min(min_coins[j - coins[i - 1]] + 1, min_coins[j])
    return min_coins


Longest lines of file descending This is a challenge question from codeeval.com:

  Write a program which reads a file and prints to stdout the specified
  number of the longest lines that are sorted based on their length in
  descending order. Input sample:

  Your program should accept a path to a file as its first argument. The
  file contains multiple lines. The first line indicates the number of
  lines you should output, the other lines are of different length and
  are presented randomly. You may assume that the input file is
  formatted correctly and the number in the first line is a valid
  positive integer.

  For Example:

2
Hello World
CodeEval
Quick Fox
A
San Francisco

  Output sample:

  Print out the longest lines limited by specified number and sorted by
  their length in descending order.

  For example:

San Francisco
Hello World

I think my code is pretty readable.

lines = IO
  .readlines(ARGV.first)

puts lines
  .drop(1)
  .sort_by(&:length)
  .last(lines.first.to_i)
  .reverse

Reading a file named on the command line is a common task.  I suggest making use of the ARGF to accomplish that.

Not all lines of the input are to be treated uniformly.  Since the first line is to be treated differently, I suggest defining lines to exclude it.

top_n, *lines = ARGF.to_a
puts lines.sort_by(&:length).last(top_n.to_i).reverse


Code-First Notes Database I need to learn more about Entity Framework, so I created a database to store notes. The database definition is as follows:

public class User
{
    [Key]
    public int UserId { get; set; }

    [MaxLength(20)]
    public string UserName { get; set; }

    public virtual List<Note> Notes { get; set; }
}

public class Note
{
    [Key]
    public int NoteId { get; set; }

    [MaxLength(30)]
    public string Title { get; set; }

    [MaxLength(200)]
    public string Content { get; set; }

    public int UserId { get; set; }
    public virtual User User { get; set; }
}

public class NotesContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Note> Notes { get; set; }
}

I wrote the following helper functions (I'm working off a Console Application for now):

class Program
{
    private static void AddUser(string userName)
    {
        using (var db = new NotesContext())
        {
            db.Users.Add(new User { UserName = userName });
            db.SaveChanges();
        }
    }

    private static void RemoveUser(int userId)
    {
        using (var db = new NotesContext())
        {
            var user = db.Users.FirstOrDefault(u => u.UserId == userId);
            if (user != null)
            {
                db.Users.Remove(user);
                db.SaveChanges();
            }
        }
    }

    private static void ClearUsers()
    {
        using (var db = new NotesContext())
        {
            db.Users.RemoveRange(db.Users);
            db.SaveChanges();
        }
    }

    private static void AddNote(int userId, string title, string content)
    {
        using (var db = new NotesContext())
        {
            db.Notes.Add(new Note { UserId = userId, Title = title, Content = content });
            db.SaveChanges();
        }
    }

    private static void RemoveNote(int noteId)
    {
        using (var db = new NotesContext())
        {
            var note = db.Notes.FirstOrDefault(u => u.NoteId == noteId);
            if (note != null)
            {
                db.Notes.Remove(note);
                db.SaveChanges();
            }
        }
    }

    private static void ClearNotes()
    {
        using (var db = new NotesContext())
        {
            db.Notes.RemoveRange(db.Notes);
            db.SaveChanges();
        }
    }
}

Other than the fact that it would be somewhat expensive to add or remove a set of users using these extensions, rather than getting one DB instance, updating it, and running SaveChanges() once, is there anything I should be doing differently?

Foreign Key

Your foreign key is typed to List. I recommend using a HashSet to prevent adding the same entities twice to you navigation properties. I also recommend instantiating it, too, so that you don't get null reference exceptions on new Users that haven't been loaded from EF.

public virtual ICollection<Note> Notes { get; set; } = new HashSet<Note>()

Additionally, you can take advantage of EF Code First Conventions to not require the foreign key id fields or primary key id fields at all, and have EF imply them for you. This will lead to your entities most closely resembling your domain model, instead of DTOs.

public class User
{
    [MaxLength(20)]
    public string UserName { get; set; }

    public virtual ICollection<Note> Notes { get; set; } = new HashSet<Note>();
}

public class Note
{
    [MaxLength(30)]
    public string Title { get; set; }

    [MaxLength(200)]
    public string Content { get; set; }

    public virtual User User { get; set; }
}

public class NotesContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Note> Notes { get; set; }
}

Structure

There isn't a ton wrong with your code being structured as it is. Anything extra would really be redundancy at this stage, but then it isn't very large at this stage.

The following are recommendations that don't make sense in a trivial project like this, but once you start involving substantial logic, they will be a huge benefit.

Put your logic in a class that makes sense

Program is doing too much, move your DB logic into a Notes or Users class. For command line apps, I prefer to use Program to bridge the chasm between the screaming maw of stringly-typed CMD world and the beautiful, shining crystal palaces of your OOP domain.

I like to use a Service Object for this.

That DbContext Issue

The approach of using a whole db context per operation would be an efficiency issue but you appear to be aware of that.

However, performance aside, I'd recommend against this for a number of reasons.

These methods creating their own db contexts is a violation of the Single Responsibility Principle. It shouldn't matter what DB store you've got in there or when it's saved. Leave that to the consumer of those methods. On top of that, you cannot swap out what DbContext is used in the case of testing.

Secondly the static methods are permanently affecting state. It is very difficult to test these methods without first creating an entire database.

To fix this, you should inject this DbContext dependency.

Lastly, there's a lot of duplication in the boilerplate of creating a DbContext, so we can extract that out to a single method. With it in a single method, it frees you to be more open to altering db code too, allowing you to implement transactions, for example, in the future.

Don't pass ids around, pass the entities

Now that Program is acting as a barrier between the nasty, stringly-typed command line frontier and the beautiful, pure objects domain, let's make that actual domain use pure objects.

You've got these lovely types for a reason, benefit from the type checker and get extra correctness by passing the whole entity between your functions.

Recommendation

(assuming the EF model recommendation earlier)

class NoteService
{
    readonly NotesContext db;

    public NoteService(NotesContext context)
    {
        db = context;
    }

    public Note CreateNote(User user, string title, string content) => new Note { User = user, Title = title, Content = content };

    public void AddNote(Note note) => db.Notes.Add(note);

    public Note GetNote(int id) => db.Notes.Find(id);

    public void RemoveNote(Note note) => db.Notes.Remove(note);

    public void ClearNotes() => db.Notes.RemoveRange(db.Notes);
}

class UserService
{
    readonly NotesContext db;

    public UserService(NotesContext context)
    {
        db = context;
    }

    public User CreateUser(string userName) => new User() { UserName = userName };

    public void AddUser(User user) => db.Users.Add(user);

    public User GetUser(int id) => db.Users.Find(id);

    public void RemoveUser(User user) => db.Users.Remove(user);

    public void ClearUsers() => db.Users.RemoveRange(db.Users);
}

class Program
{
    private static void ExecuteAgainstDatabase(Action<NotesContext> action)
    {
        using (var db = new NotesContext())
        {
            action(db);
            db.SaveChanges();
        }
    }

    private static void ExecuteForUsers(Action<UserService> action) => ExecuteAgainstDatabase(db => action(new UserService(db)));

    private static void ExecuteForNotes(Action<NoteService> action) => ExecuteAgainstDatabase(db => action(new NoteService(db)));

    private static void AddUser(string userName) => ExecuteForUsers(us => us.AddUser(us.CreateUser(userName)));

    private static void RemoveUser(int userId) => ExecuteForUsers(us => us.RemoveUser(us.GetUser(userId)));

    private static void ClearUsers() => ExecuteForUsers(us => us.ClearUsers());

    private static void AddNote(int userId, string title, string content)
    {
        ExecuteAgainstDatabase(db =>
        {
            var noteService = new NoteService(db);
            var userService = new UserService(db);

            var user = userService.GetUser(userId);

            noteService.AddNote(noteService.CreateNote(user, title, context));
        });
    }

    private static void RemoveNote(int noteId) => ExecuteForNotes(ns => ns.RemoveNote(ns.GetNote(noteId)));

    private static void ClearNotes() => ExecuteForNotes(ns => ns.ClearNotes());
}


Entity Framework - Add or Update Parent Entity with Children This code saves an DomainEntityRecord (parent) and DomainEntityDetailRecords (child), and it works. It feels odd that I get the record from the DB, then remove the entities that don't exist in the domain model version, then when I save, I save (AddOrUpdate) the domain entities, and not the EF version. Maybe this is the right way?

public void Handle(SaveDomainEntity message)
{
  var domainEntityRecord = mapper.Map<DomainEntityRecord>(message);

  var existingDomainEntity = dbContext.Set<DomainEntityRecord>()
    .Where(x => x.Id == domainEntityRecord.Id)
    .Include(x => x.DomainEntityDetailRecords)
    .SingleOrDefault();

  if (existingDomainEntity != null)
  {
    // Delete detail records that no longer exist.
    foreach (var existingDetail in existingDomainEntity.DomainEntityDetailRecords.ToList())
    {
      if (domainEntityRecord.DomainEntityDetailRecords.All(
        x => x.DetailId != existingDetail.DetailId))
      {
        dbContext.Set<DomainEntityDetailRecord>().Remove(existingDetail);
      }
    }
  }

  dbContext.Set<DomainEntityRecord>().AddOrUpdate(domainEntityRecord);

  domainEntityRecord.DomainEntityDetailRecords.ForEach(
    record => dbContext.Set<DomainEntityDetailRecord>().AddOrUpdate(record));

  dbContext.SaveChanges();
}

The line ...

 dbContext.Set<DomainEntityRecord>().AddOrUpdate(domainEntityRecord);

... will always try to find an existing record in the database in order to determine whether domainEntityRecord should be marked as Added or as Modified.

But you already fetch the existing record by the statement:

var existingDomainEntity = dbContext.Set<DomainEntityRecord>()
   .Where(x => x.DomainEntityId == domainEntityRecord.DomainEntityId)
   .Include(x => x.DomainEntityDetailRecords)
   .SingleOrDefault();

So there is a redundant database roundtrip in your code. After this statement var existingDomainEntity = ... you know everything that AddOrUpdate is going to find out again. So you may as well do it yourself: if the record exist: modify it and its details, if it doesn't: add it. To modify the existing records, use CurrentValues.SetValues:

  var domainEntityRecord = mapper.Map<DomainEntityRecord>(message);

  var existingDomainEntity = dbContext.Set<DomainEntityRecord>()
    .Where(x => x.DomainEntityId == domainEntityRecord.DomainEntityId)
    .Include(x => x.DomainEntityDetailRecords)
    .SingleOrDefault();

  if (existingDomainEntity != null)
  {
    // Delete detail records that no longer exist.
    foreach (var existingDetail in existingDomainEntity.DomainEntityDetailRecords.ToList())
    {
      if (domainEntityRecord.DomainEntityDetailRecords.All(
        x => x.DomainEntityDetailId != existingDetail.DomainEntityDetailId))
      {
        dbContext.Set<DomainEntityDetailRecord>().Remove(existingDetail);
      }
    }
    // Copy current (incoming) values to db entry:
    dbContext.Entry(existingDomainEntity).CurrentValues.SetValues(domainEntityRecord);
    var detailPairs = from curr in domainEntityRecord.DomainEntityDetailRecords
                      join db in existingDomainEntity.DomainEntityDetailRecords
                        on curr.DomainEntityDetailId equals db.DomainEntityDetailId into grp
                      from db in grp.DefaultIfEmpty()
                      select new { curr, db };
    foreach(var pair in detailPairs)
    {
      if (pair.db != null)
        dbContext.Entry(pair.db).CurrentValues.SetValues(pair.curr);
      else
        dbContext.Set<DomainEntityDetailRecord>().Add(pair.curr);
    }
  }
  else
  {
    dbContext.Set<DomainEntityRecord>().Add(domainEntityRecord);
    // This also adds its DomainEntityDetailRecords
  }

  dbContext.SaveChanges();

As you see, for the details I use a GroupJoin (join - into which serves as an outer join) to determine the existing and the new details. The existing ones are modified, the new ones are added.


Guarantee at least one in a list This is a short piece of code but I feel like it could be done more elegantly. What am I missing?

The goal: if there are any items in a list, and none of them have a given property, set one of them to have that property.

static void GuaranteeAtLeastOne<T>(IEnumerable<T> list, Func<T,bool> getter, Action<T> setter)
{
    if (list.Any() && !list.Any(getter))
    {
        setter(list.First());
    }
}

I wouldn't assume to go for the First, rather I'd have a Func<T, bool> predicate parameter which you pass to a .FirstOrDefault(predicate) and ?? it with .First()

Also, I'd verify IEnumerable<T> != null before anything.

static void GuaranteeAtLeastOne<T>(IEnumerable<T> list, Func<T,bool> getter, Action<T> setter, Func<T,bool> predicate)
{
    if (list == null || list.Count == 0 || list.Any(getter))
    {
        return;
    }

    setter(list.FirstOrDefault(predicate) ?? list.First());
}


Applying correction to a time series in Matlab I face a computation efficiency problem. I have a time series of a non-monotonically drifting variable, that is measurements of objects going through a machine (where the measurement is made) in a production line. The job to do consists of simulating what this time series would yield if there was a correction made to the object each time the measurement drifts above or below a threshold.

To do that I could simply make a for loop, and each time the thresholds are crossed, apply the correction to the rest of the time series. However the time series is very long and the for loop would take too much time to compute. I would like to improve the performance of my code. Does anyone see a way to do this?

Here is a working example using a for loop:

ts = [1 2 3 4 3 2 1 0 -1 -2 -3];
threshold = [-3.5 3];
correction = [1 -1];
for i = 1:numel(ts)
    if ts(i) > threshold(2)
       ts(i:end) = ts(i:end) + correction(2);
   elseif ts(i) < threshold(1)
       ts(i:end) = ts(i:end) + correction(1);
   end
end
disp(ts)

The result is and should be the following array:

[1 2 3 3 2 1 0 -1 -2 -3 -3]

There is really nothing wrong with using a loop in MATLAB. For decades, they have been teaching us to vectorize our code. But in recent years the differences between vectorized code and the equivalent loop code has been shrinking dramatically. And I've run into examples where vectorized code is actually slower!

Nonetheless, there is a simple improvement to be made to your code. Note that what you implemented is an algorithm of \$O(n^2)\$. This simplified bit:

for i = 1:numel(ts)
   ts(i:end) = ts(i:end) + correction(2);
end

does \$n(n+1)/2\$ additions (hence \$O(n^2)\$). Also the indexing is expensive, since you're copying half the array (on average) every loop iteration.

I suggest that, instead of adding correction(2) to all subsequent elements, you store the "current correction", update it every loop iteration, and add it to the current value only.

Below is the test function I wrote. method1 is your code, method2 is my suggestion. At the top is a function that exercises these two methods, compares their output, and times them:

function test_methods
ts = [1 2 3 4 3 2 1 0 -1 -2 -3];
ts1 = method1(ts);
ts2 = method2(ts);
if any(abs(ts1-ts2)>1e-6)
   error('the methods differ');
end
timeit(@()method1(ts))
timeit(@()method2(ts))

function ts = method1(ts)
threshold = [-3.5 3];
correction = [1 -1];
for i = 1:numel(ts)
   if ts(i) > threshold(2)
      ts(i:end) = ts(i:end) + correction(2);
   elseif ts(i) < threshold(1)
      ts(i:end) = ts(i:end) + correction(1);
   end
end

function ts = method2(ts)
threshold = [-3.5 3];
correction = [1 -1];
current = 0;
for i = 1:numel(ts)
   value = ts(i) + current;
   if value > threshold(2)
      current = current + correction(2);
      value = value + correction(2);
   elseif value < threshold(1)
      current = current + correction(1);
      value = value + correction(1);
   end
   ts(i) = value;
end

For the short example input, these functions both run too fast for accurate timing. I see 3.1 μs and 1.4 μs, my version is only twice as fast as yours. But for larger inputs the differences become more important (I figured that the cumulative sum of a random process would imitate appropriately your drifting variable):

ts = cumsum(randn(1,1000));

0.29 ms and 8.33 μs, an order of magnitude difference.

ts = cumsum(randn(1,100000));

Now I see 1.66 s and 0.812 ms, 3 orders of magnitude difference.

Because method1 is quadratic in the input length, and method2 is linear, the time difference grows quadratically.


Why my listview style change when I loop the javascript twice? I develop an android native application using phonegap and jquery mobile. I've made a function to create a listview style dynamically using looping for... When I run the function for the first time, it works, the listview style is working, and match with the content. but when I press back button and run the function again, the style change (the listview style is gone) but the content still there. is my function wrong? how to solve this problem?

the screenshoot for more explanation:

this is the result when I press the back button and run the function again

the codes for more detail:

function detail(kodenegara, koderesult)
        {
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "http://10.80.3.73/webservice/Service1.svc/json/weeklyflash/"+kodenegara,
                dataType: "json",
                success:function(data){
                    var result = koderesult;

                    maks = -1;
                    for(i = 0; i < data[result].length; i++) {
                        if(data[result][i].bulan > maks)
                        maks = data[result][i].bulan;
                    }

                    var loop_tipe = countTypesForBulan(data[result], maks);
                    var innerHtml = "";

                    for (i = 0; i < loop_tipe; i++){
                        a=i+loop_tipe;
                        b=a+loop_tipe;
                        innerHtml +=
                        "
"+
                        "
"+data[result][i].type+"
"+
                        "
"+
                            "
"+
                                "&nbsp;	"+
                                ""+data[result][i].bulan+"/2012	"+
                                ""+data[result][a].bulan+"/2012	"+
                                ""+data[result][b].bulan+"/2012	"+
                            "
"+
                            "
"+
                                "Cash	"+
                                ""+data[result][i].uang+"	"+
                                ""+data[result][a].uang+"	"+
                                ""+data[result][b].uang+"	"+
                            "
"+
                            "
"+
                                "Qty	"+
                                ""+data[result][i].total+"	"+
                                ""+data[result][a].total+"	"+
                                ""+data[result][b].total+"	"+
                            "
"+
                        "
"+
                        "
";
                    }
                    $('#tipe').html(innerHtml);
                    $.mobile.changePage("#detail", "slide", false, true);

                    //show the page
                },
                error: function () {
                    alert("ERROR");
                }
            });
        }

        function countTypesForBulan(resultArray, bulanVal) {
            var i,
                types,
                count = 0;
            for (i=0, types = {}; i < resultArray.length; i++)
                if (resultArray[i].bulan === bulanVal && !types[resultArray[i].type]) {
                types[resultArray[i].type] = true;
                count++;
            }
            return count;
        }

here is for simulation my project with jsfiddle

I can't see anything wrong with your code in terms of why it gives you different styles. I would however ensure you have a consistent coding standard.

For example my coding standards usually include:

Always declare variables. Variable maks is never declared here (I'm going to assume it is never declared.) Change it to var maks = -1;
Always use { and }. This will ensure you don't screw up a block.

if(data[result][i].bulan > maks)
    maks = data[result][i].bulan;

would become:

if(data[result][i].bulan > maks)
{
    maks = data[result][i].bulan;
}

Its just proofing for us who make mistakes from time to time.
make local variables where possible

if (resultArray[i].bulan === bulanVal && !types[resultArray[i].type]) {
    types[resultArray[i].type] = true;
    count++;
}

could be:

 var current = resultArray[i];
 if (current.bulan === bulanVal && !types[current.type]) {
    types[current.type] = true;
    count++;
}

It means less look ups. Most of the time its easier to read.


A function that updates JSON disk object So I have created this function that will add a disk if needed and it takes a disk and a size as inputs. The idea is that I need to update data.disks with a few properties. Disk is called from an external request and it follows the pattern of "disk1", "disk2" and so on. Looking at it there are a few hard-coded values and some that are null. However I left them on purpose to show the structure of data.disk for the next person that might read it or modify it. Because of this it looks verbose and I don't really like it all that much.
Do you see a way to make this function more readable/better in any way?

function addDisk(disk, size) {
    var diskNumber = disk.slice(-1);
    var diskLabel = "Hard disk " + diskNumber;
    var diskIndex = diskNumber - 1;

    //Updating JSON data object
    data.disks[diskIndex] = {
        "componentTypeId" : "com.vmware.csp.iaas.blueprint.service",
        "componentId" : null,
        "classId" : "Infrastructure.Compute.Machine.MachineDisk",
        "typeFilter" : null,
        "data" : {
            "capacity" : size,
            "custom_properties" : null,
            "id" : null,
            "initial_location" : "",
            "is_clone" : false,
            "label" : diskLabel,
            "storage_reservation_policy" : "",
            "userCreated" : true,
            "volumeId" : diskIndex
        }
    }
    log(diskLabel + " has capacity of: " + size + " GBs");
}

You could define a default disk object, so you can show all fields on default values and document the values allowed for each:

var DiskSkelethon = {
    "componentTypeId" : "com.vmware.csp.iaas.blueprint.service",
    "componentId" : null,
    "classId" : "Infrastructure.Compute.Machine.MachineDisk",
    "typeFilter" : null,
    "data" : {
        "capacity" : -1,
        "custom_properties" : null,
        "id" : null,
        "initial_location" : "",
        "is_clone" : false,
        "label" : "",
        "storage_reservation_policy" : "",
        "userCreated" : true,
        "volumeId" : -1
    }
}

Then in your function you will make a copy of it and override just the fields you're changing:

function addDisk(disk, size) {
    var diskNumber = parseInt(disk.slice(-1), 10);
    if (isNaN(diskNumber)) {
       log("some error...");
       return false;
    }
    var diskLabel = "Hard disk " + diskNumber;
    var diskIndex = diskNumber - 1;

    //Updating JSON data object
    var diskData = Object.assign({}, DiskSkelethon)

    diskData.data.capacity = size;
    diskData.data.label = diskLabel;
    diskData.data.volumeId = diskIndex

    data.disks[diskIndex] = diskData
    log(diskLabel + " has capacity of: " + size + " GBs");
}


Best approach on handling function that returns either a promise or just synchronous code I wrote some code and I'm trying to get some feedback on it. I'll try to summerize the essential only. I have a function that based on a condition returns a promise or something else:

this.isActive = function(){
  if(this.disableApplePay && window.ApplePaySession){
    return window.ApplePaySession.canMakePaymentsWithActiveCard(this.merchantId).then(function(response){
      return response;
    });
  }
  return !!(window.ApplePaySession && window.ApplePaySession.canMakePayments() &&
    window.ApplePaySession.supportsVersion(3));
}

Then I call this function to check isActive() in another few methods like this:

Promise.resolve(this.isActive()).then(function(response){
  if(response){
    //execute code here
  }
});

Is the Promise.resolve() in this case following best practice? Is there a better way to deal with the isActive() function?

PS: Let's exclude the async await for the sake of the above example please.

You really don't want a function sometimes returning a promise and sometimes returning a value.  That just makes it difficult for the caller.  Instead, if you sometimes have a promise to return, then you should always return a promise.

function isActive(){
  if(condition){
    return API.someFunction().then(function(response){
      return response;
    });
  }
  return Promise.resolve(active);
}

Then, your caller can just know that it always returns a promise and they can code accordingly.  When you have complexity like this, it's better to encapsulate it in the function itself rather than make every single caller deal with it.

So, the caller can then always and consistently just do:

isActive().then(...).catch(...);

Also, if you actually have this in your real code:

   .then(function(response){
      return response;
    });

then, you can remove that entirely and just use this as it generates the exact same result, but is less code:

function isActive(){
  if(condition){
    return API.someFunction();
  }
  return Promise.resolve(active);
}

Both examples return a promise that resolves to response.  One is obviously a lot simpler than the other.


Strong password checker in Python This is a Leetcode problem -

  A password is considered strong if below conditions are all met -

  1. It has at least 6 characters and at most 20 characters.

  2. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.

  3. It must NOT contain three repeating characters in a row (...aaa... is weak, but ...aa...a... is strong, assuming other
  conditions are met).

  Write a function strong_password_checker(s), that takes a string s
  as input, and returns the MINIMUM change required to make s a
  strong password. If s is already strong, return 0.

  Insertion, deletion or replacements of any one character are all
  considered as one change.

Here is my solution to this challenge -

def strong_password_checker(s: str) -> int:
    def has_lower(s):
        for c in s:
            if c.islower(): return 1
        return 0

    def has_upper(s):
        for c in s:
            if c.isupper(): return 1
        return 0

    def has_digits(s):
        for c in s:
            if c.isnumeric(): return 1
        return 0

    def find_repeats(s):
        i = 0
        j = 0
        repeats = []
        while i < len(s) - 1:
            if s[i+1] == s[i]:
                i += 1
                continue
            if (i - j + 1) > 2: repeats.append(i - j + 1)
            i += 1
            j = i
        if (i - j + 1) > 2: repeats.append(i - j + 1)
        return repeats

    def repeats_after_delete(reps, d):
        if d >= sum([r - 2 for r in reps]):
            return []
        reps = sorted(reps, key=lambda d: d%3)
        while d > 0:
            for i in range(len(reps)):
                if reps[i] < 3:
                    continue
                r = reps[i] % 3 + 1
                reps[i] -= min(r, d)
                d -= r
                if d <= 0:
                    break
        return [r for r in reps if r > 2]

    def num_repeats_change(repeats):
        return sum([r // 3 for r in repeats])

    total_changes = 0
    format_changes = (1 - has_lower(s)) + (1 - has_upper(s)) + (1 - has_digits(s))
    repeats = find_repeats(s)
    if len(s) < 6:
        repeat_change = num_repeats_change(repeats)
        total_changes = max([6 - len(s), format_changes, repeat_change])
    elif len(s) > 20:
        repeats = repeats_after_delete(repeats, len(s) - 20)
        repeat_change = num_repeats_change(repeats)
        total_changes = len(s) - 20 + max([repeat_change, format_changes])
    else:
        repeat_change = num_repeats_change(repeats)
        total_changes = max([repeat_change, format_changes])
    return total_changes

Here are some example outputs -

#print(strongPasswordChecker("aaaaaaaaaaaaAsaxqwd1aaa"))

>>> 6

#Explanation - aa1aa1aa1aAsaxqwd1aa (just an example - delete three characters, add three digits to replace consecutive a's)

#print(strongPasswordChecker("aaaaa"))

>>> 2

#Explanation - aaAaa1 (just an example - add a character (so the length is at least 6), add an uppercase letter to replace consecutive a's)

#print(strongPasswordChecker("aAsaxqwd2aa"))

>>> 0

#Explanation - A strong password (all conditions are met)

Here are the times taken for each output -

%timeit strongPasswordChecker("aaaaaaaaaaaaAsaxqwd1aaa")
>>> 18.7 µs ± 1.75 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit strongPasswordChecker("aaaaa")
>>> 5.05 µs ± 594 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit strongPasswordChecker("aAsaxqwd2aa")
>>> 7.19 µs ± 469 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.

You could use this code for checking whether it has an uppercase/lowercase:

if s.lower() == s:
    # doesn't have any uppercase
if s.upper() == s:
    # doesn't have any lowercase

This way, you don't have to iterate through the entire string.


Finding the differences between two revisions (or objects) This detects the difference between two objects (or revisions):

var A = {A: 10, B: 20, C: 30, D: 90, BB: 5, CC: 4, AA: 2};
var B = { B: 22, C: 30, L: 4, KK: 444, A:15};

var difference = diff(A, B);
console.log(difference);
document.write("<pre>"+JSON.stringify(difference, 0, 3)+"</pre>");

function diff(a, b) {
    var result = {removed: "", changed: "", created: "", notChanged: ""};

    var str1 = JSON.stringify(a);
    str1 = str1.slice(1, str1.length - 1);
    var arr1 = str1.split(',');
    var str2 = JSON.stringify(b);
    str2 = str2.slice(1, str2.length - 1);
    var arr2 = str2.split(',');

    var keys1 = Object.keys(a);
    var keys2 = Object.keys(b);
    while (arr1.length || arr2.length) {
        var key1 = keys1[0];
        var key2 = keys2[0];
        var findIndex = keys2.indexOf(key1);
        var findIndex2 = keys1.indexOf(key2);

        if (findIndex >= 0 && findIndex2 >= 0) {
            if (a[key1] == b[keys2[findIndex]]) {
                arr2.splice(findIndex, 1);
                keys2.splice(findIndex, 1);
                keys1.shift();
                result.notChanged += (result.notChanged && ", ") + arr1.shift();
            } else {
                arr1.shift();
                keys1.shift();
                keys2.splice(findIndex, 1);
                result.changed += (result.changed && ", ") + arr2.splice(findIndex, 1);
            }
        } else {
            if (findIndex === -1 && keys1.length) {
                keys1.shift();
                result.removed += (result.removed && ", ") + arr1.shift();
            }
            if (findIndex2 === -1 && keys2.length) {
                keys2.shift();
                result.created += (result.created && ", ") + arr2.shift();
            }
        }
    }
    result.removed = JSON.parse("{" + result.removed + "}");
    result.notChanged = JSON.parse("{" + result.notChanged + "}");
    result.changed = JSON.parse("{" + result.changed + "}");
    result.created = JSON.parse("{" + result.created + "}");

    return result;

}

Is there anything wrong with my snippet? Do you know of another great way?

You certainly seem to be going a pretty long detour in some cases.

What worries me most is that you look at stringified JSON. Just look at the objects. If you try to manually parse JSON by splitting on commas, you risk splitting on commas in strings, and all sorts of other nonsense.

You really don't need raw JSON strings for anything here (except perhaps for printing the result in a readable way)

Just iterate the objects with for...in, and use hasOwnProperty to check for properties.

For instance:

var A = {A: 10, B: 20, C: 30, D: 90, BB: 5, CC: 4, AA: 2};
var B = { B: 22, C: 30, L: 4, KK: 444, A:15};

var difference = diff(A, B);
document.write("<pre>"+JSON.stringify(difference, 0, 3)+"</pre>");

function diff(a, b) {
  var result = {
    removed: {},
    changed: {},
    created: {},
    notChanged: {}
  };

  // check for changed/unchanged/removed keys
  for(var aKey in a) {
    if(!a.hasOwnProperty(aKey)) continue; // skip inherited properties

    if(b.hasOwnProperty(aKey)) {
      // check for changed/unchanged values
      if(b[aKey] === a[aKey]) {
        result.notChanged[aKey] = a[aKey]; // no change between a and b
      } else {
        result.changed[aKey] = [a[aKey], b[aKey]]; // get before/after values
      }
    } else {
      result.removed[aKey] = a[aKey]; // key wasn't in b, so it's been removed
    }
  }

  // do the reverse to check for added keys
  for(var bKey in a) {
    if(!b.hasOwnProperty(bKey)) continue;
    if(!a.hasOwnProperty(bKey)) {
      result.created[bKey] = b[bKey];
    }
  }

  return result;
}


Graph representation implementation I wanted to represent graphs in Python, and wrote the following class. I don't care about values associated with nodes or the weights of the connections between them, simply the connections between nodes.

Is this a good enough implementation? Or is there a significantly better way?

class Graph:
    def __init__(self, nodes):
        self.array_representation = [[] for _ in range(nodes)]

    def directly_connected(self, node_1, node_2):
        # Predicate, checks if the two nodes are connected by one edge
        return node_2 in self.array_representation[node_1]

    def connect(self, node_1, node_2):
        # Draws an edge between the node at node_1 and the node at node_2
        self.array_representation[node_1].append(node_2)
        self.array_representation[node_2].append(node_1)

If your graph becomes big (or rather if a node has many connections), node_2 in self.array_representation[node_1] might take a long time, because in is O(n) for lists. Therefore I would use a set for the connections of a node. You don't even needed to change a lot:

class Graph:

    def __init__(self, nodes):
        self.connections = [set() for _ in range(nodes)]

    def directly_connected(self, node_1, node_2):
        """Predicate, checks if the two nodes are connected by one edge"""
        return node_2 in self.connections[node_1]

    def connect(self, node_1, node_2):
        """Draws an edge between the node at node_1 and the node at node_2"""
        self.connections[node_1].add(node_2)
        self.connections[node_2].add(node_1)

And while I was at it, I promoted your comments to proper docstrings. Now you can do help(Graph.connect) in an interactive session.

I also changed the name of the internal representation to self.connections.


Harnessing hashCode as JAXB @XmlID in order to use it with @XmlIDREF I have a class Fighter in a software for planning boxing events.  I implemented its hashCode() and equals() since I collect them in various data structures in many places.

Now I want to persist specific planned boxing events which themselves contain the same Fighters  in different lists.  I am using JAXB for this purpose.

In order not to have duplication in the XML nodes I made use of @XmlID and @XmlIDREF such that only once the whole Fighter data is stored – but referenced in other places. The code for the id is simple and it works as expected:

@XmlID
@XmlAttribute
public String getId() {
    return Integer.toString(hashCode());
}

(I was also searching for an auto-mechanism to generate those ids by JAXB but could not find anything which would be simpler as the solution above. Please tell me, if there is such a solution!)

The hashCode method looks as follows:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result =
        prime * result + ((firstNameProperty == null) ? 0 : firstNameProperty.get().hashCode());
    result = prime * result + ((lastNameProperty == null) ? 0 : lastNameProperty.get().hashCode());
    result = prime * result + ((genderProperty == null) ? 0 : genderProperty.get().hashCode());
    result = prime * result + ((birthdayProperty == null) ? 0 : birthdayProperty.get().hashCode());
    result = prime * result + ((clubProperty == null) ? 0 : clubProperty.get().hashCode());
    long temp;
    temp = Double.doubleToLongBits((weightProperty == null) ? 0 : weightProperty.get());
    result = prime * result + (int) (temp ^ (temp >>> 32));
    result = prime * result + ((winsProperty == null) ? 0 : winsProperty.get());
    result = prime * result + ((lossesProperty == null) ? 0 : lossesProperty.get());
    result = prime * result + ((drawsProperty == null) ? 0 : drawsProperty.get());
    return result;
}

And the class member variables which are used here:

private StringProperty firstNameProperty;
private StringProperty lastNameProperty;
private ObjectProperty<Gender> genderProperty;
private StringProperty clubProperty;
private ObjectProperty<LocalDate> birthdayProperty;
private DoubleProperty weightProperty;
private IntegerProperty winsProperty;
private IntegerProperty lossesProperty;
private IntegerProperty drawsProperty;

My rationale was that hashCode() would give me a unique id for every fighter and is already there.

What do you think about that? Are there any drawbacks I just don't see? Is it common to do it this way? Is there a far better solution?

Thanks for including the hashCode() method. As I suspected, the purpose of the hashCode method is to fulfil the equals/hashCode contract, and is not suitable for being an ID. For example, by changing the number of wins, you change the hashCode, and by proxy you change the player's ID.

If you want the ID to be a temporary thing that is only constant for the short time that the player is constant, then your solution is OK. If you want the ID to last through a persist/restore cycle, or even from one moment to the next when they pee .... and their weight changes, then you need a different system.

In addition, while you claim your hashCode is unique, it is not technically true. The chances of their being a duplicate are remote, but it is possible that two players will have the same hashCode, and hence the same ID.

In reality, your system is not reliable, and the best solution would be to create an externally managed ID for each player - a record number from a database, a unique counter, or something.


Could this depth system for a game be improved? I am still new to C++ and don't have a great insight on my coding yet, so I would be very grateful to anyone and everyone that gives advice.

Also, this code is meant to: keep all of my objects in an ordered fashion based on depth. I have a couple functions that allow for easy management and I made object friends with the depth manager because I only want the depthManager to have control over each objects idDepth and depth which are two different things.

The reason I need a depth system is because I need to have objects execute there code in an orderly fashion, and I also need to have control of what objects are drawn first to last.

This class has been tested and works as expected.

Stay up to date with this project on GitHub.com

Abstract object class:

class object{
    // Placement Data
        unsigned int depth, idDepth, idObject, idMain;

    // Friends
        friend class depthManager;
        friend class objectManager;
protected:
    unsigned int getDepthId(){ return idDepth; }
public:
    virtual void update() = 0;
    virtual void draw() = 0;
    unsigned int getDepth() { return this->depth; }
};

note: I have each object handle its own update and draw events for easier design. I'm mainly asking on approval for the depth system.

depthManager class

class depthManager{
private:
    std::map<unsigned, std::vector<object*>* > objectMap;

    void changeListPlacement( unsigned int depth, unsigned int position, int change);
public:
    void objectAdd( unsigned int depth, object* obj);
    void objectRemove( object* obj );
    void objectMove( unsigned int depth, object* obj );
};

depthManagers Functions:

void depthManager::objectAdd(unsigned int depth, object *obj)
{
    obj->depth = depth;
        // Check if depth key existant
        if ( objectMap.find( depth ) != objectMap.end() )
        {
            std::vector< object* >* &refVec = objectMap[ depth ];
            refVec->push_back( obj );
            obj->idDepth = (unsigned)(int)refVec->size() - 1;
        }
        else // Add new Key
        {
            objectMap[ depth ] = new std::vector< object* >;
            std::vector< object* >* &refVec = objectMap[ depth ];
            refVec->push_back( obj );
            obj->idDepth = (unsigned)(int)refVec->size() - 1;
        }
}

void depthManager::changeListPlacement(unsigned int depth, unsigned int position, int change = -1)
{
    if ( objectMap.find( depth ) == objectMap.end() )
    {
        return;
    }

    std::vector<object*>* &refVec =  objectMap[ depth ];
    for( unsigned int i = refVec->size() - 1; i > position; i -- )
    {
        object* &pObj =  refVec->at( i );
        pObj->idDepth += change;
    }
}

void depthManager::objectRemove(object *obj)
{
    if (  objectMap.find( obj->depth ) == objectMap.end() )
    {
        std::cout << "ERROR DEPTH NOT FOUND \n" << std::flush ;
        return;
    }
    std::vector<object*>* &refVec =  objectMap[ obj->depth ];
    changeListPlacement( obj->depth, obj->idDepth);
    refVec->erase( refVec->begin() + obj->idDepth );
}

void depthManager::objectMove(unsigned int depth, object *obj)
{
    this->objectRemove( obj );
    this->objectAdd( depth, obj );
}

previous verions

Depth Manager Source Code 1

Some remarks to your current map-based implementation:

The idiomatic way of accessing an item in a map and adding it if not present usually goes like this:

if not map.contains(key)
    map[key] = new value

value = map[key]
... modify value

So objectAdd could be shortened:

obj->depth = depth;
// make sure we have an object vector for the given depth
if ( objectMap.find( depth ) == objectMap.end() )
{
    objectMap[ depth ] = new std::vector< object* >;
}

std::vector< object* >* &refVec = objectMap[ depth ];
refVec->push_back( obj );
obj->idDepth = (unsigned)(int)refVec->size() - 1;

In objectRemove it is apparently illegal to pass an object with a non-existent depth. Printing an error message to stdout is not the best way to handle an error like that. You should throw an appropriate exception (fail early is a valuable debugging tool) or allow it by ignoring invalid depths.
It is not imminently clear what objectMove exactly does based on its name and the names of its parameters. It looks like it moves an object to a different depth. So a better name and signature might be:

void depthManager::changeDepth(unsigned int newDepth, object *obj)

In class object the methods getIdDepth() and getDepth do not modify the object state so you should consider making them const (i.e. unsigned int getDepth() const { return this->depth; }).
I'm not 100% convinced of the idDepth property. It basically just reflects the current position of the object in the depth-list and you are writing a fair amount of boiler plate code to keep it that way. This increases the complexity of the class somewhat. I'd revisit the concept and check if I can't get by without it.


Generator function to enumerate files I want to implement a function that enumerates all files in directory. I think the function should

Return a Promise, because underlying readdir call is prefered over readdirSync.
Be a generator function, because checking statSync(...).isFile() might take some time and maybe, I will need only first few files...

So my attempt

import * as fs from 'fs';
import * as path from 'path';

function enumerateFiles(dir: string): Promise<IterableIterator<string>> {
    let result = function* (files: string[]): IterableIterator<string> {
        for (let enty of files) {
            let fullpath = path.join(dir, enty);

            if (fs.statSync(fullpath).isFile())
                yield fullpath;
        }
    };

    return new Promise<IterableIterator<string>>((resolve, reject) => {
        fs.readdir(dir, (err, files) => {
            if (err)
                reject(err);
            else
                resolve(result(files));
        });
    });
}

And usage

for (let file of await enumerateFiles(String.raw`C:\Windows\Web\Screen`))
    console.log(file);

// C:\Windows\Web\Screen\img100.jpg
// C:\Windows\Web\Screen\img101.jpg
// ...

What do you think? I'm really not sure about combining Promises with generator functions. Especially in this order...

for (let file of await enumerateFiles(String.raw`C:\Windows\Web\Screen`))

The await looks like a leaky abstraction. Could your generator naturally behave synchronously?  A quote from Exploring ES6

  22.1.5 Use case: receiving asynchronous data

  Generators can receive input from next() via yield. That means that you can wake up a generator whenever new data arrives asynchronously and to the generator it feels like it receives the data synchronously.


How parse nicely a string into three (or more) pieces? See, I have a file which consists of a bunch of lines like

NAME:0001;some text
ANOTHERNAME:000103;some more text
NEWNAME:42; blah blah

So what I need to do is to have a list of those names, list of numbers (IDs actually, so the order matters) and list of further comments. I wrote a code, which actually does work, but I'm afraid it's horrible and not pythonic at all.

reactions_file = open("reactions.txt","r")
lines = reactions_file.readlines()
reaction_names = []
reaction_other = []
reaction_IDs = []
reaction_notes = []
for line in lines:
    r_name = line.partition(":")[0]
    r_other = line.partition(":")[2]
    reaction_names.append(r_name)
    reaction_other.append(r_other)
for item in reaction_other:
    r_ID = item.partition(";")[0]
    r_note = item.partition(";")[2]
    reaction_IDs.append(r_ID)
    reaction_notes.append(r_note)
print(reaction_names)
print(reaction_IDs)
print(reaction_notes)
reactions_file.close()

How can it be changed to look less like written by newbie? :)

You can say:

>>> import re
>>> re.split('[:;]', 'NAME:0001;some text')
['NAME', '0001', 'some text']


Setting PHP variables for 2 years back and 2 years in the future The following code gets years (dates), 1 and 2 years back (for example 2017 - 2016) and 1 and 2 years into the future (for example 2019 - 2020). Now PHP is not my expertise so I would like to get some help cleaning this up.

Is there a different approach I should use when doing this?

//Filter jaren
$year = date("Y");
$yearBack = $year;
$yearBack--;
$yearDoubleBack = $yearBack;
$yearDoubleBack--;
$yearAhead = $year;
$yearAhead++;
$YearDoubleAhead = $yearAhead;
$YearDoubleAhead++;

Only three-four line code rquired for getting required result:-

<?php

$date = date("Y"); //current year

$date_range = range($date-2, $date+2);//get year range

//print_r($date_range); //print year range

echo implode(',',$date_range);//comma seperated date range

Output:- https://eval.in/944817


Detecting capturing moves that pawns can make, in both directions I have this function that contains two similar if statements that is kind of hard to re-factor.

I am saying this because these two share a significant portion of duplicated code, but because of the part where it differs slightly, like board[startX + 1][startY - 1] and board[startX - 1][startY - 1], I find it difficult to re-factor it efficiently.

In other words, I can surely re-factor this by creating another function that contains the common parts, but I am afraid of creating a few more if blocks inside that function and making the code dirtier.

Any advice for refactoring this kind of code?

public boolean hasCapturableEnemy(Piece[][] board, int startX, int startY, int endX, int endY) {

    //If the Pawn belong to the Upper Team (Faces downward)
    if(board[startX][startY] != null && board[startX][startY].getTeam() == Player.UP) {
        //If a Piece exists on a diagonally adjacent tile, return true
        if(startX - endX == -1 && Math.abs(startY - endY) == 1) {
            if( (board[startX + 1][startY - 1] != null && board[startX + 1][startY - 1].getTeam() != Player.UP) ||
                    (board[startX + 1][startY + 1] != null && board[startX + 1][startY + 1].getTeam() != Player.UP)) {
                return true;
            }
        }
    }

    if(board[startX][startY] != null && board[startX][startY].getTeam() == Player.DOWN) {
        //If the Pawn belongs to the Down Team (Faces upward)

        if(startX - endX == 1 && Math.abs(startY - endY) == 1) {
            //If a Piece exists on a diagonally adjacent tile, return true
            if( (board[startX - 1][startY - 1] != null && board[startX - 1][startY - 1].getTeam() != Player.DOWN) ||
                    (board[startX - 1][startY + 1] != null && board[startX - 1][startY + 1].getTeam() != Player.DOWN)) {
                return true;
            }
        }
    }

    return false;

}

In other words, I can surely re-factor this by creating another function that contains the common parts, but I am afraid of creating a few more if blocks inside that function and making the code dirtier.

Au contraire. If your refactoring is increasing the code complexity, you're not doing it right.

The refactoring I did in this answer has reduced maximum nesting to a single level.

Maybe some quick-fire observations about why your code was so complex:

You were pushing all your calculations into your array index, which caused you to have to repeat the same value+1 and value-1 statements over and over.
As you already acknowledged, you had copy/pasted code and only made minor alterations (turning a +1 into a -1 due to the different player teams).
Your variables names weren't really all that clear, nor clearly used. Even after having refactored it, I still have no clue what endX and endY were used for.

There are two "types" of refactoring:

Simplifying code by changing it while not making any functional difference.

A simple example would be seeing if(myBool == true) and changing it to if(myBool). It makes no functional difference, and therefore can be safely refactored.

Revisiting the code and redesigning it, so you can optimize it with knowledge you have now (but didn't have at the time).

This often happens when a problem is complex at the beginning, but after developing a solution, it looks so much easier in hindsight.

We're going to be doing the second type of refactoring here. Which means we'll start from scratch and build the requirements as they come.

Assumptions:

Arrays are 0-indexed (it's been a while since I did Java, I think that's the case?)
We're using screen coordinates:

Method signature

We want:

A boolean that tells us whether the pawn can capture an enemy.

We need to supply:

The specific pawn
Access to the game board for retrieving information.

Your code:

public boolean hasCapturableEnemy(Piece[][] board, int startX, int startY, int endX, int endY)

I've been looking at it for a while, and I genuinely have no idea why you are supplying endX and endY. My suggestion:

public boolean hasCapturableEnemy(Piece[][] board, int pawnX, int pawnY)

1 - Input validation

Let's store the pawn in its own variable, for ease of use:

Piece pawn = board[pawnX][pawnY];

Does the referenced position actually contain a pawn? As it stands, you're only really checking for null, so I'll do the same:

if (pawn == null)
    return false;

Notice that I inverted the logic. If the pawn does not exist, then we immediately return false. This helps reduce nesting, and you won't need to indent the subsequent code.

2 - Defining the possible capture regions

To help you simplify this, let's look at the row calculation and the column calculation separately:

Columns are easy: given that a pawn is standing in column X, the capture regions can be found in columns X-1 and X+1.
Importantly, this is true for both the UP and DOWN players!

int captureColumnLeft = pawnX - 1;
int captureColumnRight = pawnX + 1;

When the pawn is on column 0 or 7, it will only have one capture region. But we'll get to that later.

Rows, however, are a bit more complex. This is the first time we need to observe the team that this pawn belongs to. Given that a pawn is standing on row Y, its capture regions are found in row Y+1 for the UP player, but in row Y-1 for the DOWN player.

int captureRow;

if(pawn.getTeam() == Player.UP)
    captureRow = pawnY + 1;
else
    captureRow = pawnY - 1;

We don't need to exclude fringe cases. A pawn can never be at the end of the board (for either player), since it would then turn into another piece.

Now we've very easily defined a given pawn's capture regions:

Piece captureRegionLeft = board[captureColumnLeft][captureRow];
Piece captureRegionRight = board[captureColumnRight][captureRow];

The next step is checking to see if there is a capturable piece on any of the capture regions. As the logic is exactly the same for both regions, we'll put this in a new method.

Before we get to that, let's close our current method:

return CanCaptureAt(captureRegionLeft, pawn)
       || CanCaptureAt(captureRegionRight, pawn);

3 - Checking if a possible capture region contains a capturable piece

public boolean CanCaptureAt(Piece captureRegion, Piece pawn)
{

    // ...

}

The logic isn't all that hard:

If there is no piece in the capture region, we cannot capture anything in that region.

if(captureRegion == null)
    return false;
If there is a piece in the capture region, it must be of the opposing team. In other words, a piece is capturable if the teams are different:

return captureRegion.getTeam() != pawn.getTeam();

Combined:

public boolean hasCapturableEnemy(Piece[][] board, int pawnX, int pawnY)
{
    Piece pawn = board[pawnX][pawnY];

    if (pawn == null)
        return false;

    int captureColumnLeft = pawnX - 1;
    int captureColumnRight = pawnX + 1;

    int captureRow;

    if(pawn.getTeam() == Player.UP)
        captureRow = pawnY + 1;
    else
        captureRow = pawnY - 1;

    Piece captureRegionLeft = board[captureColumnLeft][captureRow];
    Piece captureRegionRight = board[captureColumnRight][captureRow];

    return CanCaptureAt(captureRegionLeft, pawn)
        || CanCaptureAt(captureRegionRight, pawn);
}

public boolean CanCaptureAt(Piece captureRegion, Piece pawn)
{
    if(captureRegion == null)
        return false;

    return captureRegion.getTeam() != pawn.getTeam();
}

Additionally

I said we still needed to exclude two fringe cases: if the pawn is on the leftmost column, it doesn't have a left capture region; and when it is on the rightmost column, it's doesn't have a right capture region.

This can be achieved by slightly reshuffling the code:

public boolean hasCapturableEnemy(Piece[][] board, int pawnX, int pawnY)
{
    Piece pawn = board[pawnX][pawnY];

    if (pawn == null)
        return false;

    int captureRow;

    if(pawn.getTeam() == Player.UP)
        captureRow = pawnY + 1;
    else
        captureRow = pawnY - 1;

    if(pawnX > 0) // == NOT in the leftmost column
    {
        int captureColumnLeft = pawnX - 1;
        Piece captureRegionLeft = board[captureColumnLeft][captureRow];

        if(CanCaptureAt(captureRegionLeft, pawn))
            return true;
    }

    if(pawnX < 7) // == NOT in the rightmost column
    {
        int captureColumnRight = pawnX + 1;
        Piece captureRegionRight = board[captureColumnRight][captureRow];

        if(CanCaptureAt(captureRegionRight, pawn))
            return true;
    }

    //Neither caption region registered a hit,
    //Therefore we cannot capture anything
    return false;
}

Footnotes

There is currently no check to see if the provided X/Y values are within the bounds of the board.
There is currently no check to see if the Piece at the provided X/Y coordinates is actually a pawn.


Password reveal functionality I have made a password reveal feature, however the code is duplicated. Essentially all I want to be able to improve the code, however I'm not exactly sure how I could do this, all I know is it would consist of some form of loop.

I would go straight to jQuery but there is no need in 2018.

This is my functionality markup for my HTML (it’s the same for the login page and modal):

<form action="/login" method="post">

        Username :
        <input class="input-field width-100" type="text" autocomplete="username" name="username" placeholder="Enter Your Username">

        Password :
        <input class="input-field width-100 password" data-js="viewShowPassword" type="password" autocomplete="current-password" name="password" placeholder="Enter Your Password">

            <input type="checkbox"/> Remember Me

            Show Password

        <button class="submit width-100 input-field text-white background-red--light" style="padding: 5px">Login</button>

</form>

And this is my JavaScript, which shows both the login page and login modal code to demonstrate what I have so far:

document.addEventListener("DOMContentLoaded", function(event) {

    var modalShowPassword = document.querySelector("[data-js=modalPasswordReveal]");
    var modalPassword = document.querySelector("[data-js=modalPassword]");

    if(modalShowPassword || modalPassword) {
        modalShowPassword.addEventListener("click", function (){
            if (modalPassword.type === "password") {
                modalPassword.type = "text";
            } else {
                modalPassword.type = "password";
            }
        });
    }

    var viewShowPassowrd = document.querySelector("[data-js=viewPasswordReveal]");
    var viewPassword = document.querySelector("[data-js=viewShowPassword]");

    if( viewShowPassowrd || viewPassword) {
        viewShowPassowrd.addEventListener("click", function (){
            if (viewPassword.type === "password") {
                viewPassword.type = "text";
            } else {
                viewPassword.type = "password";
            }
        });
    }
});

FYI I'm fairly new to the world of JavaScript so I'm not very good.

Before I comment on your implementation. Your code has a bug in it.

The code inside this if block:

if(modalShowPassword || modalPassword) {

will execute if either modalShowPassword or modalPassword is set but you really only want it to execute if both are set. You want to use the and (&&) operator like this:

if(modalShowPassword && modalPassword) {

With your code, think about what would happen if you were to have more (say 10) password boxes on your page? Would you repeat your code 10 times with different variables and different values for the data-js attribute? What I would suggest is to use something similar to the Bootstrap style (see how their modal dialogs work here https://getbootstrap.com/docs/4.1/components/modal/#via-data-attributes). There are two things to note. First they use the same data attribute for all instances even if there are multiple modals on the page. Secondly they do not apply an attribute to the modal form. They have two attributes on the toggle button, data-toggle defines the action while data-target tells the button what to show as a modal.

So a solution might look like:

<form>
    <input id="password1" type="password" autocomplete="current-password" name="password" placeholder="Enter Your Password">
    Show Password

    <input id="password2" type="password" autocomplete="current-password" name="password" placeholder="Enter Another Password">
    Show
</form>


Project Euler 50 in Python Project Euler, problem #50:

  The prime 41, can be written as the sum of six consecutive primes:

  41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive
  primes that adds to a prime below one-hundred.

  The longest sum of consecutive primes below one-thousand that adds to
  a prime, contains 21 terms, and is equal to 953.

  Which prime, below one-million, can be written as the sum of the most
  consecutive primes?

I came up with this code, but it only works decently for primes below ten thousand.

Any ideas on how to optimize it?

from pyprimes import *

def sequence_exists(l,ls,limit = 100):
    for x in range(0,len(ls)-l):
        if x+l > len(ls): return False
        if any (ls[i] > limit/6 for i in range(x,x+l,1)) :
            return False
        test_sum = sum(ls[x:x+l:1])
        if (test_sum <limit) and is_prime(test_sum) :
            return True
    return False

def main():
    n = prime_count(10000)
    prime_list = list(nprimes(n))
    l = 6
    for x in range(6,len(prime_list)):
        if sequence_exists(x,prime_list,10000):
            l=x
    print l

if __name__ == '__main__':
    main()

Don't import 'wildcards'

Especially if the module is not part of the Standard Library people will be confused and not understand where the function is coming from. You can cut down typing as follows:

 import pyprimes as pr

Use longer names

def sequence_exists(l,ls,limit = 100):

In the above l and ls tell nothing to the reader.


"Intelligent" removal of carriage returns that preserves paragraph breaks, headings, etc It's often useful to strip carriage returns out of a plain text document, for example when copying and pasting into a field that automatically wraps lines.  However, it's usually a good idea to leave some of the carriage returns in — most obviously at paragraph breaks, but also around bullet lists, section headings, etc.  So one needs an algorithm to decide which carriage returns to retain.

In my attempt to address this problem, I came up with the following:

shouldMerge::[Char]->[Char]->Bool
shouldMerge "" _ = False
shouldMerge _ "" = False
shouldMerge _ nextline | (not . isAlphaNum . head) nextline = False
shouldMerge line nextline | length (line ++ " " ++ (head . words) nextline) <
                              length nextline = False
shouldMerge _ _  = True

where shouldMerge is a function that attempts to guess whether a line should be merged with its successor.  The rules state, roughly, 1) never merge blank lines; 2) don't merge with a line beginning with a non-alphanumeric character; and 3) if placing the first word on the next line at the end of the current line would result in a line shorter than the next line, don't merge, as the current line was probably cut short intentionally (catches things like section headings.)  This set of rules "seems to work" :) much of the time.

My question is: how would you improve on this algorithm (perhaps by considering more than one line of text at a time?)

Two things:

Try using String instead of [Char], it reads a lot easier (imho).
Don't use head, use pattern matching instead. It reads better, and it's good practice, because if it passes an empty list you will get an error (though you will not encounter that in this program, since you already check for empty lists).

If you wanted to have your program consider multiple lines, a quick and dirty solution would be something like this:

function :: [String] -> [Bool]
function [] = []
function [line1,line2] = [(shouldMerge line1 line2)]
function (line1:line2:morelines) = [(shouldMerge line1 line2)] ++ function (line2:morelines)

NOTE: I haven't tested the above code for bugs.

Another solution would be to make shouldMerge recursive, with a type of [String] -> [Bool].


Retrieving lists of consecutive capitalised words from a list Ok, so given the string:

s = "Born in Honolulu Hawaii Obama is a graduate of Columbia University and Harvard Law School"

I want to retrieve:

[ ["Born"], ["Honolulu", "Hawaii", "Obama"], ["Columbia", "University"] ...]

Assuming that we have successfully tokenised the original string, my first psuedocodish attempt was:

def retrieve(tokens):
    results = []
    i = 0
    while i < len(tokens):
        if tokens[i][0].isupper():
            group = [tokens[i]]
            j = i + 1
            while i + j < len(tokens):
                if tokens[i + j][0].isupper():
                    group.append(tokens[i + j])
                    j += 1
                else:
                    break
        i += 1
    return results

This is actually quite fast (well compared to some of my trying-to-be-pythonic attempts):

  Timeit: 0.0160551071167 (1000 cycles)

Playing around with it, the quickest I can get is:

def retrive(tokens):
    results = []
    group = []
    for i in xrange(len(tokens)):
        if tokens[i][0].isupper():
            group.append(tokens[i])
        else:
            results.append(group)
            group = []
    results.append(group)
    return filter(None, results)

  Timeit 0.0116229057312

Are there any more concise, pythonic ways to go about this (with similar execution times)?

A trivial optimisation that iterates on the tokens instead of by index (remember that in Python lists are iterables, it's unPythonic to iterate a list by index):

def retrieve(tokens):
    results = []
    group = []
    for token in tokens:
        if token[0].isupper():
            group.append(token)
        else:
            if group:  # group is not empty
                results.append(group)
            group = []  # reset group
    return results

A solution like @JeremyK's with a list comprehension and regular expressions is always going to be more compact. I am only giving this answer to point out how lists should be iterated.