Python file modifying script with focus on OOP

PEP-8

ClassNames should be BumpyWords; snake_case is used for things like method_names and variable_names.  So you class should be:

class VisFileTools:
    ...

Unnecessary __init__ method

This method does nothing; it may safely be omitted.

    def __init__(self):
        pass

Public / Private

remove_jedec_line looks like a private method, used by the remove_jedecs_file method.  If remove_jedec_line is not supposed to be used by actors outside of the class, it should be prefixed with a leading underscore:

    def _remove_jedec_line(self, inputline):
        ...

Garbage Collection

temp_data = ""    # Empties memory

This is unnecessary.  The variable is about to go out of scope, which will naturally release the memory it is holding.

Stop Writing Classes

See the video Stop Writing Classes

Your class is unnecessary.  It has no data members.  It has one public method.  It should just be a function.

Simplified code

Here is a function version of your code (untested):

def remove_jedecs_file(path_input_file: str, path_output_file: str) -> None:
    """
    Read `path_input_file`, copying each line to `path_output_file`.
    Once the start of components is reached (indicated by a line containing "COMP"),
    the last "word" (jedec) of each line is removed.
    """

    def remove_jedec_line(input_line: str) -> str:
        return " ".join(input_line.split(" ")[:-1]) + "\n"

    with open(path_input_file) as file, open(path_output_file, "w") as write_file:
        comp_line_reached = False

        for line in file:
            if comp_line_reached:
                line = remove_jedec_line(line)
            else:
                comp_line_reached = "COMP" in line

            write_file.write(line)

Notes:

Type-hints (Python 3.6+) have been added to the function (: str and -> None)
A """docstring""" has been added to describe the function.
A nested function is used for remove_jedec_line(), making it "private".
[:-1] returns all but the last element in a list, which is simpler than using del input_line_split[-1].
Lines are not being accumulated in temp_data.  Instead, lines are written out immediately after being read in, which is a much lighter load on memory, and avoid \$O(N^2)\$ string concatenation.
"COMP" in line is a "slow" search operation, looking for that substring in the line string.  When found, it sets a flag.  Here, once the flag is set, we can skip the slow substring search.  But I'm introducing a slight change in behaviour: if subsequent lines also contain "COMP", the OP version would not do the remove_jedec_line() transformation where as mine will.  The assumption here is that "COMP" only appears once.


Cleaning and simplifying function that returns a number based on certain values

some style issues to consider:

1) it's conventional to use ALL_CAPS for constants such as 'supers' and w1, etc.

2) for long term maintenance, it's also a good idea to use longer more descriptive names - not only is this hard to parse for the uninitiated, it's also prone to hard-to-catch typos which will be hard to spot.  It's especially bad when you do multiple assignments on a single line.

3) supers could be a dictionary

4) you can simplify the range logic by excepting for incomplete groups:

<snip>
enter code here
group = group.replace("-", "q")
fnv, lnv = None
try:
   fnv = group[:5]
   lnv = group[6:9]
except IndexError:
   raise ValueError "group string %s is malformed"
fn_value = int(fnv, 36)
ln_value = max(int(lnv, 36), 1000) or 1000

5) maxNum is always the same, it should be a constant or a cached module-level field:

informative_name = sum(map(lambda x: x[1], supers))

at the top will execute at module load and wont need to be recalced for every call.


Java job responsible for processing file statements

Here's the best I think we can get it without actually knowing what your code is for.

public class StatementJob {
    public static final Logger LOGGER = LoggerFactory.getLogger(StatementJob.class);

    public static final String JOB_IS_DISABLED = "Uploads statement job is disabled and will not run";
    public static final String UNABLE_TO_CONTINUE = "Unable to continue";

    private final Configuration jobConfiguration;
    private final Log log;

    public StatementJob(JobConfiguration jobConfiguration) {
        this.jobConfiguration = jobConfiguration;
        this.log = new JobLog();
    }

    public Log execute() {
        LOGGER.debug("Stating uploading statements");

        final JobProperties properties;
        try {
            properties = jobConfiguration.loadProperties();
        } catch (BadConfigurationException e) {
            return log.addError(e.getMessage());
        }

        if (!properties.isRunJob()) {
            return log.addSuccess(JOB_IS_DISABLED);
        }

        Employee employee = Employee.load(properties.getStatementUploader());
        FileStatements fileStatements = new Statements(properties.getDirectories());

        FatalConsumer<WipStatement> wipConsumer = wip -> {
            try {
                new UploadableDocument(employee, wip).upload();
                fileStatements.moveToArchiveLocation(wip);
            } catch (FailedToUploadDocumentException e) {
                log.addError(e.getMessage());
                fileStatements.moveToErrorLocation(wip);
            }
        };
        FatalConsumer<InboundStatement> inboundConsumer = inbound -> {
            fileStatements.moveToWipLocation(inbound);
            fileStatements.getWipStatements().forEach(wipConsumer);
        };

        fileStatements.getInboundStatements().forEach(inboundConsumer);

        return log;
    }

    @FunctionalInterface
    public interface FatalConsumer<T> extends Consumer<T> {
        void fatalAccept(T t) throws UnableToMoveFileToDirectoryException, UnableToReadFileException;

        @Override
        default void accept(T t) {
            try {
                fatalAccept(t);
            } catch (UnableToMoveFileToDirectoryException | UnableToReadFileException e) {
                LOGGER.error(UNABLE_TO_CONTINUE, e);
            }
        }
    }
}

Changelog:

Separate constants to be grouped by category. The logger typically is flush with the class declaration while other constants are grouped below it.
No need to have the extra space after the start of the execute method
Use more accurate log levels. Specifically, you overuse "info". Refer to this article about different things to avoid when logging effectively.

"DEBUG is intended for messages that could be useful in debugging an issue (ex: method execution started)"

Use line breaks in fluent calls only when it becomes too long, and then only when you have created your stream/data-structure. Specifically, there's no need to have a line break after fileStatements
You have a lot of excess indentation and repeated code. Specifically, all of times you catch an exception, log it, and then immediately rethrow it. My changes above resolve that.
If you are going to statically define the document uploader to be an Employee, naming the variable documentUploader instead of employee is kind of pointless.

I would highly recommend moving FatalConsumer and each of the non-logging constants you have to their own files. Besides that, this is about as good as you're going to get imo. Hope this helps!


Copying a range from one file to another

I doubt this is how you've actually declared arrays:

dim vArr1 as array
Dim vArr as array

That would be

Dim vArr1() As String
Dim vArr() As String

But nevermind that: you need to use more meaningful names. If they're folder names, consider calling them something like folders or folderNames - and avoid arbitrary Hungarian-like prefixes such as v.

This is why multiple declarations in the same instruction should be avoided:

Dim fileName1, Pathname1 As String

Do you think fileName1 is a String? It's not. It's implicitly declared as Variant, because As String only applies to Pathname1!

Indentation is off here, and only looks the way it does because WB1 has 3 characters (and it's another bad name):

Set WB1 = Workbooks.Open(Pathname1 & vFile & "\" & fileName1)
    WB1.Application.ScreenUpdating = False
    WB1.ActiveSheet.Range("M1:M30").Copy
    WB1.Close (False)

Should be:

Set WB1 = Workbooks.Open(Pathname1 & vFile & "\" & fileName1)
WB1.Application.ScreenUpdating = False
WB1.ActiveSheet.Range("M1:M30").Copy
WB1.Close (False)

Note that your usage of parenthesis in method calls is going to cause a bug one day or another, when you pass an argument like that into a ByRef parameter.

How so? Well, the "normal" VBA syntax for passing arguments is like this:

WB1.Close False

By doing this:

WB1.Close (False)

You are forcing the argument to be passed ByVal, overriding the procedure's signature that might have said ByRef. Of course it doesn't really matter here for a Boolean literal..

Workbooks.Open(Pathname1 & vFile & "\" & fileName1)

...or even for a String literal. But one day you're going to want to pass an argument into a ByRef parameter, and learn the hard way that parentheses should be dropped when doing procedure calls. They're only needed for function calls.

The main reason why your code is slow is because you're opening and closing workbooks - there's not really anything to do to speed that up unfortunately.

Except perhaps...

WB1.Application.ScreenUpdating = False

Take that part out of the loop, and turn off screen updating all the while.

Application.ScreenUpdating = False

Now, whenever you turn off screen updating, you need to turn it back on when you're done, and you need to handle runtime errors and make sure you're turning it back on even when an error breaks you out of the code. You're accessing the file system here, so you have to handle runtime errors.

See this post for how to properly handle errors in VBA.


Add a newline to a String if not empty in Java

Every key-value-pair needs to have a newline appended after it, though not if it is the last one.

So are you interested to know how to concatenate Strings together using \n as a delimiter, or are you still interested to know how can you append \n to a non-empty String? Both have different implementations...

(using Java 8 where applicable below)

\n as a delimiter:

String toString = organizationMap.entrySet().stream()
                    .map(ThisClass::constructStringFromEntry)
                    .filter(v -> !v.isEmpty())
                    .collect(Collectors.joining("\n"));

\n as an optional suffix:

StringBuilder builder = new StringBuilder();
Iterator<Entry<String, String>> iterator = organizationMap.entrySet().iterator();
while (iterator.hasNext()) {
    Entry<String, String> entry = iterator.next();
    // some other processing...
    // time to append the current entry to builder
    String entryString = constructStringFromEntry(entry);
    builder.append(entryString);
    if (!entryString.isEmpty() && iterator.hasNext()) {
        builder.append('\n');
    }
}
String toString = builder.toString();

I am suggesting the usage of a StringBuilder here since the kind of String concatenation in a loop is usually structured, hence it can be better done relying on that rather than +. Usually, I will prefer the enhanced for-loop over using an explicit Iterator, but its usage here is required in order to avoid adding the last \n.


Initializing private HashMap<Character, HashMap> root; at declaration will simplify your code

public class Trie {
    private HashMap<Character, HashMap> root = new HashMap<>();
    private final Character END_CHARACTER = '$';

    public Trie() {}

    public Trie(String s) {
        add(s);
    }

    public Trie(Collection<String> collection) {
        for (String s : collection) {
            add(s);
        }
    }

    public void add(String s) {
        HashMap<Character, HashMap> node = root;
        for (int i = 0; i < s.length(); i++) {
            Character character = s.charAt(i);
            if (!node.containsKey(character)) {
                node.put(character, new HashMap<Character, HashMap>());
            }
            node = node.get(character);
        }
        node.put(END_CHARACTER, new HashMap<>());
    }

    public boolean contains(String s) {
        HashMap<Character, HashMap> node = root;
        for (int i = 0; i < s.length(); i++) {
            Character character = s.charAt(i);
            if (node.containsKey(character)) {
                node = node.get(character);
            } else {
                return false;
            }
        }
        return node.containsKey(END_CHARACTER);
    }
}

From whats-wrong-with-overridable-method-calls-in-constructors

  Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the @Override is invoked, the state of the object may be inconsistent and/or incomplete.

This having in mind we will refactor the class, to add a private internalAdd() method which we call from the constructor and the public add() methods

public class Trie {
    private HashMap<Character, HashMap> root = new HashMap<>();
    private final Character END_CHARACTER = '$';

    public Trie() {}

    public Trie(String s) {
        internalAdd(s);
    }

    public Trie(Collection<String> collection) {
        for (String s : collection) {
            internalAdd(s);
        }
    }

    public void add(String s) {
        internalAdd(s);
    }

    private void internalAdd(String s) {
        HashMap<Character, HashMap> node = root;
        for (int i = 0; i < s.length(); i++) {
            Character character = s.charAt(i);
            if (!node.containsKey(character)) {
                node.put(character, new HashMap<Character, HashMap>());
            }
            node = node.get(character);
        }
        node.put(END_CHARACTER, new HashMap<>());
    }

    public boolean contains(String s) {
        HashMap<Character, HashMap> node = root;
        for (int i = 0; i < s.length(); i++) {
            Character character = s.charAt(i);
            if (node.containsKey(character)) {
                node = node.get(character);
            } else {
                return false;
            }
        }
        return node.containsKey(END_CHARACTER);
    }
}

but we can do better.. let us take a look at internalAdd()

private void internalAdd(String s) {
    HashMap<Character, HashMap> node = root;
    for (int i = 0; i < s.length(); i++) {
        Character character = s.charAt(i);
        if (!node.containsKey(character)) {
            node.put(character, new HashMap<Character, HashMap>());
        }
        node = node.get(character);
    }
    node.put(END_CHARACTER, new HashMap<>());
}

If node.isEmpty() we won't need to check if (!node.containsKey(character)) anymore.
Also if (!node.containsKey(character)) evaluates one time to true, we won't need to check this anymore. Let us add a new method:

private void internalAdd(String s, HashMap<Character, HashMap> node) {
    for (int i = 0; i < s.length(); i++) {
        Character character = s.charAt(i);
        node.put(character, new HashMap<>());
        node = node.get(character);
    }
}

and call it

private void internalAdd(String s) {
    HashMap<Character, HashMap> node = root;
    for (int i = 0; i < s.length(); i++) {
        Character character = s.charAt(i);
        if (node.isEmpty() || !node.containsKey(character)) {
            internalAdd(s.substring(i), node);
            break;
        }
        node = node.get(character);
    }
    node.put(END_CHARACTER, new HashMap<>());
}

But wait, we can do even better, as node.isEmpty() should also be used in the contains() method

public boolean contains(String s) {
    HashMap<Character, HashMap> node = root;
    for (int i = 0; i < s.length(); i++) {
        if(node.isEmpty()){
            return false;
        }
        Character character = s.charAt(i);
        if (node.containsKey(character)) {
            node = node.get(character);
        } else {
            return false;
        }
    }
    return node.containsKey(END_CHARACTER);
}

Finished ? No, we still can do better. As the passed String parameters won't be changed, let us make them final the same is true for the root field. Also as janos has answered

  use interface types instead of the implementation

Putting altogether

public class Trie {

    private final Map<Character, HashMap> root = new HashMap<>();
    private final Character END_CHARACTER = '$';

    public Trie() {
    }

    public Trie(final String s) {
        internalAdd(s);
    }

    public Trie(final Collection<String> collection) {
        for (String s : collection) {
            internalAdd(s);
        }
    }

    public void add(final String s) {
        internalAdd(s);
    }

    private void internalAdd(final String s) {
        Map<Character, HashMap> node = root;

        for (int i = 0; i < s.length(); i++) {
            Character character = s.charAt(i);
            if (node.isEmpty() || !node.containsKey(character)) {
                internalAdd(s.substring(i), node);
                break;
            }
            node = node.get(character);
        }
        node.put(END_CHARACTER, new HashMap<>());
    }

    private void internalAdd(final String s, Map<Character, HashMap> node) {
        for (int i = 0; i < s.length(); i++) {
            Character character = s.charAt(i);
            node.put(character, new HashMap<>());
            node = node.get(character);
        }
    }

    public boolean contains(final String s) {
        Map<Character, HashMap> node = root;

        for (int i = 0; i < s.length(); i++) {
            if (node.isEmpty()) {
                return false;
            }
            Character character = s.charAt(i);
            if (node.containsKey(character)) {
                node = node.get(character);
            } else {
                return false;
            }
        }
        return node.containsKey(END_CHARACTER);
    }
}


Angular wrapper for SignalR event aggregator

Hmm... interesting use of run + $rootScope, but I would avoid it primarily because of $rootScope. It's essentially the "global space" of an Angular app. The only legit use I see for it is attaching event listeners ($rootScope.$on), and for broadcasting events ($rootScope.$emit).

As an alternative, you could wrap your event relay in a factory.

As a factory, the dependency is explicit. The dependent knows it's there and Angular will throw if the dependency is missing on initialization, unlike $rootScope where it only throws when you use it.
Factories are singletons. You don't have to worry about checking and using the existing or create a new one.
You're not polluting the $rootScope nor depending on something that might not be there or have been overridden by something in a lower, enclosing scope. This is a headache to debug, especially without tools like Batarang or ngInspector.

Additionally, you might also want to put your event names in a constant. That way, you have a global lookup of event names, and you won't be hardcoding string literals all over the app.

Here's an example of how it would look like as a factory (using implicit dependency injection syntax for brevity).

angular.module('SignalrModule', []);
  .constant('SIGNALR_EVENTS', {
    FOO_EVENT: 'fooevent',
    BAR_EVENT: 'barevent',
  })
  .factory('SignalrFactory', function(){
    return {
      publish: function(){...},
      subscribe: function(){...},
      unsubscribe: function(){...},
    };
  });

angular.module('app', ['SignalrModule'])
  .controller('MyController', function(SignalrFactory, SIGNALR_EVENTS){
    SignalrFactory.subscribe(SIGNALR_EVENTS.FOO_EVENT, function(){
      // on foo event
    });
  });

Now I did mention that angular has a built-in pub-sub system. We can just hook on to it so your controllers will simply use regular events over $rootScope (we're not adding stuff to $rootScope, just making it a relay for events). Not sure of the following works, but the concept is there.

angular.module('SignalrModule', []);
  .constant('SIGNALR_EVENTS', {
    FOO_EVENT: 'fooevent',
    BAR_EVENT: 'barevent',
  })
  .run(function($rootScope, SIGNALR_EVENTS){

    // Iterate through our registry of events
    Object.keys(SIGNALR_EVENTS).forEach(function(eventName){

      // Relay angular events to signalr over $rootScope
      $rootScope.$on(SIGNALR_EVENTS[eventName], function(){
        signalR.eventAggregator.publish(SIGNALR_EVENTS[eventName]);
      });

      // Relay signalr events to angular over $rootScope
      signalR.eventAggregator.subscribe(SIGNALR_EVENTS[eventName], function(e) {
        $rootScope.$emit(SIGNALR_EVENTS[eventName], e);
      });
    });

  });

angular.module('app', ['SignalrModule'])
  .controller('MyController', function($rootScope, SIGNALR_EVENTS){

    // Using regular angular-ish emit and on

    $rootScope.$emit(SIGNALR_EVENTS.FOO_EVENT, { foo: 'data' });

    $rootScope.$on(SIGNALR_EVENTS.BAR_EVENT, function(){
      // bar event emitted somewhere
    });
  });


You can use the its syntax:

require "spec_helper"

describe InvoiceMailer do
  let(:user) { create(:user) }
  let(:student) { create(:student, user: user) }
  let(:body) { "And I for one will join with anyone, don't care what color you are. As long as you want change this miserable condition that exists on this earth." }

  describe "issue" do
    subject { InvoiceMailer.issue(student, body) }

    its(:subject) { should eq "New Invoice!" }

    its(:to) { should eq [student.user.email] }

    its(:from) { should eq ["info@test.com"] }
  end

  describe "rescind" do
    subject { InvoiceMailer.rescind(student, body) }

    its(:subject) { should eq "Invoice Rescinded!" }

    its(:to) { should eq [student.user.email] }

    its(:from) { should eq ["info@test.com"] }
  end

end

You can further DRY it up using example groups

describe InvoiceMailer do
  let(:user) { create(:user) }
  let(:student) { create(:student, user: user) }
  let(:body) { "And I for one will join with anyone, don't care what color you are. As long as you want change this miserable condition that exists on this earth." }

  shared_examples_for "outgoing mail" do |method, mail_subject|
    subject { InvoiceMailer.send(method, student, body) }

    its(:subject) { should eq mail_subject }

    its(:to) { should eq [student.user.email] }

    its(:from) { should eq ["info@test.com"] }
  end

  describe "issue" do
    it_should_behave_like "outgoing mail", :issue, 'New Invoice!'
  end

  describe "rescind" do
    it_should_behave_like "outgoing mail", :rescind, 'Invoice Rescinded!'
  end
end


You can try

String string = "asdf";
byte[] result = new byte[100];
System.arraycopy(string.getBytes(), 0, result, 100 - string.length(), string.length());


Read about the with statement and ALWAYS use it with file operations

with open( somefilename, 'rb' ) as source:
    reader = csv.reader( source )
    for row in reader:
       etc.

That guarantees that the file is closed and all OS resources released.


Function which returns the smallest / largest numbers in a nested array structure

I shoudn't be able to think to this elegant and concise solution by myself! Notably because till now I didn't pay great attention to some of the acute features of JS.

So it was for me the opportunity to examine them deeper. From this I notice a possible little improvement, by slightly reducing the code, like this:

function getExtrema(structure, funct) {

  var ret = structure.map(function(value) {
    if (Array.isArray(value)) {
      return funct(...value);
    }
  });

  return ret;
}

Here is the working modified example: http://codepen.io/anon/pen/obYMmQ?editors=101.


Get Elapsed Time as Human Friendly String

Does this cover all possible use cases?

Maybe, but it doesn't calculate timespan components (year, month, etc) exactly.

  Is it done optimally in the least lines of code?

Probably no.
You could generalize check of different TimeSpan elements using the following approach:

private static string GetElapsedTime(DateTime datetime)
{
    TimeSpan ts = DateTime.Now.Subtract(datetime);

    // The trick: make variable contain date and time representing the desired timespan,
    // having +1 in each date component.
    DateTime date = DateTime.MinValue + ts;

    return ProcessPeriod(date.Year - 1, date.Month - 1, "year")
           ?? ProcessPeriod(date.Month - 1, date.Day - 1, "month")
           ?? ProcessPeriod(date.Day - 1, date.Hour, "day", "Yesterday")
           ?? ProcessPeriod(date.Hour, date.Minute, "hour")
           ?? ProcessPeriod(date.Minute, date.Second, "minute")
           ?? ProcessPeriod(date.Second, 0, "second")
           ?? "Right now";
}

private static string ProcessPeriod(int value, int subValue, string name, string singularName = null)
{
    if (value == 0)
    {
        return null;
    }
    if (value == 1)
    {
        if (!String.IsNullOrEmpty(singularName))
        {
            return singularName;
        }
        string articleSuffix = name[0] == 'h' ? "n" : String.Empty;
        return subValue == 0
            ? String.Format("A{0} {1} ago", articleSuffix, name)
            : String.Format("About a{0} {1} ago", articleSuffix, name);
    }
    return subValue == 0
        ? String.Format("{0} {1}s ago", value, name)
        : String.Format("About {0} {1}s ago", value, name);
}


Shutdown method in queue implementations

My immediate thought is that this is an unacceptable implementation.  In particular, you seem to be trying to shutdown the threads accessing the queue by signally conditions, which I think confuses things badly.

See Concurrent Programming in Java, Second Edition by Doug Lea -- especially Chapter 3 ("State Dependence").

Consider this use case: you have a service, with multiple publishers (Runnables) and consumers (also Runnables); publishers offer items to the queue, consumers take items from it.  There's a UI, with a big red SHUTDOWN button on it.  When the user hits that button, what does the user want?

You seem to be implementing the idea that the user wants to shut down the queue.  But I put it to you that it's more accurate that the user wants to shut down the service itself.  The service itself maintains its own shutdown state, which the runnables can access.  Invoking service shutdown then does two things - (1) it sets the shutdown flag, so that the producer and consumer flags can see the change, and (2) it interrupts the producers and consumers, so that they look at the shutdown flag.

So the usual idiom would be to run the publishers and consumers in an ExecutorService, and after the shutdown flag has been set, ExecutorService.shutdownNow() would be invoked to signal the interruption to the running threads.  The threads that are parked on your conditions (queueNotFull.await()) throw InterruptedExceptions, and the handlers for these exceptions can then check the shutdown flag and do the right thing.

Condition.signalAll doesn't interrupt() the threads, it just gets them contending on the lock again.  When they get the lock, they just return from await; which means they check the while condition, and then put themselves back to sleep (Condition.await) because it is still true.

In short, Locks and Conditions are for co-ordination; if you are trying to implement cancellation, you should be using interrupts.


Few problems here.

Fragility and possible inefficiency by returning {it} rather than true
Iterating over the collection more often than is necessary (even though the later iterations may be over smaller sets).
Duplication of the same pattern

Point 1: Fragility

Just return true (oh, and not { true }).  That's what you want.  By returning the object you risk some odd circumstance where the object evaluates to false.  Why expose yourself to that risk?  And returning true is just cheaper.

Point 2: Repeated iteration

Each call to findAll is returning a new collection, which you iterate over with the next call.  That's a waste.  You can do it with one findAll and one closure.  The simplest (and most naive) way to do that would be this:

def requests = Request
    .list()
    .findAll { (exportFrom ? it.tsCreated.millis >= exportFrom.millis : true)
        && (exportTo ? it.tsCreated.millis <= exportTo.millis : true)
        && (clientId ? it.resolvedClient?.clientId == clientId : true)
        && (params.exportType ? it.typeName == params.exportType : true)
        && (params.exportStatus ? it.status.toString() == params.exportStatus : true)
        && true }

That will do just what your code does only without creating four intermediate copies of the list.  It is, however, ugly.  So one approach would be to turn each of those criteria into a function which takes a parameter and returns true or false.  So you would have

def requests = Request
    .list()
    .findAll { cond1(it) && cond2(it) && cond3(it) && cond4(it) && cond5(it) }

Which is at least cleaner.  However, let's consider

Point 3: Duplication of a pattern

You have a set of basic conditions.  Each, if true, has a matching predicate with which you test the list item for validity.  If the condition is not valid/present, you accept the list item.  So...

Imagine you create a Criteria class.  It should have two properties

criterion: the condition which, if true, requires a list element to be tested.  Should probably be a closure.
predicate: the test (another closure) to apply to the list element

The Criteria class should also have a reject method which might look like this

    boolean reject (Object item) {
        if (this.criterion(item)) ! this.predicate(item) else false
    }

(I used Object because I'm not sure what type is actually in your list)

Now you can create a list of Criteria objects, each containing a criterion and a matching test.  Lets say you call it criteriaList.  Now the main bit of code can look like this:

def requests = Request
    .list()
    .findAll { x -> ! criteriaList.find { c -> c.reject(x) } }

If none of the criteria objects reject the item, then the find call returns null (empty list) and ! null evaluates to true.  No rejections, so we like this item.

On the other hand, if a list item is going to fail one of the tests, then find will return the first Criteria object in the list which rejected the item (and not try any others after that).  So in that case ! criteriaList.find will evaluate to false and the item will be discarded.

Can you see why I used a reject method (which returns true if the test fails) rather than an accept method (which would return true if the test succeeds)?  I did that because find returns as soon as it finds a match, so we want to return as soon as one Criteria object rejects the list item.

There are other ways to do this (e.g. closure composition, although that's a more functional approach which you said isn't your style) but I hope this is a good example which will help you think of your own solutions.


If your items contain a comma, carriage return or other special CSV character, you must delimit it with quotation marks.

namespace CsvStuff
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    internal static class CsvConstants
    {
        public static char[] TrimEnd { get; } = { ' ', ',' };

        public static char[] CsvChars { get; } = { ',', '"', ' ', '\n', '\r' };
    }

    public abstract class CsvBase<T>
    {
        private readonly IEnumerable<T> values;

        private readonly Func<T, object> getItem;

        protected CsvBase(IEnumerable<T> values, Func<T, object> getItem)
        {
            this.values = values;
            this.getItem = getItem;
        }

        public override string ToString()
        {
            var builder = new StringBuilder();

            foreach (var item in
                from element in this.values.Select(this.getItem)
                where element != null
                select element.ToString())
            {
                this.Build(builder, item).Append(", ");
            }

            return builder.ToString().TrimEnd(CsvConstants.TrimEnd);
        }

        protected abstract StringBuilder Build(StringBuilder builder, string item);
    }

    public class CsvBare<T> : CsvBase<T>
    {
        public CsvBare(IEnumerable<T> values, Func<T, object> getItem) : base(values, getItem)
        {
        }

        protected override StringBuilder Build(StringBuilder builder, string item)
        {
            return builder.Append(item);
        }
    }

    public sealed class CsvTrimBare<T> : CsvBare<T>
    {
        public CsvTrimBare(IEnumerable<T> values, Func<T, object> getItem) : base(values, getItem)
        {
        }

        protected override StringBuilder Build(StringBuilder builder, string item)
        {
            return base.Build(builder, item.Trim());
        }
    }

    public class CsvRfc4180<T> : CsvBase<T>
    {
        public CsvRfc4180(IEnumerable<T> values, Func<T, object> getItem) : base(values, getItem)
        {
        }

        protected override StringBuilder Build(StringBuilder builder, string item)
        {
            item = item.Replace("\"", "\"\"");
            return item.IndexOfAny(CsvConstants.CsvChars) >= 0
                ? builder.Append("\"").Append(item).Append("\"")
                : builder.Append(item);
        }
    }

    public sealed class CsvTrimRfc4180<T> : CsvRfc4180<T>
    {
        public CsvTrimRfc4180(IEnumerable<T> values, Func<T, object> getItem) : base(values, getItem)
        {
        }

        protected override StringBuilder Build(StringBuilder builder, string item)
        {
            return base.Build(builder, item.Trim());
        }
    }

    public class CsvAlwaysQuote<T> : CsvBare<T>
    {
        public CsvAlwaysQuote(IEnumerable<T> values, Func<T, object> getItem) : base(values, getItem)
        {
        }

        protected override StringBuilder Build(StringBuilder builder, string item)
        {
            return builder.Append("\"").Append(item.Replace("\"", "\"\"")).Append("\"");
        }
    }

    public sealed class CsvTrimAlwaysQuote<T> : CsvAlwaysQuote<T>
    {
        public CsvTrimAlwaysQuote(IEnumerable<T> values, Func<T, object> getItem) : base(values, getItem)
        {
        }

        protected override StringBuilder Build(StringBuilder builder, string item)
        {
            return base.Build(builder, item.Trim());
        }
    }

    public static class CsvExtensions
    {
        public static string ToCsv<T>(this IEnumerable<T> source, Func<T, object> getItem, Type csvProcessorType)
        {
            if ((source == null)
                || (getItem == null)
                || (csvProcessorType == null)
                || !csvProcessorType.IsSubclassOf(typeof(CsvBase<T>)))
            {
                return string.Empty;
            }

            return csvProcessorType
                .GetConstructor(new[] { source.GetType(), getItem.GetType() })
                ?.Invoke(new object[] { source, getItem })
                .ToString();
        }

        private static void Main()
        {
            var words = new[] { ",this", "   is   ", "a", "test", "Super, \"luxurious\" truck" };

            Console.WriteLine(words.ToCsv(word => word, typeof(CsvAlwaysQuote<string>)));
            Console.WriteLine(words.ToCsv(word => word, typeof(CsvRfc4180<string>)));
            Console.WriteLine(words.ToCsv(word => word, typeof(CsvBare<string>)));
            Console.WriteLine(words.ToCsv(word => word, typeof(CsvTrimAlwaysQuote<string>)));
            Console.WriteLine(words.ToCsv(word => word, typeof(CsvTrimRfc4180<string>)));
            Console.WriteLine(words.ToCsv(word => word, typeof(CsvTrimBare<string>)));
            Console.ReadLine();
        }
    }
}


The big difference between the functions is not the userKey vs. groupKey but rather than they have different queries embedded in them

_QueryPermissions.GetQueriesForTaskAndUser(Int32.Parse(onlineReport.Value), userKey, ref webQueries, true);

vs.

_QueryPermissions.GetQueriesForTaskAndUserGroup(Int32.Parse(onlineReport.Value), groupKey, ref webQueries, true);

It looks like these can be abstracted as

 delegate void NodeQueryDelegate(int reportValue, int key, ref List<WebQuery> webQueries, bool someBool);

so it should be possible to refactor thus

public IEnumerable<Node> GetNodesFromQuery(int key, IEnumerable<OnlineReport> onlineReports, NodeQueryDelegate query) {
    var nodes = new List<Node>();
    foreach (var onlineReport in onlineReports)  {
        var parentNode = new Node { Text = onlineReport.Key, Value = onlineReport.Value };
        var webQueries = new List<WebQuery>();
        //Line that is different
        query(Int32.Parse(onlineReport.Value), key, ref webQueries, true);
        foreach (var childNode in webQueries.Select(webQuery => new Node(parentNode) { Text = webQuery.QueryTitle, Value = webQuery.QueryKey.ToString() })) {
            parentNode.Children.Add(childNode);
        }
        nodes.Add(parentNode);
    }
    return nodes;
}

Getting the user nodes becomes

var userNodes = GetNodesFromQuery(userKey, onlineReports, _QueryPermissions.GetQueriesForTaskAndUser);

Getting the group node

var groupNodes = GetNodesFromQuery(groupKey, onlineReports, _QueryPermissions.GetQueriesForTaskAndUserGroup);


Classifying top and bottom navigation links

You can have a function to which you will pass your links as an object (will be passed by reference) and classes. In the function, if you will pass the top or bottom links, they will be passed by reference and every change in the function will affect the original object.

function setClasses(links, classes){
    for(var i = 0; i < links.length; i++){
       if( (links[i].getAttribute('href').indexOf('a') > -1) ){
           links[i].className += classes[0];
       } else if ( links[i].getAttribute('href').indexOf('b') > -1 ){
           links[i].className += classes[1];
       }
     }
}

Used like this:

var topLinks = document.querySelectorAll('.navUtility-listItem a');
var bottomLinks = document.querySelectorAll('.footerMain-listPlatformItem a');

setClasses(topLinks, [' top-nav-a', ' top-nav-b']);
setClasses(bottomLinks , [' bottom-nav-a', ' bottom-nav-b']);


Higher order functions in Python using reduce technique

If a homework problem starts with the words "Show that", I would expect the answer to contain a proof (or at least an argument), not just an implementation.
You've misunderstood the problem statement. It says that start "specifies what value to use to start the accumulation", but in your implementation, start is the index of the first item in the sequence to contribute to the accumulation. Both of the test cases have start=1 and f(1)=1 so they are incapable of detecting your mistake.
Your implementations of summation_using_accumulate and product_using_accumulate do not actually use accumulate!


Populating an HTML combo box by looped concatenation

You give us a very short piece of code, and two simple questions. I will not address the other issues of your code (or maybe I will), but concentrate on the two questions.

1. "Would it be better to start with an empty htmlCode and then concatenate all the  code in the loop before finally using echo outside the loop?"

I guess the other alternative is echo'ing the html inside the loop? This is probably a question about performance? The best way to figure this out, is to test both cases. If the question is about coding I would not echo inside this method at all, but just return a string with the HTML. This allow you to decide later, in another part of the code, what to do with the HTML: Store it? Put it in an email? Or echo it?

2. "do I need to declare $boxOption, $paramKey and $paramValue as class variables or are they OK as is because they're only used in this method?".

Well, if they're only used in this method, then they should be local variables, NOT the class variables which you made them into now. So replace $this-> by $.

Just one remark about your method: A method should have one purpose, one thing to do. Yours does several: 1. retrieve data from the database using a query that's stored in a strange way. 2. Build HTML, but not even a whole <select>, only the options. 3. Output the HTML. This is not very flexible. Your data always has to come from a predetermined place, and your output will always be echoed. Any variation on this method will require a completely new method, probably doing almost the same thing.

You also seem to have a class that does many things. The 'single responsibility principle' doesn't seem to have been applied. These principles are here for a very good reason. See:

http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29

A programmer can ignore these principles for a long time, and programs will work, but when they grow, and expand, you will find that sticking to these principles can be very useful. Luckily the 'single responsibility principle' is one of the easiest to understand. A better explanation can be found here:

http://www.codemag.com/article/1001061


Array choice based on template specialization

Small rant about question / description

  And these arrays: [..]

Be as precise as necessary when describing things. Generalize ("containers") when it helps to make things more clear. But don't say wrong things. These are no arrays, these are sets.

Accessing the sets based on their content type.

std::set<std::shared_ptr<Tickable>> tickables;

The fact that this set contains "tickables" is encoded twice in the line above: The type of that std::set contains the type Tickable and the name (informally) tells us the same. While accessing this set as tickablesis a good and very readable option, this does not lend itself to template programming that much, because the compiler doesn't understand "tickables". It's just another identifier, the meaning (that we humans are able to understand) is lost.

Thus I suggest accessing your sets like set_of<Tickable>(). This is still readable to us, but also provides information for the compiler about the content of the set.

To be able to pull this off I wrap the sets in a helper struct:

template <typename Content>
struct SetWith {
  std::set<Content> set;
};

This only holds a single set (with a single content type). I generalize to multiple content types (and multiple sets) via variable template arguments:

template <typename... Contents>
struct SetsContainer {};

template <typename Content, typename... OtherContents>
struct SetsContainer<Content, OtherContents...>
  : public SetsContainer<OtherContents...>,
    public SetWith<Content>
{};

The first is the template definition that will be used when the template specialization (the second definition above) doesn't match, i.e. when there's no (more) content: SetsContainer<>.

The specialization inherits from the previously defined wrapper (and thus gets a member of type std::set<Content>) and also inherits from a variation of its own type with the Content "removed".

Accessing the sets is now almost trivial:

template <typename C, typename Container>
std::set<C> & set_of(Container & sets) {
    return static_cast<SetWith<C> *>(&sets)->set;
}

// Use:
SetsContainer<int, bool, char> sets;
set_of<bool>(sets).insert(true);

Of course you can also make set_of an (template) member function of a class containing a SetsContainer named sets and drop the parameter.

Your add is then:

template <typename T>
void add(T actor) {
  set_of<typename std::decay<T>::type>().insert(std::forward<T>(actor));
}

Here's an ideone link to play with the above.

Don't throw away useful information

What if you add the very same Tickable twice? Do you want to be informed about this? Because if its added twice when you didn't intent to, this could help you find bugs.

std::set::insert returns useful information, so why throw it away? Better make your add return e.g. the bool returned by insert.

Heavy copies ahead!

The "new" for syntax has its issues, IMO. Do you know that every time you run that (or any of the other) loop ...

for (std::shared_ptr<Tickable> tick : tickables) // ...

... you're creating a copy of every smart pointer in the set. This is not as bad as making a copy of the Tickables, but it still degrades performance: Every time a smart pointer is created it needs to increment the reference counter, and on every destruction it decrements it again.

Better add a reference to avoid those copies:

for (std::shared_ptr<Tickable> & tick : tickables) // ...

This isn't facebook, don't share that much ;)

This is just a guess, but I'd assume that you misuse std::shared_pointer. Think carefully about who owns (for example) a Tickable. Who controls its lifetime?

If it's the GameEngine, then you are far better of using std::set<Tickable>.

The sets are useless

That said, putting std::shared_pointers inside a std::set (with the default compare) means that its operator< is used by the set to prevent duplicates. But, from above link (emphasis mine):

  Note that the comparison operators for shared_ptr simply compare pointer values; the actual objects pointed to are not compared.

Thus you can happily write (assuming a copy constructor) ...

auto foo = std::make_shared<Tickable>();
auto bar = std::make_shared<Tickable>(*foo); // Calls copy constructor
add(foo);
add(bar);

... and have two copies of a Tickable in your set.


This is not best practice but simple logic.

Why you have add inside the loop this (non change) parameters ?

    string Type = "D";
    DateTime Date = DateTime.Now;
 string connectionString =
       ConfigurationManager.ConnectionStrings["Foo"].ConnectionString;

Get them out of the loop.

Second place the connection inside using, and totally outside the loop, why you need to open it and close it all the time.

protected void RadButton2_Click(object sender, EventArgs e)
{
    //GridDataItem item = (GridDataItem)RadGrid1.SelectedItems;
    string Type = "D";
    DateTime Date = DateTime.Now;

    string connectionString = ConfigurationManager.ConnectionStrings["Foo"].ConnectionString;
    SqlConnection connection = new SqlConnection(connectionString);

    using(SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        foreach (GridDataItem item in RadGrid1.SelectedItems)
        {
            try
            {
                string Description = "Monthly Storage Fee - Tag: " + item["PackageTag"].Text + Label3.Text;
                Int32 AmountDue = Convert.ToInt32(item["AmtDue"].Text);
                int UserID = Convert.ToInt16(item["UserID"].Text);

                using (SqlCommand cmd = new SqlCommand("INSERT INTO Billing (UserID, Type, Date, Description, Amount) VALUES (@UserID, @Type, @Date, @Description, @AmountDue)", connection))
                {
                    cmd.Parameters.AddWithValue("@UserID", UserID);
                    cmd.Parameters.AddWithValue("@Type", Type);
                    cmd.Parameters.AddWithValue("@Date", Date);
                    cmd.Parameters.AddWithValue("@Description", Description);
                    cmd.Parameters.AddWithValue("@AmountDue", AmountDue);

                    cmd.ExecuteNonQuery();
                }
            }
            catch
            {
                Label4.Text = "uh oh";
            }
        }
    }
}

Need some extra test for check if the connection is open or fail


Whenever I start a review, I open up PEP 8, the Python style guide.  That document is so rarely read that it is depressing.  Your naming is not in accordance with it.  From Method Names and Instance Variables:

  Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

(There's more, but it isn't pertinent here)

Your indentation looks good mostly, but for some reason you did eight-space indentation in makeGallow().

In makeGallow(), you do a bunch of .append() calls, but you don't guarantee that your list was empty in the first place.  It is very easy to clear a list.  Just do gallow[:] = [].  As long as you are doing something like that any way, you might as well do gallow[:] = [[] for _ in range(8)] and take out your first for loop.  I used _ as my variable name instead of i because it is the convention in Python to name a variable _ when you aren't using it.

Your code could benefit from an if __name__ == '__main__': block.  That way, you might later create a very fancy hangman game that imports this one to use its makeGallow function.  As it is, importing this would start the game.  I would suggest that you define a main function and call it in your if __name__ == "__main__": block.

Strings are iterable.  That can be useful when making a list of each character in it.  For example, list("foo") is ["f", "o", "o"].  Therefore, you can change

secret_wordls = list()
for c in secret_word:
    secret_wordls.append(c)

to

secret_wordls = list(secret_word)

and change

blanks = list()
for i in range(len(secret_word)):
    blanks.append('_')

to

blanks = list("_" * letters)

Notice that I also changed len(secret_word) to letters.  You defined the variable; why not use it?  While I'm there, is letters really a good name?  From the name, I would expect it to be a list of characters or a string, not a number.  Maybe word_length would be better?

I see that you are using generator expressions.  That's good, but actually a list comprehension is faster when using str.join().  Even better, don't bother with either.

"".join(i for i in blanks)

could be

"". join(blanks)

for example.

I suggest that you add an elif len(letter) != 1 between if letter == "quit": and the rest of the elifs.  That way, you can inform the user that he should type just one letter instead of penalizing him because what he typed isn't in your list of letters.

Th-th-th-th-that's all, folks! (Don't worry; it's a quotation.)


You're using some poor methods when there are better options available to the data types you've picked.

A huge bottleneck is hidden in those 2 lines:

Sock = Laundry.ElementAt(rand.Next(Laundry.Count));
Laundry.Remove(Sock);

Let's see why

General vs specific methods

ElementAt is an extension method of the type IEnumerable<T>, the List<T> is inheriting IEnumerable<T> but guess what, so are most of the collections in C#. That means when you write a method that is applicable to so many types, you need to make it as generic/general as possible while still maintaining reasonable performance, but of course using a concrete implementation of that method for said collection would be faster. You can do that because you are 100% sure that the optimizations will always be valid.

So the first thing is to replace the ElementAt() with normal indexer.

RemoveAt() vs Remove()

In most cases Remove() would be a O(n) operation where RemoveAt() would be O(1) operation. The first uses the latter internally so it's always better to use this method when you know what index you want to remove, guess what, you already know what index you're removing:

int index = rand.Next(Laundry.Count);
Sock = Laundry[index];
Laundry.RemoveAt(index);

Besides that you're never utilizing the collection Matched. You're just wasting time adding stuff into it without ever touching them.

Adding those changes made the code about 2.5 times faster. On average from 45ms  to about 17ms per run.


At times to speed up a recursion you can use memoization to cache the results of your previous known calculations, trading memory for speed. (Memoization is slightly different to dynamic programming.)

  A memoized function "remembers" the results corresponding to some set
  of specific inputs. Subsequent calls with remembered inputs return the
  remembered result rather than recalculating it, thus eliminating the
  primary cost of a call with given parameters from all but the first
  call made to the function with those parameters.

Here's an example, after I took the liberty to simplify the number of arguments a bit for sake of clarity,

public static Map<List<Integer>, Boolean> cache = new HashMap<List<Integer>, Boolean>();

public static boolean subSetSum(List<Integer> S, int sum) {
    if (sum == 0) return true;
    if (S.size() == 0 || sum < 0) return false;

    List<Integer> key = new ArrayList<Integer>(S); // composite (set, sum) memoization key
    key.add(sum);
    // let x be the first element of S, then there is either a solution with
    // the set S - {x} without the first element considered, or there is a
    // solution where x is accounted for, ie with the set S - {x} and sum - x
    if (!cache.containsKey(key)) {
        List<Integer> forwardSet = S.subList(1, S.size());
        cache.put(key, subSetSum(forwardSet, sum) || subSetSum(forwardSet, sum - S.get(0)));
    }
    return cache.get(key);
}
// Example: subSetSum(Arrays.asList(new Integer[] { -7, -3, -2, 5, 8 }), 1);

Note the caveat that the example outlines the trade-off described above, it may or may not be faster than your specific example. For example, notice that the list of integers that constitutes the key is cloned, which is suboptimal.


Filling random values in two sheets from a single sheet via Excel VBA

Accessing Objects such as Sheets, Cells & Range takes considerable time. Try to reduce their use as much as you can by assigning their values to a variable before entering a For loop.

If Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "ARB11" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "ARB13" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "FVB1" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "FVB1E" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "FVB4" Or Sheets("Testfall-Input_Vorschlag").Cells(1, j) = "FVB4E" Then

These chained If statements will each be getting the value of your test cell in turn, each one accessing Sheets and Cells individually over and over for the same value, this will likely be having an impact on your performance.

Try putting the cell value in a variable before your tests:

testCell = Sheets("Testfall-Input_Vorschlag").Cells(1, j).Value
If testCell = "ARB11" Or testCell = "ARB13" Or testCell = "FVB1" Or testCell = "FVB1E" Or testCell = "FVB4" Or testCell = "FVB4E" Then

For i = 13 To 501
    UB = sh2.Cells(Rows.Count, i + 364).End(xlUp).Row 'i - 10 controls column in Admin start at col 1.
    sh1.Cells(i, j).Value = sh2.Cells(Int((UB - LB + 1) * Rnd + LB), i + 364)
Next

Within this loop, it appears that each iteration is finding the bottom row number with UB = sh2.Cells(Rows.Count, i + 364).End(xlUp).Row, could this be done before the loop?


Some suggestions:

#!/usr/bin/env bash is a very common shebang line these days.
Use More Quotes™:

echo -e $i'\t'"${BOOKMARKS[$i]}" should be echo -e $i'\t'"${BOOKMARKS[$i]}" (or even better, printf '%s\t%s' "$i" "${BOOKMARKS[$i]}")
command=$1 should be command="$1"

In [[ "$command" =~ [0-9]+ ]] you'll want to anchor the regex.
If this is for your own use I don't quite understand the need for both option-style and command-style invocation.
== in Bash is a bit of a historical accident. It won't make any difference as long as you use Bash, but I usually prefer the POSIX = in this case.
It seems bm_compact should run on every change, since it'll be super fast and you avoid changing indexes.
bmfile would be better as either configuration or as a single variable.
"default !/.bookmarks" should probably be "default ~/.bookmarks".
You can set IFS for a single command, such as while IFS=… read …
All the single semicolons are extraneous - you definitely don't need one for echo -e $i'\t'"${BOOKMARKS[$i]}" ;, and you can use

for i in "${!BOOKMARKS[@]}"
do

for loops and conditionals.


How to automatically insert HTML to a form and obtain the inputs?

A better way is to use templates. Handlebars should be a good start for this.

Here's a quick demo:

HTML:

JS:

// The data.
var data = {
  people : [
    {
      id : 1,
      name : 'Alice'
    },{
      id : 2,
      name : 'Bob'
    }
  ]
};

// We get the template HTML
var template = $('#template').html();

// Compile it as a handlebars template renderer
var renderer = Handlebars.compile(template);

// and just feed in the data into the renderer to return the HTML with the data
var html = renderer(data);

// Then all we need to do is pop-in the HTML with the data to our page
$('#container').html(html);

The rest is up to you. You can use the demo as your guide. You can use the id of the data as your n. Handlebars also provides you the index if you loop through an array in the template, which you could also use as your n.


Code to modify DOM element using DOM.style property

Inline style lengths require units. In quirks mode, browsers will assume pixels as the unit, if provided with an integer instead of a length. If you are not sure how the browser will handle the value, specify the units.

  The CSS parser interprets unitless numbers as px (except for line-height and any other properties where they have distinct meaning, and except in shorthands).

Bonus: Here is an extensible version of your script.

const state = {
  color : { r : 0, g : 255, b : 0 },
  dimensions : { width : 50, height : 300 }
}

const applyState = (el, state) => {
  Object.assign(el.style, {
    backgroundColor: `rgb(${state.color.r}, ${state.color.g}, ${state.color.b})`,
    width: `${state.dimensions.width}px`,
    height: `${state.dimensions.height}px`
  })
}

applyState(document.getElementById('my-div'), state)


Your code is nice overall, but here are my two cents :

initializing instance variables before using them is not mandatory, so initialize as you implemented it is useless. A call to @context if it is not initialized will return nil.
Since uninitialized instance variables return nil, you may have have problem when doing things like @context.parameters[:cache]. As such, i would advise to initialize them... in initialize :

class Generator
  def initialize( params )
    @context = Context.new( params )
  end
end

This also leaves you the latitude to inspect the params and throw an ArgumentError if some usefull params are not present.

I think your object has mixed responsibilities. What does it represent ? It is not clear at first glance. Is it an uploader, an image ? It looks like a Service to me (the process is stateless), or maybe a "context" in DCI slang. Maybe your structure could more accurately represent this :

module ImageGeneratorService

  def self.start( params )
    cache = params.delete( :cache )
    image = ImageFactory.create_from_params( params )
    CacheService.cache_image( image, cache ) if cache
    image
  end

end

... ok, it's a bit too much, but i think you get the spirit. YMMV


Perl script to match case law references

Adding use warnings; at the top of the script doesn't emit any warnings. Adding use strict; makes the variable $search_text undeclared, but it's easy to fix it by adding my before its first use.

The easiest way to read the input from a file is to specify the filename as a parameter to the script, and read from the file with the diamond operator <> looping over the input lines:

while (my $search_text = <>) {

Also, there's a lot of repetition in your code. To deduplicate it, you can store the regular expressions in a hash keyed by the type of the reference. It shortens your script to

#!/usr/bin/perl
use warnings;
use strict;

my %reference = (
    NCits => [ qr/((\(|\[)\d{4}(\)|\]))(\s+((EWHC)|(EWHC\s+Admin)|(CAT)|(EWCA)|(EWCA\s+Civ)|(EWCA\s+Crim)|(EWCOP)|(EWFC)|(EWFC\s+B)|(EWPCC)|(UKHL)|(UKIAT)|(UKPC)|(UKSC)|(CSOH)|(CSIH)|(NICA)|(IESC)|(IECCA)|(IECA)|(IEHC)|(UKUT))\s+\d+)/ ],
    WLR => [ qr/((|\[)\d{4}(\)|\]))(\s+\d+\s+((WLR))\s+\d+)/ ],
    'Appeal Cases' => [ qr/((|\[)\d{4}(\)|\]))(\s+\d+\s+((AC))\s+\d+)/,
                        qr/((|\[)\d{4}(\)|\]))(\s+((AC))\s+\d+)/ ],
    "Queen's Bench Cases" => [ qr/((|\[)\d{4}(\)|\]))(\s+\d+\s+((QB))\s+\d+)/,
                               qr/((|\[)\d{4}(\)|\]))(\s+((QB))\s+\d+)/ ],
    'External references' => [ qr/((\(|\[)\d{4}(\)|\])){0,1}(\s*\d+\s+((TLR)|(TLR\s+\(Pt\s+1\))|(TLR\s+\(Pt\s+2\))|(LGR)|(Cr\s*App\s*R)|(Cr\s*App\s*R\s*\(S\))|(Ll\s*L\s*Rep)|(LlLR)|(TC)|(FLR)|(BCLC))\s+\d+)/ ],
    "NI Queen's Bench Cases" => [ qr/((|\[)\d{4}(\)|\]))(\s+((NIQB))\s+\d+)/ ],
    NZLR => [ qr/((|\[)\d{4}(\)|\]))(\s+\d+\s+((NZLR))\s+\d+)/,
              qr/((|\[)\d{4}(\)|\]))(\s+\d+\s+((All ER))\s+\d+)/ ],
    ECR => [ qr/((|\[)\d{4}(\)|\]))(\s+((ECR))\s+\d+)/ ],
    'Older volume' => [ qr/(\d+\s+((App\s*Cas)|(Ch\s*D)|(CPD)|(Ex\s*D)|(P.D.)|(Q.B.D.))\s+\d+)/ ],
);

print "\n-----------------------------\n";
print "Case References Found in Text";
print "\n-----------------------------\n";

while (my $search_text = <>) {
    for my $type (keys %reference) {
        print "\n***** $type *****\n";
        for my $regex ( @{ $reference{$type} } ) {
            while ($search_text =~ /$regex/ig) {
                print "$1$4\n";
            }
        }
    }
}

In a regex, (\(|\[) can be more readably written as ([[(]). For grouping without capturing, you can use (?: instead of (. For example, the NCits regex can be written as

/((?:[[(])\d{4}(?:[])]))(\s+(?:EWHC(?:\s+Admin)?|CAT|EWCA(?:\s+(?:Civ|Crim))?|EW(?:COP|PCC)|EWFC(?:\s+B)?|UK(?:HL|IAT|[PS]C|UT)|CS(?:[OI]H)|NICA|IE(?:SC|CCA|CA|HC))\s+\d+)/

which changes the variables to output to $1$2.

To output to a file, just redirect the output:

script.perl input-file > output-file


Calculating the statistical Mode(s) of a (possibly multi-modal) set of elements

So without really understanding what you mean with mode I would suggest the following purely based on your code:

Add includes. The code as is doesn't compile, which makes it harder for reviewers.
Premature Optimization. You are doing a lot of it. There is no reason to assign vectorsize to myvector.size(). The compiler will take care of that. Also currentnum is unnecessary.
Be consistent with your style. Putting else clauses at the same line with the code makes the code incredibly hard to read. Also parentheses really help in tracing the control flow. Generally nested control flow should utilize parentheses.
Naming. Consider camelCase or scores, but do not just add lowercaseletters as in alreadyin
alreadyin == false should be !alreadyin

So know that I know what you mean we can optimize the code.

The first thing would be naming. The vector containing the modes should be named modes rather than maxs. Similarly I would rather name max as currentMode or better modeStrength.

The second point would be the update of the vector. Currently you always clear it. However, if it only has one mode you can just change that value.

if (modes.size() == 1)
    modes[0] = myVector[i];
else if (modes.size() > 1)  {
    modes.clear();
    modes.push_back(myVector[i]);
} else {
    modes.push_back(myVector[i]);
}

The third idea would be to increment your loop based on the found matches so you do not reiterate already processed data

unsigned counter;
unsigned modeStrength = 0;
for (unsigned i=0; i < myVector.size() - 1; i += counter) {
    counter = 1;
    while ((counter + i != myVector.size()) &&
           (myVector[i] == myVector[i+counter])) {
        counter++;
    }
    if (counter == modeStrength) {
        modes.push_back(myVector[i]);
    } else if (counter > modeStrength) {
        modeStrength = counter;
        if (modes.size() == 1) {
            modes[0] = myVector[i];
        } else {
            modes.clear();
            modes.push_back(myVector[i]);
        }
    }
}

That would also turn the check for existence unnecessary.


Using a try-with-resources

You're correctly closing your Scanner at the end of the method in a finally block, so there can be no resource leaks.

However, starting with Java 7, you can simply use the try-with-resources construct to make this easier:

try (Scanner sc = new Scanner(text)) {
    // ...
}

Reading words with lines

You're using a Scanner to read each line and then you are splitting the line on non word characters, i.e. everything that is not [a-zA-Z_0-9].

This can be a problem: what if you encounter a word that has a dash or a quote? You will wrongly split it. It would be better to split around a whitespace character, i.e. \s.

Also, you're currently using a lineNo variable to hold the current line number. You could use the built-in LineNumberReader that already maintains a line number. You can access it with getLineNumber().

Code structure

Your declaration of

private Map<String, ArrayList<Integer>> occurences;

is located at the bottom of the class. Generally, instance variables are found at the top instead so that you can see directly what the class has as instance variables.

You're currently using two classes: one for the main part and one to find the occurences. It introduces a problem: the constructor does too much work. In fact, the constructor of Index does all the work. It would be better to refactor this into a method properly named after what it does. We could introduce a method populateOccurences whose goal would be to create the occurences map.

Also, I don't think the Index class is really that necessary: the more a code is simple, the better it is to maintain it. In this case, this class really contains a single method, which to populate the occurences map. It would be easier to not have that class and simply have a method

private static Map<String, List<Integer>> getOccurencesMap(Reader text) throws IOException

inside the main class that would return the map.

Also, don't name your variables index_str: use camel-case, as indexStr.

Handling exceptions

When you're reading a text from a file, you're not directly catching the FileNotFoundException, instead you're letting the main method do it:

try {
    BufferedReader br;
    if (args.length == 0) {
        br = new BufferedReader(new InputStreamReader(System.in));
    } else {
        br = new BufferedReader(new FileReader(args[0]));
    }
    // ...
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

This create a coupling between the method and what it reads from. Instead, it would be best to delegate that to a method dedicated to returning the Reader to read:

private static Reader getReader(String[] args) {
    if (args.length == 0) {
        return new BufferedReader(new InputStreamReader(System.in));
    } else {
        try {
            return new BufferedReader(new FileReader(args[0]));
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException("The given file does not exist.", e);
        }
    }
}

Note two things:

The catch (FileNotFoundException e) is done inside the else part: that is the only part of the code responsible for reading a file, so it must be the only part of the code for handling a FileNotFoundException.
A custom IllegalArgumentException is re-thrown to indicate that the file wasn't found. This runtime exception wraps the initial FileNotFoundException to have a proper stacktrace but it hides that from the surrounding code.

Lowercasing Strings

Be very careful when lowercasing / uppercasing Strings in Java. This depends on the locale. By default, Java will use the locale of the current JVM, which is your system locale (by default). If you were to read a Turkish text on a server in France, you might have inconsistencies and hard to understand bugs! It is preferable to use a locale when doing those operations

word = word.toLowerCase(Locale.ROOT);

Using Java 8 constructs

Your code updating the Map holding the line numbers for each word reads line

ArrayList<Integer> list = occurences.get(word);
if (list == null) {
    list = new ArrayList<>();
    list.add(lineNo);
} else {
    list.add(lineNo);
}
occurences.put(word, list);

Let alone the fact that you could drop the else clause and have list.add(lineNo); after the if (which would remove this little duplication), you could use the method computeIfAbsent that will get the value for a specified key or if there is no value, set it with an initial value based on the given mapping function. In this case, you can simply have

occurences.computeIfAbsent(word, k -> new ArrayList<>()).add(lineNo);

If the current word is not in the map, a new ArrayList will be created and returned, otherwise the current list for that word will be returned. Then, on this instance, we add the current line number.

Beginning with Java 8, a BufferedReader also has a useful lines() method that returns a Stream<String> of the lines. Instead of looping with a for, we could make that a Stream pipeline. This is what it would look like:

Make a Stream of the lines: this is done by calling lines() on the BufferedReader.
Flat map each line into a Stream of its words: this can done by using a method reference: Pattern.compile("\\s+")::splitAsStream. This creates a Pattern around the whitespace characters delimiter and splits each given String into a Stream<String> using splitAsStream. The :: operator creates the method-reference. Flat mapping is done by calling flatMap from the Stream API.
Map each word as lowercase: this can be done by using the lamda expression w -> w.toLowerCase(Locale.ROOT), fed to the map method of the pipeline
Collect that into a Map having the word as key and the line numbers as value: this can be done with the built-in Collectors.groupingBy collector, where the classifier returns the current word. All values mapped to the same word are collected using a downstream collector, which in this case would map, using Collectors.mapping, each line number into a downstream list (with Collectors.toList()).

Into code, it would look like:

try (LineNumberReader reader = new LineNumberReader(text)) {
    return reader.lines()
                 .flatMap(Pattern.compile("\\s+")::splitAsStream)
                 .map(w -> w.toLowerCase(Locale.ROOT))
                 .collect(Collectors.groupingBy(
                     w -> w,
                     Collectors.mapping(w -> reader.getLineNumber(), Collectors.toList())
                 ));
}

Of course, you can't run this in parallel.

Putting it all together

With all this, this is what you could have

public class BookIndexer {

    public static void main(String[] args) throws IOException {
        Reader br = getReader(args);
        String indexStr = getOccurencesMap(br).toString();
        System.out.println(indexStr);
    }

    private static Reader getReader(String[] args) {
        if (args.length == 0) {
            return new BufferedReader(new InputStreamReader(System.in));
        } else {
            try {
                return new BufferedReader(new FileReader(args[0]));
            } catch (FileNotFoundException e) {
                throw new IllegalArgumentException("The given file does not exist.", e);
            }
        }
    }

    private static Map<String, List<Integer>> getOccurencesMap(Reader text) throws IOException {
        try (LineNumberReader reader = new LineNumberReader(text)) {
            return reader.lines()
                         .flatMap(Pattern.compile("\\s+")::splitAsStream)
                         .map(w -> w.toLowerCase(Locale.ROOT))
                         .collect(Collectors.groupingBy(
                             w -> w,
                             Collectors.mapping(w -> reader.getLineNumber(), Collectors.toList())
                         ));
        }
    }

}


1e9 is only 1 billion, which will fit into a standard integer range of 2 billion some.

The hcf function is unexpected, because it's just a wrapper for BigInteger. I think just using the built in GCD function would be better than making your own method that calls a standard function. If it's critical to the algorithm understanding that we think of a highest common factor instead of a greatest common denominator, then keep the function. If you do keep it, though, use the full name instead of an abbreviation i.e. private BigInteger highestCommonFactor.

I looked at your code and expected to see a loop. I'm assuming you've worked out the math to do this without loops, which is good and probably more efficient. But, I don't really know how this would work, and would be worried someone else looking at the code would have the same problem. A code comment indicating what mathematical principles, or even the name of a theorem, would help immensely.


The code is overall good basic PHP and above the average. However, I would like it more structured.
For example, why you are setting the error reporting manually in this file? Apparently you have sort of a bootstrap file as includes/header.php, why not to put these lines there?
Besides, i don't see any point in the line assigning $post_id variable. What does a post id to do with deleting an account? And yes, such a syntax structure looks embarrassing.
It is also a good rule of thumb to follow Location header with an explicit exit call. Although it is not critical in this particular case, sometimes the lack of the script termination could pose a serious threat, as the header itself doesn't stop the script execution.
Some notes on the database structure

The computer world has its own representation for "yes" and "no", it's 1 and 0 respectively. So consider making the field of tinyint type instead of varchar.
it is considered a good practice to address all database entities by the unique id. It's better to store the user id in the session and use it for all the database operations.

The code structure
One big issue I overlooked at first is the structure of your script. It seems that includes/header.php is not just a bootstrap file but it also starts some HTML output. that's a big NO. An HTTP header such as Location cannot be sent after HTML. Your PHP lets you to do it due to some permissive setting, but it is nevertheless wrong, from the logical and technological points of view. It just makes no sense to start any output when your script is not going to display anything but would only redirect to another page.
Split your includes/header.php file into two: bootstrap.php and header.php. The former should contain all the configuration options such as database connection, error reporting etc, but not a byte should it output. And the latter would contain all the HTML.
Than make your code like this
<?php

include 'includes/bootstrap.php';

$id= $_SESSION['user_id'];

if(isset($_POST['close_account']))
{
    $stmt = $con->prepare('UPDATE users SET user_closed = 1 WHERE id = ?');
    $stmt->bind_param("s", $id);
    $stmt->execute();

    session_destroy();
    header("Location: register.php");
    exit;
}
include 'includes/header.php';
?>
<center>


Web Scraping, Serializing and Deserializing in Python

PEP8 names
All of these variables:
def __init__(self, Date, DocumentType, Procedure, NoOfPages):
    self.Date = Date
    self.DocumentType = DocumentType
    self.Procedure = Procedure
    self.NoOfPages = NoOfPages

should be lower_snake_case.
Data classes
Replace JsonClass with a @dataclass that uses an implicit __init__.
Connection
First note that there's no point in separating out your connection parameters like
'Driver={SQL Server};' 'Server=xyz-PAVILION;'

since they will be implicitly concatenated to
'Driver={SQL Server};Server=xyz-PAVILION;'

Beyond that, the documentation states that kwargs are converted to a formatted conn string, so you're better off writing
pyodbc.connect(
    Driver='{SQL Server}',
    Server='xyz-PAVILION',
    Database='jsondata',
    Trusted_Connect='yes',
)

Context management
Use a with on your connection and cursor objects; read
https://github.com/mkleehammer/pyodbc/wiki/Connection#context-manager
Exception interference
Don't convert exceptions to booleans, as in
except pyodbc.Error as error:
    print('Error : %s' % error)
    return False
except:
    print('Operation Failed')
    return False
conn.close()
return True

Deal with the exceptions, potentially wrapping them in your own exception types, and catching them at an upper level.
Double serialization
Don't do this:
with open('html_to_json.json', 'w') as file_out:
    json.dump(dict_list, file_out, indent=4)  # Serializing dict_list and writing in  .json file
return json.dumps(dict_list)

Hold onto the result of dumps and write that string to the file.
Print helpers
Move this code:
    print('Date : ' + i.Date)
    print('DocumentType : ' + i.DocumentType)
    print('Procedure : ' + i.Procedure)
    print('NoOfPages : ' + i.NoOfPages)

to a method of JsonClass.
Hard-coded paths
my_file = open("C:/Users/xyz/Downloads/sample.htm", 'r')

should not be hard-coded. Set it as some kind of parameter - a command-line argument maybe.
Dict literals
    record = dict()
    date_obj = datetime.datetime.strptime(column[1], '%d.%m.%Y')
    record['Date'] = date_obj.date().isoformat()
    record['DocumentType'] = column[2]
    record['Procedure'] = column[3].replace('\u00a0/\u00a0', '/').replace('\u00a0', '/')
    record['NoOfPages'] = column[4]

should not call dict(), should not individually index keys, and should instead use a dict {} literal.


Potential bugs

I just spent a few minutes reviewing this, so I'm not sure these are bugs, but you should have a look at them:

The comma operator is not the same as &&. You have this code:

for (int i = 0; i < ipSrcLen, addrIdx < 4; i++) {

but I think you meant to use && instead of ,. I'm not sure it matters because I'm not sure what the chances are that you will get a mismatch between the string contents and the length, but it's a possible source of error.
Incomplete error checking. In the "invalid digit" section of your loop, you have this check:

if (addrIdx == 3 && current >= 0) {

but you don't do anything if that condition is not true. If addrIdx is 0, 1, or 2 you don't handle the bad digit, but instead fall through. I think you need to catch those cases and fail gracefully.

IpToString

I mentioned this in the comments, but you know the range of values is small. So there's no reason not to replace your divisions with either a series of if statements or a lookup table.

Unless you're writing a router or something, I don't expect the lookup table would pay for itself, so the if statements seem to be the way to go. Something like this:

need_tens_0 = FALSE

// hundreds digit
if number >= 100:
    need_tens_0 = TRUE

    if number >= 200:
        *ptr++ = '2'
        number -= 200
    else:
        *ptr++ = '1'
        number -= 100

// tens digit (binary search)
if number >= 50:
    if number >= 80:
        if number >= 90:
            *ptr++ = '9'
            number -= 90
        else:
            *ptr++ = '8'
            number -= 80

// ... buncha cases omitted ...

else if number >= 10:
else:
    // "6" could be 56 or 106 or 216. Check if we need to insert a padding 0
    if need_tens_0:
        *ptr++ = '0'

// Ones digit
*ptr++ = '0' + number


There's nothing that looks bad at a first glance. Couple observations though:

It isn't clear what happens if the time entered isn't in the departure list. Consider adding a default case, even if just to explain to the user that he has to punch in a time present in the list.

A negative number of passengers is valid according to your program, but I doubt this is intentional. Always validate user input.

An exception is thrown if I enter a string instead of a number when asked for the passenger count. See above ;)

At first read, I thought total_seats was, well, the total number of seats but it is the number of seats per coach according to the script output. You might want to clarify that or rename the variable.

You can use \n in your prints to add newlines, I'm not a fan of binding the formatting of your code to the formatting of your output. Both of these lines print the same thing:

print(f"""Your total price is: {current_passengers*ticket_price} dollars
""")
print(f"""Your total price is: {current_passengers*ticket_price} dollars \n""")

The run variable isn't as self-documenting as it could be if it was named incorrectInput or retryInput or something like that.

Take these two more as suggestions than actual issues with your code:

The fact that your timing system relies on list indexes isn't very pythonic (Explicit is better than implicit). You could use a dict to assign a unique ID to every train... But you'd need a bit more code to reproduce index_train = departure.index(commute), and I'm not a fan of doing syntax gymnastics in "exam code" so I'd say that your solution is good enough.
Another pythonic thing, "Ask forgiveness not permission": you could get rid of the check for wether commut is in departure, do index_train = departure.index(commute) right away and handle the ValueError that gets thrown if commute isn't in departures using a try except block. Your solution is already fine though (and probably less verbose).

Overall I don't see anything that doesn't work as intended, so it's already pretty solid (as long as the user isn't messing with the input like I did). If it is "exam code" I'd prioritize the formatting and documentation stuff so that your code is more readable. Readable = fast to grade, and fast to grade = less time spend analyzing and figuring out every minor issue with the code ;)


Streaming scheduled TV shows according to a CSV playlist

I'd start with a few specific points for the code style.

Consistent naming. You are mixing snake_case and camelCase. Check the section on naming conventions.
Whitespaces around keyword arguments is advised against.
Try to use str.format() or str % () modes to insert variables into strings, preferring the .format over % style. If you do decide to switch to python 3.6+ (as commented), you also have f"" (format-type strings).
Order your imports in the following suggested order:

Standard library imports.
Related third party imports.
Local application/library specific imports.

Now, to some changes you can do for optimisations, maintainability and portability.

Your entire cron.py is redundant. Since everything it does depends only on the tvshow.py, switch to only using that file. Place the code currently in cron.py inside the if __name__ == "__main__" block.
You're trying to import config twice.

import config
import csv
import config

You can have a class TVSchedule(r), which reads the config file when initialising, and sets up the file_name, time, app_path beforehand.
The performance of scanFileForTime and getFileContent will get better if the latter yields the rows :)
Make use of .extend method; so that the following:

for item in config.appArguments:
    arguments.append(item)

becomes

arguments.extend(config.appArguments)


You can try the .Any function on IQueryable. It is made for checking if there are any records.

Remember that .Any() has an overload that takes an expression, making the solution

internal static bool WellExists(string name, DatabaseContext context)
{
    return context.Wells.Any(x => x.Name == name);
}

I'm going to add a comment about your code as well.
In the second example you have return !(well == null). This obfuscates the meaning of the code a bit, and would be clearer if you write return well != null;


Fading HTML elements in and out after timed delays using jQuery

Explicit question

  Criticize my Javascript

So... you have some JavaScript that uses the jQuery library, and there are a lot of nested function calls. Obviously that isn't very flexible, and some might say it looks daunting with all of those nested callbacks.

Implicit question

i.e. How can I simplify this?

There are numerous ways to achieve this... but one way is to use function partials to simplify the callbacks.

Consider the function below, which checks for a next sibling element using .next():

function fadeInOutNext(elementCollection) {
   elementCollection.delay(500).fadeIn(300).delay(getDelayForElement(elementCollection)).fadeOut(300, function() {
     const next = elementCollection.next();
     if (next) {
       fadeInOutNext(next);
     }
   });
 }

With this function, the nested callbacks can be reduced:

$("button.button").click(function(){
 $("h1.about-title").fadeOut(300, fadeInOutNext.bind(null, $("div.b")));
});

As well as the function to get the delay between fading in and out:

function getDelayForElement(elementCollection) {
  if (elementCollection.is('.e, .f, .g')) {
    return 5000;
  }
  return 4000;
}

See the complete code in the snippet below:

 function getDelayForElement(elementCollection) {
  if (elementCollection.is('.e, .f, .g')) {
    return 5000;
  }
  return 4000;
 }
 function fadeInOutNext(elementCollection) {
   elementCollection.delay(500).fadeIn(300).delay(getDelayForElement(elementCollection)).fadeOut(300, function() {
     const next = elementCollection.next();
     if (next) {
       fadeInOutNext(next);
     }
   });
 }
 $(document).ready(function() {
   $("button.button").click(function(){
     $("h1.about-title").fadeOut(300, fadeInOutNext.bind(null, $("div.b")));
   });
 });
/* ------------------------------THE RESET----------------------------*/

html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  background-color: black;
}

ol,
ul {
  list-style: none;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/*-----------MY CODE-----------*/

* {
  font-family: Futura, Futura-Medium, "Futura Medium", "Century Gothic", CenturyGothic, "Apple Gothic", AppleGothic, "URW Gothic L", "Avant Garde", sans-serif;
  color: white
}

.frontpage {
  font-family: Futura, Futura-Medium, "Futura Medium", "Century Gothic", CenturyGothic, "Apple Gothic", AppleGothic, "URW Gothic L", "Avant Garde", sans-serif;
  text-transform: uppercase;
  letter-spacing: 8px;
  font-size: 3.5em;
  text-align: center;
  padding-top: 1.25em;
  z-index: 1;
  position: relative;
  color: white;
  text-shadow: 0 0 15px black;
}

.frontname {
  font-size: 2em;
  padding-bottom: .2em;
}

.navbar {
  font-family: Futura, Futura-Medium, "Futura Medium", "Century Gothic", CenturyGothic, "Apple Gothic", AppleGothic, "URW Gothic L", "Avant Garde", sans-serif;
  letter-spacing: 3px;
  background-color: #000;
  position: fixed;
  top: 0;
  width: 100%;
  color: white;
  margin: 0px;
  padding 0px;
}

.name {
  float: left;
  padding: 2em;
  text-transform: uppercase;
}

.links {
  float: right;
  text-decoration: none;
  color: white;
  padding: 2em .45em;
}

.list {
  font-size: .45em;
  list-style-type: none;
  text-decoration: none;
}

a {
  text-decoration: none;
}

.pagetitle {
  text-align: center;
  font-size: 3em;
  text-transform: uppercase;
  letter-spacing: 4px;
}

.SDmain {
  margin-top: 45px;
}

/*----------PAGE SPECIFIC STYLES-----------*/

.contactinfo {
  text-align: center;
  letter-spacing: px;
  font-size: 1.5em;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.contact-social-media-block {
  position: fixed;
  left: 50%;
  bottom: 0;
  transform: translate(-50%)
}

.sm {}

.contact-social-media {
  height: 8vh;
  width: 8vw;
}

.email-link {
  text-decoration: none;
}

.about-title {
  font-size: 10em;
  text-transform: uppercase;
  text-align: center;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.about-body {
  text-align: center;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 2em;
}

.b {
  display: none;
}

.c {
  display: none;
}

.d {
  display: none;
}

.e {
  display: none;
  font-size: 1.5em;
}

.f {
  display: none;
}

.g {
  display: none;
}

.h {
  display: none;
}

.article {
  color: white;
  width: 85%;
  margin: auto;
  margin-top: 1em;
}

.article-title {
  font-size: 1.75em;
  text-transform: uppercase;
}

.article-sub,
.article-date,
.port-sub {
  font-family: helvetica;
  font-style: italic;
}

.article-body,
.port-desc {
  text-indent: 1.75em;
  line-height: 1.2em;
}

.port-table {
  display: table;
  margin-top: 1.25em;
}

.port-row {
  display: table-row;
  margin-top: 1.25em;
}

.port-image {
  display: table-cell;
  float: left;
  width: 35%;
  margin: 0 2.5%;
}

.port-text {
  display: table-cell;
  float: right;
  width: 55%;
  margin: 0 2.5%;
}

.port-title {
  font-size: 2em;
  text-transform: uppercase;
}

/*-----------Animations and JQuery---------*/

.button {
  background-color: transparent;
  border: none;
  color: white;
  padding: 10px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  text-align: center;
  position: fixed;
  bottom: 5%;
  left: 50%;
  transform: translate(-50%)
}

.preopen {
  left: 150% !important;
}

.open {
  left: 50% !important;
}

.closed {
  left: -50% !important;
}

.transition {
  -webkit-transition: left 0.3s ease-out;
  -moz-transition: left 0.3s ease-out;
  -o-transition: left 0.3s ease-out;
  transition: left 0.3s ease-out;
}

.preopen2 {
  opacity: 0 !important;
}

.open2 {
  opacity: 1 !important;
}

.closed2 {
  opacity: 0 !important;
}

.transition2 {
  -webkit-transition: opacity 0.3s ease-out;
  -moz-transition: opacity 0.3s ease-out;
  -o-transition: opacity 0.3s ease-out;
  transition: opacity 0.3s ease-out;
}

#text1 {
  min-width: 67vw;
}

/*------------------FERNTS-----------------*/

@font-face {
  font-family: Futura;
  src: url(fonts/futuramedium.otf) format('opentype');
}

@font-face {
  font-family: Futura-Medium;
  src: url(fonts/futural-webfont.svg);
}

/*----------VIDJER---------*/

#myVideo {
  position: fixed;
  right: 0;
  bottom: 0;
  min-width: 100%;
  min-height: 100%;
  z-index: 0;
}

/*-----------MEDIA QUERIES-------------*/

@media all and (min-width: 1800px) {
  .frontname {
    font-size: 5em;
  }
  .list {
    font-size: 1em;
  }
  .break {
    display: none;
  }
  .contactinfo {
    font-size: 4em;
    letter-spacing: 6px;
  }
  .pagetitle {
    padding-top: 1em;
    font-size: 11em;
  }
  .navbar {
    font-size: 3em;
  }
  .about-title {
    font-size: 40em;
  }
  .port-row {
    font-size: 3em;
  }
  .article {
    font-size: 3em;
  }
}

@media all and (min-width: 1200px) and (max-width: 1799px) {
  .frontname {
    font-size: 3em;
  }
  .list {
    font-size: 1em;
  }
  .break {
    display: none;
  }
  .contactinfo {
    font-size: 2em;
    letter-spacing: 6px;
  }
  .pagetitle {
    padding-top: 1em;
    font-size: 5em;
  }
  .navbar {
    font-size: 1.4em;
  }
}

@media all and (min-width: 900px) and (max-width: 1199px) {
  .break {
    display: none;
  }
  .contactinfo {
    font-size: 1em;
    letter-spacing: 4px;
  }
  .pagetitle {
    padding-top: 1em;
    font-size: 4.5em;
  }
  .navbar {
    font-size: 1em;
  }
}

@media all and (min-width: 600px) and (max-width: 899px) {
  .frontname {
    font-size: 2em;
  }
  .list {
    font-size: .6em
  }
  .contactinfo {
    letter-spacing: 4px;
  }
  .pagetitle {
    padding-top: 1em;
    font-size: 4.5em;
  }
  .navbar {
    font-size: 1em;
  }
}

@media all and (max-width: 599px) {
  .frontname {
    font-size: 1.4em
  }
  .list {
    font-size: .6em
  }
  .contactinfo {
    font-size: 1em;
    letter-spacing: 2px;
  }
  .pagetitle {
    font-size: 3em;
  }
  .navbar {
    font-size: .5em;
  }
  .about-title {
    font-size: 4em;
  }
}

Hello

Welcome.
My name is Erik.
I enjoy Minimalism.

I made this happen with
Javascript and JQuery.

I like Java as well.
Programs just make sense to me.

I have made apps for android, websites for my friends, and I am looking for new projects.
You can find my other works in the Portfolio.

I write about my life occasionally. If that interests you, it drains out of my head into my Blog.

I am currently seeking my first job in Software Development.

My Resume can be found on the Contact page.

Thank you for reading.

  <button class="button" id="b"> Play </button>


First, your weather color list is unique by weather key, and you're querying the color based on it. I'd suggest turning this into an object of colors keyed by weather condition. This way, it's easier to locate the colors by condition than using a loop. You also gain one extra advantage: you can add your special cases of Clear in the same object, just keyed with a unique key value.
Next, you'll want to assign those properties into variables. Long property accesses are hard to read.
Now you'll want to split your logic. In your code, you're mixing color selection logic with background setting logic in a conditional. It's always important to figure out what thing is actually conditional from what can be extracted off of it. In this case, only color1 and color2 are conditional, not the setting of the background.
Here's how I'd do it.

const colorsByCondition = {
  Clear: {
    color1: '#7AE7C7',
    color2: '#72C1E1'
  },
  // Special forms of Clear
  Clear5: {
    color1: '#89a1dd',
    color2: '#E4E5E7'
  },
  Clear15: {
    color1: '#C94926',
    color2: '#BB9F34'
  },
  // Other conditions
  Clouds: {
    color1: '#F981BB',
    color2: '#7F7E84'
  },
  // and so on...
}

// Assign to variables
// const weather = weather.list[0]
// const temp = weather.main.temp
// const conditions = weather.weather[0].main

// Assuming these values represent our weather
const temp = 6
const conditions = 'Clear'

// Find the right colors
const { color1, color2 } = temp < 5 && conditions == 'Clear'
  ? colorsByCondition.Clear5
  : temp > 15 && conditions == 'Clear'
    ? colorsByCondition.Clear15
    : colorsByCondition[conditions]

// Apply to the body
document.body.style.backgroundImage = `linear-gradient(to bottom right, ${color1}, ${color2})`


Redundant headers
Read
https://github.com/psf/requests/blob/master/requests/models.py#L514 - your use of
    headers = {"content-type": "application/x-www-form-urlencoded"}

should not be needed.
Out-of-order progress
You print
    print(f"connecting to URL: {self.login_url}")

when this has already happened. Either say "connected to", or move this statement before your post.
Exception degradation
Resist the urge to sabotage the Python exception system. Rather than returning booleans from your methods, call response.raise_for_status, and optionally wrap that in a try/except/raise MyException() from e with your own exception type. raise_for_status will also obviate your status code checks.


A couple of minor things:

Some people like to always declare what interfaces a class implements, for the sake of clarity. Thus, you could have your subclasses of AbstractImageProcessor also specify implement Runnable.
For consistency, I would rename ImageIOProcessor to AbstractImageIOProcessor.
Not so minor, I would have the method create in ImageProcessorFactory to return an interface, not an abstract class.
While naming is not easy, perhaps you could find a better alternative to ImageIOFileWriter and ImageIOBase64Writer, because they're not only image writers, they also read. They are processors as your other classes.
Do you have any other class extending AbstractImageProcessor besides ImageIOProcessor? If not, maybe you don't need both.


Your code looks good enough. "optimize" is a vague action.

1. /* highlight input, if it is empty */
2. jQuery(function ($) {
3.     function toggleHighlightIfEmpty() {
4.         var $this;
5.         $this = $(this);
6.         $this.toggleClass('highlight-input', !$this.val());
7.     }
8.     $('#id_index-EditForm-gpnr').on('keyup.highlight', toggleHighlightIfEmpty).trigger('keyup.highlight');
9. });

Line 2:

I'd use the aliasing form of document.ready to prevent conflicts with other libs

Line 3:

I'd use the function declaration form over variable declaration form for the internal function. It's really a personal preference sort-of-thing. Additionally, using camelCase is relatively standard for JavaScript function names.

Lines 4-6:

I'd store a reference to $this so that you don't keep calling the jQuery factory function. It shouldn't be significant in any way for performance, but it can save some headaches with perens which can be easily misplaced

Line 8:

I'd set the event using a namespaced event name so that it can be triggered and removed simply by calling $(...).off('keyup.highlight'). Instead of passing the function to each again, I prefer to use trigger. If you need backwards compatibility, use bind instead of on.

None of these "optimizations" should lead to code that's in any significant way different as far as performance is concerned. It really comes down to personal preference.


Project Euler problem 92 in Scala, square digit chains

Let's start off with your code to convert to the sum of digits.

number.toString.toList.map(_.toString).map(_.toInt).map(x => x * x).sum

First of all, a String can already be treated as List[Char], so that toList is unnecessary. Also, instead of converting from Char to String to Int, you can just call asDigit. And while we're at it, let's stuff that in a function, so that we know what's going on when we call that line. After all that, the line looks like:

def sumSquareDigits(number: Int): Int = number.toString.map(_.asDigit).map(x => x*x).sum

Now, you had the right idea in creating a hash. However, as an array of Booleans it's hard to tell what's been set and what hasn't. For now, let's start with a HashMap, since it's the most obvious construct for a cache. If it were too slow you could worry more about optimization, but at least on my computer it's sufficient to solve it. This has the added advantage of not needing to cache values that aren't repeated. Instead of needing to fill in 10,000,000 integers (I don't have that kind of spare RAM), it only ends up needing to cache 495 values. Additionally, since we're using the cache inductively, we should prepopulate the cache with our base case:

val cache = scala.collection.mutable.HashMap[Int,Int](1->1,89->89)

Now, we want to see whether a value converges to 1 or 89. We can do this by recursively calling the hash on the sumSquareDigits defined above until we get an answer, placing the results of any new stuff into the cache. We'll use a helper function just for simplicity:

def addValueToCache(number: Int) =
{
  val converged = getConvergedValue(number)
  cache.put(number,converged)
  converged
}
def getConvergedValue(number: Int) = cache.getOrElse(sumSquareDigit(x), addValueToCache(sumSquareDigit(x))

And now we just need to check which values converge to 89,

def checkAll(max: Int): Int=
  (1 until max).map(getConvergedValue).filter(_ == 89).size

then call it from main!

def main(args: Array[String]): Unit =
{
  println("Answer: "+checkAll(10000000))
}

Notice how using if statements for flow control is entirely unnecessary here. Functional programming style tends to do flow control with monadic operations (filter, map, flatMap, flatten, etc...) or pattern matching. If you're trying to stick to a functional style, when you see a lot of nested if statements you should be wondering if there's a better way to do it.