texts: User registration - Controller, service and repository layers in Spring framework

texts:
I'm writting a registration feature currently and I I'm confused how to divide logic between layers. Can you review this code and tell if it's good way to do? In try-catch block I publish event to send verification email to new User.

Should I keep in my Controller class just AuthService field? I'm using userRepository to check if username and email is available.
In AuthService should I keep just authRepository and other services fields? Currently I'm using there RoleRepository.
Is return type in my controller a good practise? ApiRespose is two-field class.

Controller:

@PostMapping("/signup")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest, HttpServletRequest httpServletRequest) {
    if (userRepository.existsByUsername(signUpRequest.getUsername())) {
        return new ResponseEntity(new ApiResponse(false, "Username is already in use!"), HttpStatus.BAD_REQUEST);
    }

    if (userRepository.existsByEmail(signUpRequest.getEmail())) {
        return new ResponseEntity(new ApiResponse(false, "Email is already in use!"), HttpStatus.BAD_REQUEST);
    }

    User user = new User(signUpRequest.getName(), signUpRequest.getUsername(), signUpRequest.getEmail(), signUpRequest.getPassword());

    User resultUser = authService.createUser(user);

    try {
        String host = httpServletRequest.getHeader("apphost");
        eventPublisher.publishEvent(new OnRegistrationCompleteEvent(resultUser, host));
    } catch (Exception e) {
        e.printStackTrace();
    }

    URI location = ServletUriComponentsBuilder
            .fromCurrentContextPath().path("/users/{username}")
            .buildAndExpand(resultUser.getUsername()).toUri();

    return ResponseEntity.created(location).body(new ApiResponse(true, "User registered successfully"));
}

Service:

@Override
public User createUser(User user) {
    user.setPassword(passwordEncoder.encode(user.getPassword()));

    Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
            .orElseThrow(() -> new AppException("User Role not set."));

    user.setRoles(Collections.singleton(userRole));

    return userService.saveRegisteredUser(user);
}


texts:
I am trying to design thread-safe data structure that I cna use as a buffer in my application. Can you please give me comments about this code and what can be improved:

#include <deque>
#include <thread>
#include <mutex>
#include <condition_variable>

template <typename T>
class Buffer
{
public:
    void add(T num)
    {
        while (true)
        {
            std::unique_lock<std::mutex> locker(mu);
            buffer.push_back(num);
            locker.unlock();
            cond.notify_all();
            return;
        }
    }
    T remove()
    {
        while (true)
        {
            std::unique_lock<std::mutex> locker(mu);
            cond.wait(locker, [this](){return buffer.size() > 0;});
            T back = buffer.back();
            buffer.pop_back();
            locker.unlock();
            cond.notify_all();
            return back;
        }
    }
    int size()
    {
        std::unique_lock<std::mutex> locker(mu);
        int s = buffer.size();
        locker.unlock();
        return s;
    }
private:
    std::mutex mu;
    std::condition_variable cond;

    std::deque<T> buffer;
};


texts:
I have a helper method to clean up a string and remove pieces that I will be generating again. (defined by the "SpecialKey" Constants) but I've never been real happy with the code. Although I find it easy to read adding more keys doesn't always seem so clean.

    protected static System.String[] GetStringParts(System.String stringValue)
    {
        System.String[] stringParts = stringValue.Split('!');

        System.Func<System.String, System.Boolean> isConstKey = (System.String key) =>
        {
            return !System.String.IsNullOrWhiteSpace(key) && (
                    key.StartsWith(MyUtility.SpecialStringKey1) ||
                    key.StartsWith(MyUtility.SpecialStringKey2) ||
                    key.StartsWith(MyUtility.SpecialStringKey3) ||
                    key.StartsWith(MyUtility.SpecialStringKey4)
                );
        };
        return stringParts.Where(key => !isConstKey(key)).ToArray();
    }

I have removed specific names and such. I don't usually go by the convention SpecialKey1/2 etc

I'd like any pointers on performance or readability. This code gets hit often but in the last two years has only been changed once (maybe twice).


texts: How to get cordinates of selected numbers which are from array?

texts:
You are given to paint a floor area of size A. There will be 12 paint buckets from 4 primary
colors with each having 3 shades (i.e. total 12 buckets). The bucket size, or more specifically,
the amount of area you can paint from each shade is given in the following arrays.
The different shades of the same primary color are shown in the same row.

[12, 23, 14]
[10, 30, 15]
[16, 22, 35]
[14, 24, 20]

Problem & Constraints

You need to select 4 shades to paint the floor area such that;

Entire floor area should be painted; also no overlaps of shades are allowed
"One and only one" shade from each primary color has been selected for the final painting
Amount of wastage is minimized (i.e. assume once we open and use a bucket, any
remainings will be discarded)

Implement a python program to answer the following problems;

Q1. The color shades (or buckets) satisfying the above constraints (if A = 100)
Q2. The amount of wastage in the above scenario
Q3. What will be the solution for Q1 and Q2 if A = 90?

Note: You may use the below notation to reference each shade in the above map.

R - row index
C - column index
(r,c) - shade in (r+1)th row and (c+1)th column
e.g. (0,0) -> 12, (0,1) -> 23, (1,2) -> 15, etc.

With this, the answer for Q1 can be given in the format [(0,1), (1,2), (2,0), (3,2)]

If user enter 100 system should display color code areas with their coordinates which sum are most close to 100

Example

Enter your Area = 100
100 ~ 101(sum of areas 12+30+35+24, There for 101 is the closet number to 100)

Shades          = [12 30 35 24]
Cordinates of shades = (0,0)(1,1)(2,2)(3,1)

This is my answering code

import numpy as np
import itertools

colors = np.array([[12, 23, 14], [10, 30, 15], [16, 22, 35], [14, 24, 20]])

max_tot = 0

#get total of all integers which are in array
for i in range(len(colors)):
    max_tot = max_tot + max(colors[i])

#Enter Area
area = int(input("Enter your Area = "))

if(area > max_tot):
    print("Area is too long. Don't have enough paints for painting")
elif(area <= 0):
    print("Wrong area")
else:
    #get shades which are given lowest minimum wastage
    for element in itertools.product(*colors):
        if(sum(element) >= area):
            x = sum(element)
            if(x <= max_tot):
                max_tot = x
                el = np.array(element)

    print()
    print("sum of shades   =", max_tot)
    print("minimum wastage =" , max_tot - area)
    print("Shades          =", el)
    print("Cordinates of shades = " ,end ='')

    #get coordinates using manual method
    for i in range(4):
        g,h = np.where(colors == el[i])
        print("(" ,g[0],",", h[0], ")", sep=' ', end='', flush=True)

Output -:

Enter your Area = 100

sum of shades   = 101
minimum wastage = 1
Shades          = [12 30 35 24]
Cordinates of shades = ( 0 , 0 )( 1 , 1 )( 2 , 2 )( 3 , 1 )

You can see I have got coordinates of 12 30 35 24 is manual type. That is not a good programming method.

How can I get that coordinates directly(using better way)?

Note that I have done all question. I want a better answer for Q3


texts: Creative triangle stacks using for loops

texts:
I was wondering if someone can help me out with achieving the following result (using for loops):

|../\..../\..|
|./\/\../\/\.|
|/\/\/\/\/\/\|

This is the code that I have written:

public static void drawBody1(){
  for (int line = 1; line <= 3; line++){
      System.out.print("|");
      for (int dot = 1; dot <= (-1 * line + 3); dot++){
        System.out.print(".");
      }
      for (int mount = 1; mount <= line; mount++){
        System.out.print("/\\");
      }
      for (int dot = 1; dot <= (-2 * line + 6); dot++){
        System.out.print(".");
      }
      for (int mount = 1; mount <= line; mount++){
        System.out.print("/\\");
      }
      for (int dot = 1; dot <= (-1 * line + 3); dot++){
        System.out.print(".");
      }
      System.out.print("|");
      System.out.println();
  }

Although I did get the figure above, I realize that the code abounds in redundancy and is, thus, far from efficient.

I was hoping if someone can show me a simple yet elegant solution to this problem.


texts: Bash/zsh function that cd to the root of git tree

texts:
I'd like to get a review for the function that cd into the git tree root or does nothing if we are outside of the repository.
reviewed version:
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
  git_root() {
    local super_root
    local top
    top="$(git rev-parse --show-cdup)"
    top="${top:-./}"
    super_root="$(git rev-parse --show-superproject-working-tree)"
    if [[ "$super_root" ]]; then
      printf '%s' "$top../"
      ( cd "$top../" && git_root || return )
    fi
    printf '%s' "$top"
  }
  local git_root
  git_root="$(git_root)"
  [ "x${git_root}" != "x./" ] && cd "$(git_root)" && return || return 0
}

updated version:
#!/bin/bash
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
  function git_root {
    local top; top="$(git rev-parse --show-cdup)"
    top="${top:-./}"
    local super_root; super_root="$(git rev-parse --show-superproject-working-tree)"
    if [[ "$super_root" ]]; then
      printf '%s' "$top../"
      ( cd "$top../" && git_root || return )
    fi
    printf '%s' "$top"
  }
  local tree_root
  tree_root="$(git_root)"
  [[ "x${tree_root}" != "x./" ]] && cd "${tree_root}" && return || return 0
}


texts: Function that adds two items from a list in search of those that will match some given sum

texts:
I'm doing a Daily Challenges to get better with Python.
I completed the first challenges with a working code but I want to make sure if there's anyway to improve or optimize it.

I have a function that adds 2 items from a list in search of those that will match the already defined result.

def main():

  listA = [10,11,3,7]
  k = 21

  for i in listA:
    for e in listA:
      result = i + e
      if result == k:
        print(i, '+', e, ' = ', k)
        return
main()

I was thinking of reducing it to:

def main():
  k = 21
  listA=[10,11,3,7]
  print (k,'=',[(i and e) for i in listA for e in listA if k==(i+e)])
main()

… but that would print 21 = [10,11] instead of 21 = 10 + 11.


texts: Testimonial section CSS inheritance and proper use of HTML5 elements

texts:
I created this testimonial section as a prototype.

HTML

This was pretty good.

      – Bobby, Jersey City, NJ

This is pizza is the most bearable thing I ever had in Joisey. But it still sucks, just like everyone from there.

      – Vinny, New York, NY

I really savored the smoky undertones of the imported sausage. The cheese had a wonderful texture. It paired well with my pinot noir in a dance of sensations.

      – Alex, San Francisco, CA

CSS

.testimonials {
  width: 720px;
  max-width: 96%;
  margin: 0 auto;
}
.testimonials blockquote {
  background-color: #fff;
  border-left: 4px #61acca solid;
  font-size: 21px;
  line-height: 1.6;
}

.testimonials blockquote {
  padding: 10px 20px;
}

.testimonials blockquote {
  background-image: url('http://shared-assets.s3.amazonaws.com/codepen/img/elements/quotes/quote-999.jpg');
  background-repeat:no-repeat;
  background-size: 33px 45px;
  background-position: 10px 5px;
}

.testimonials cite {
  font-size: 0.7em;
  font-style: normal;
}
.author {
  font-weight: bold;
  font-size: 1.3em;
  margin: 0 6px 0 36px;
}
p { margin: 0 0 0 36px; }


texts: 100 chairs in a circle problem solving with Angular.js and visualization

texts:
Here is the problem statement:

  Take a second to imagine that you are in a room with 100 chairs arranged in a circle. These chairs are numbered sequentially from One to One Hundred. At some point in time, the person in chair #1 will be told to leave the room. The person in chair #2 will be skipped, and the person in chair #3 will be told to leave. Next to go is person in chair #6. In other words, 1 person will be skipped initially, and then 2, 3, 4.. and so on. This pattern of skipping will keep going around the circle until there is only one person remaining- The survivor! Note that each chair is removed when the person leaves the room.

Please review my attempt below considering the following points:

Correctness (I am getting the winner as # 31)
Any chances for optimization

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', [ '$scope', '$interval', '$log', function($scope, $interval, $log){

  $scope.init = function(){
    $scope.people = [];
    $scope.logs = [];

    // get the 100 people/chair
    for(var i=1; i<=100; i++){
      $scope.people.push({ index: i });
    }
  };

  $scope.startFiring = function(){

    var fireIndex = 0, // for removing the person at this index
        skipCount = 0; // for incremental counting

    if($scope.people.length >= 1){ // if start button clicked again
      $scope.gotWinner = false; // hide the winner
      $interval.cancel(fireInterval); // stop the interval
      $scope.init();
    }

    var fireInterval = $interval(function(){

      $scope.disableStartButton = true;

      if ($scope.people.length > 1) { // if more than 1 people
        $scope.logs.push({text: 'Firing #' + $scope.people[fireIndex].index}); // show the log

        $scope.people.splice(fireIndex, 1); // fire!

        // increment
        skipCount += 1;
        fireIndex += skipCount;

        //if fireIndex becomes greater than $scope.people.length, then set fireIndex to remainder from fireIndex / $scope.people.length
        if(fireIndex > $scope.people.length){
          fireIndex %= $scope.people.length;
        }

      } else {
        $interval.cancel(fireInterval); // stop the interval
        $scope.gotWinner = true; // show the winner
        $scope.disableStartButton = false;
      }
    }, 500); // every 1/2 sec.

  };

  $scope.init(); // intialize the chair/people when the view is loaded or start is clicked again

}]);
body{
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}

span{
  display: inline-block;
  padding: 5px;
  margin: 4px;
  border-radius: 3px;
  background: #000000;
  color: #FFFFFF;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JS Bin</title>

        {{person.index}}

      <button ng-click="startFiring()" ng-disabled="disableStartButton">Start!</button>

And the winner is.... # {{people[0].index}}!

Logs:

{{log.text}}


texts: Project Euler #1: multiples of 3 and 5 Ruby

texts:
Total newbie here and wouldn't mind learning from Rubyists to look at how I tried to solve this challenge.

I started with 2 variables n which starts at 0 and total which is an array where I intend to push n if it satisfy the condition set by the 2 modulo. Using the until loop with a max of 1000, my intention was to change total from an empty array with values divisible by 3 and 5.

With total now with array items, I defined a method to take in total as a parameter that I can iterate to add values to a new method variable - sum. The method then returns the new value of sum.

Here's my code.

n = 0
total = []

until n >=1000 do
  if n % 3 == 0 || n % 5 == 0
    total << n
  end
  n += 1
  total
end

def sumTotal(total)
  sum = 0
  total.each { |i| sum+= i.to_i}
  puts sum
end

sumTotal(total)


texts:
I have the following code:

public final class PropertyFileLoader {

    private static final Logger logger = LoggerFactory.getLogger(PropertyFileLoader.class);

    private final String propertyFileName;

    public PropertyFileLoader (String propertyFileName) {
        this.propertyFileName = propertyFileName;
    }

    public Properties getClasspathFileAsStream () {
        final Properties properties = new Properties();
        final InputStream is = getClass().getClassLoader().getResourceAsStream(propertyFileName);

        try {
          properties.load(is);
        }
        catch (final IOException e) {
          logger.error(e.getLocalizedMessage(), e);
         //      throw new IOException();
        }
        return properties;
    }
}

How do you think, should I use static methods instead of constructor?
The usage of this class:

final PropertyFileLoader loader = new PropertyFileLoader("flyway.properties");
final Properties flywayProperties = loader.getClasspathFileAsStream();

And I think add the static method such as

public static Properties getClasspathProperties(String propertyFileName){
    final PropertyFileLoader loader = new PropertyFileLoader(propertyFileName);
    return loader.getClasspathFileAsStream();`
}

Should I throw IOException, if I use classpath directory? If yes, why?

Could I use this class as Spring @Component with @Value?
I found how to @Autoware constructor with param using @Value annotation, but how to use this at another class?


texts: Is this an acceptable MVVM Model with IEditableObject implementation?

texts:
I'm trying to follow MVVM pattern in a VB.net WPF application, and I would like to implement IEditableObject.

Is this code acceptable for an MVVM application? In particular is it okay to have the IEditableObject implemented here on the Model rather than the ViewModel?

Public Class Component : Implements IEditableObject
    Property Name As String
    Property Part_Number As String
    Property Position_Count As Integer
    Property Stage as Integer
    Private _stored_properties As Hashtable = Nothing

    ReadOnly Property Full_Name As String
        Get
            Return Name + " " + Stage.ToString()
        End Get
    End Property

    Public Sub BeginEdit() Implements IEditableObject.BeginEdit
        Dim properties = Me.GetType.GetProperties
        _stored_properties = New Hashtable(properties.Length - 1)
        For Each prop In properties
            If prop.GetSetMethod IsNot Nothing Then _stored_properties.Add(prop.Name, prop.GetValue(Me, Nothing))
        Next
    End Sub

    Public Sub EndEdit() Implements IEditableObject.EndEdit
        _stored_properties = Nothing
    End Sub

    Public Sub CancelEdit() Implements IEditableObject.CancelEdit
        If _stored_properties Is Nothing Then Return
        Dim properties = Me.GetType.GetProperties
        For Each prop In properties
            If prop.GetSetMethod IsNot Nothing Then prop.SetValue(Me, _stored_properties(prop.Name))
        Next
    End Sub
End Class


texts:
Working with futures and .then, I keep running into the problem of needing to "capture by move" in a lambda. In fact, not only that, but when implementing e.g. when_all, I find myself needing to capture a whole parameter-pack. Neither of these things are supported out of the box in C++17.

However, we can capture a whole parameter pack "by forward", using std::forward_as_tuple and std::apply. So I decided to write a std::move_as_tuple that would do the same thing as forward_as_tuple but for moving instead of forwarding.

How does this code look? And is there a simpler way to accomplish my goal?

template<class... Types>
constexpr auto move_as_tuple(Types&&... args)
{
    return std::forward_as_tuple(std::move(args)...);
}

Sample usage (which is also fair game for critique):

future<std::tuple<>> when_all()
{
    promise<std::tuple<>> p;
    p.set_value({});
    return p.get_future();
}

template<class F, class... Rest>
future<std::tuple<F, Rest...>> when_all(F f, Rest... rest)
{
    return f.then([rest = move_as_tuple(rest...)](auto f) {
        auto w = [](auto&&... as) { return when_all(std::forward<decltype(as)>(as)...); };
        return std::apply(w, rest).then([f = std::move(f)](auto future_of_tuple_of_rest) {
            return std::tuple_cat(std::make_tuple(std::move(f)), future_of_tuple_of_rest.get());
        }).get();
    });
}


texts: PHP loop to generate an HTML form for the days in the coming week

texts:
There are two arrays, $states and $weekdays. I want to loop through them to create a form, an HTML table, or possibly some other element).

Here's my example:

// addDay() Adds 1 day to the date
// format() Returns a date in a new format
// get_date() returns todays date in unix

$weekdays = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ];
$states   = [ 'start', 'finish', 'total', 'overtime' ];
$date     = get_date();

foreach ( $states as $state ) { ?>
  <tr class="<?php echo $state; ?>">
    <?php echo $state; ?>
    <?php
    $d = 0;
    foreach ( $weekdays as $weekday ) { ?>

        <input name="date<?php echo $date->addDay( $d )->format('[Y][m][d]') . '[' . $state . ']'; ?>" />

    <?php
    $d++;
      } ?>

<?php
}

I think the code can be cleaner. Ignore the fact that there aren't comments. Focus on the HTML / PHP intertwining. Can it be separated further or tidier?

Is there a method of sprintf but for sections of code perhaps? or would you echo the whole thing with double quotes for the variables?

Note — I am using PHP7, so be as fancy as you want with the latest syntax;


texts: Minimum number of swaps required to sort the array in ascending order

texts:
Here is my problem statement. An excerpt:

You are given an unordered array consisting of consecutive integers ∈ [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.
For example, given the array arr = [7, 1, 3, 2, 4, 5, 6] we perform the following steps:

i   arr                     swap (indices)
0   [7, 1, 3, 2, 4, 5, 6]   swap (0,3)
1   [2, 1, 3, 7, 4, 5, 6]   swap (0,1)
2   [1, 2, 3, 7, 4, 5, 6]   swap (3,4)
3   [1, 2, 3, 4, 7, 5, 6]   swap (4,5)
4   [1, 2, 3, 4, 5, 7, 6]   swap (5,6)
5   [1, 2, 3, 4, 5, 6, 7]

It took 5 swaps to sort the array.

The code:
int minimumSwaps(int arr_count, int* arr) {

long long int i,count=0,j,temp,min,min_index;
for(i=0;i<arr_count;i++)
{
    min=arr[i];
    min_index=i;
    for(j=i+1;j<arr_count;j++)
    {
        if(arr[j]<min)
        {
            min=arr[j];
            min_index=j;
        }
    }
    if(min_index!=i)
    {
        count++;
    temp=arr[min_index];
    arr[min_index]=arr[i];
    arr[i]=temp;
    }
    }
return count;
}

5 out of 15 test-cases are failing. Here is one of the test cases. It is failing with a message as "Terminated due to timeout".
I used selection sort approach as selection sort makes minimum swap operation.
My time complexity is O(n^2). Can I reduce it?


texts: Loop through folder names on a server directory

texts:
I have the following code to loop through a directory of folders and print all folders names with their paths in a worksheet. This is a follow up question to this one: Excel VBA - Get Folder Names
Looking for code optimization for faster and better performance.

Sub PrintFolders()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim objFSO As Object
    Dim objFolder As Object
    Dim objSubFolder As Object
    Dim i As Integer
    Dim Folder_Name As String

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.StatusBar = ""

    Set wb = ThisWorkbook
    Set wsControl = wb.Sheets("Control"): Set wsOutput = wb.Sheets("Output")
    Folder_Name = wsControl.Cells(1, 2)
    If Folder_Name = "" Then
        MsgBox "Path location is not entered. Please enter path"
        wsControl.Cells(1, 2).Select
        End
    End If
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder(Folder_Name)

    i = 1
    Dim MyArr() As Variant
    ReDim MyArr(1 To i, 1 To 2)
    On Error GoTo CleanFail

    Application.EnableCancelKey = xlErrorHandler
    Const IterationsToUpdate As Integer = 10
    For Each objSubFolder In objFolder.subfolders
        MyArr(i, 1) = objSubFolder.Name
        MyArr(i, 2) = objSubFolder.Path
        i = i + 1
            MyArr = Application.Transpose(MyArr)
            ReDim Preserve MyArr(1 To 2, 1 To i)
            MyArr = Application.Transpose(MyArr)
        If i Mod IterationsToUpdate = 0 Then
            Application.StatusBar = objSubFolder.Path & " " & objSubFolder.Name
            DoEvents
        End If
    Next objSubFolder
    Application.StatusBar = ""

    wsOutput.Rows("2:1048576").Delete
    Dim Destination As Range
    Set Destination = wsOutput.Range("A2")
    Destination.Resize(UBound(MyArr, 1), UBound(MyArr, 2)).Value = MyArr
    wsOutput.Columns.EntireColumn.AutoFit: wsOutput.UsedRange.HorizontalAlignment = xlCenter
    wsOutput.Activate

    MsgBox ("Done")

    CleanExit:
    Application.StatusBar = False
    Application.StatusBar = ""
    Application.Cursor = xlDefault
    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    Exit Sub

    CleanFail:
    Const MsgTitle As String = "Operation not completed"
    If Err.Number = 18 Then
        MsgBox "Operation was cancelled.", vbInformation, MsgTitle
    Else
        MsgBox "An error has occurred: " & Err.Description, vbCritical, MsgTitle
    End If
    Resume CleanExit

End Sub


texts: Proper usage of "using" statement in base64 encode method

texts:
I used the example on here, but with little changes in order to write a base64 encoder method. I have a few points about the code:

I would like to use using statement, but I do not want to use inner "using" statements, so I use multiple variable declaration in a single "using" statement. Is that suitable in order to benefit from "using" statement for more than one object. Moreover, what are alternatives?
Inside the using statement block, I used different try-catch blocks for each operation that can be throw an exception. I did not catch specific exceptions first an just use Exception class, but my goal is just return true or false which indicates the success status of the method. Is it a good practice to use different try-catch blocks and use "return" statement inside these blocks for resource handling?
Also, I would like to use an extra try-catch block which surrounds the using blocks for the classes which have Dispose() methods that can throw exceptions also. This is also discussed here. Is that a common approach, or should I completely stop using using statements, for these cases.

 public static bool ConvertToBase64(string inputFile, string outputFile)
 {
     try
     {
         using (FileStream inputFileStream = new FileStream(inputFile, FileMode.Open),
                outputFileStream = new FileStream(outputFile, FileMode.Create))
         {
             try
             {
                 ToBase64Transform base64Transform = new ToBase64Transform();
                 //Buffers for read/write operations
                 Byte[] outputBuffer = new byte[base64Transform.OutputBlockSize];
                 Byte[] inputBuffer = new byte[inputFileStream.Length];
                 //Offset to count the number of bytes transformed so far
                 int inputOffset = 0;

                 try
                 {
                     inputFileStream.Read(inputBuffer, 0, (int)inputFileStream.Length);
                 }
                 catch(Exception ex)
                 {
                     return false;
                 }

                 if (false == base64Transform.CanTransformMultipleBlocks)
                 {
                     while (inputBuffer.Length - inputOffset > base64Transform.InputBlockSize)
                     {
                         //Transform a block of input data
                         base64Transform.TransformBlock(inputBuffer, inputOffset, inputBuffer.Length - inputOffset, outputBuffer, 0);
                         inputOffset += base64Transform.InputBlockSize;

                         try
                         {
                             outputFileStream.Write(outputBuffer, 0, base64Transform.OutputBlockSize);
                         }
                         catch(Exception ex)
                         {
                             return false;
                         }

                         //Insert a new line after 76 characters
                         if (inputOffset % 19 == 0)
                         {
                             byte[] newline = Encoding.ASCII.GetBytes(Environment.NewLine);
                             outputFileStream.Write(newline, 0, newline.Length);
                         }
                     }
                 }

                 //Final block transform
                 try
                 {
                     byte[] lastBlock = base64Transform.TransformFinalBlock(inputBuffer, inputOffset, inputBuffer.Length - inputOffset);
                     outputFileStream.Write(lastBlock, 0, base64Transform.OutputBlockSize);
                 }
                 catch(Exception ex)
                 {
                     return false;
                 }

                 if (false == base64Transform.CanReuseTransform)
                 {
                     base64Transform.Clear();
                 }
             }
             catch(Exception ex)
             {
                 return false;
             }
         }
     }
     catch(Exception ex)
     {
         return false;
     }

     return true;
 }


texts: How can I make this CouchDB view code more "correct"?

texts:
I have a fairly simple app set up with couchrest_model to capture data pulled in from vendors to couchdb for later searching and archiving. Each document has a show (the name of the vendor), a datatype (which is limited to seven or eight unique strings), and a pulled_at timestamp field.

The core method on this model needs to return a Hash where each key is a show and the value is an array of the most recent document for each datatype. Below, I have my (simplified) model code which defines this method. It works, but my code in self.most_recent_by_type_and_show() which loops over the list of _ids and calls get() on each one (thus generating n HTTP requests on each method call) will not scale.

class Snapshot < CouchRest::Model::Base
  property :show, String
  property :sources, [String]
  property :pulled_at, DateTime
  property :datatype, String
  property :data, [Hash]

  design do
    view :_most_recent_by_type_and_show, :map => <<-MAP, :reduce => <<-REDUCE
      function(doc) {
        if (doc.type == "Snapshot") {
          emit(doc.show, [doc.datatype, new Date(doc.pulled_at).valueOf()]);
        }
      }
    MAP
      function(keys, values, rereduce) {
        var maxes = {},
            out = [];

        if (!rereduce) {
          for (var i in keys) {
            var show = keys[i][0];
            var doc_id = keys[i][1];
            var datatype = values[i][0];
            var timestamp = values[i][1];

            if (typeof maxes[show] == 'undefined') { maxes[show] = {}; }
            if (typeof maxes[show][datatype] == 'undefined') { maxes[show][datatype] = [0, null]; }

            if (timestamp > maxes[show][datatype][0]) {
              maxes[show][datatype] = [timestamp, doc_id];
            }
          }
        }

        if (Object.keys(maxes).length == 0) { maxes = values; }
        for (var show in maxes) {
          for (var datatype in maxes[show]) {
            out.push(maxes[show][datatype][1]);
          }
        }

        return out;
      }
    REDUCE
  end

  class << self
    def most_recent_by_type_and_show opts = {}
      options = opts.merge({ reduce: true,  })
      raw = _most_recent_by_type_and_show(options).group.rows

      raw.reduce({}) do |hash, row|
        hash[row['key']] = row['value'].map { |id| get id }.sort_by(&:pulled_at).reverse
        hash
      end
    end
  end
end

This feels like I'm overcomplicating the view code, and I'm also not sure that my reduce function is written correctly for rereduce. I initially tried emitting [show, datatype, pulled_at] as the key and the entire doc itself as the value in the map function, but I've read that this is Bad Practice as it will cause the size of my view index to balloon over time. And for some reason, couchrest_model will not allow me to include_docs=true if I'm reducing a view, which seems to be just a limitation of the gem as I can't find anything saying this should be the case in the CouchDB docs.

Would this be better written as a different data structure altogether? Should I maybe be using a _list function? I'm not sure where to go from here.


texts:
I want to take user input strings and add them together with proper spacing.

HTML:

<input id="input" type="text" placeholder="Words Go Here"></input>
<button id="addWords">Add Words</button>

JavaScript:

(function () {

 $('#addWords').on('click', addWords);

 function addWords() {

    var value = $('#input').val();
    var firstChar = value.charAt(0);
    var lastChar = value.slice(-1);

     if ((/^[a-zA-Z\s]*$/.test(value)) && (value !== '')) {

         if (firstChar == ' ' && lastChar == ' ') {

            value = value.trimLeft().trimRight();

         } else if (firstChar == ' ') {

            value = value.trimLeft();

         } else if (lastChar == ' ') {

            value = value.trimRight();

         } else {

            value = value;
        }

        $('#output').append($('').text(value + ' '));

     } else {

        alert('Please use characters only.');

     }
 }

})();

Example:

JSFiddle

Is there a less-bulky (e.g. multiple if elses) method for stripping away additional spaces?


texts: Print numbers in a spiral from the center

texts:
#!/usr/bin/env stack
{- stack
     --install-ghc
     exec ghci
     --package lens
-}

module Main where

import Control.Lens
import Data.List.Lens
import Debug.Trace
import Text.Printf
import Prelude hiding (Left, Right)

data Direction = Up | Left | Down | Right

data Location = Location Int Int

type Grid = [[Int]]

main = printClockwise 25

printClockwise :: Int -> IO ()
printClockwise n = putStrLn $ concatMap printRow grid
  where
    grid = walk directions center 1 emptyGrid
    emptyGrid = replicate sq (take sq (repeat 0))
    printRow row = concatMap (printf "%4s" . show) row ++ "\n"
    -- Ex. for a 5x5 spiral the start location is (2,2)
    center = Location half half
    half = floor $ (fromIntegral sq) / 2
    -- This will return all directions we should walk through the spiral in.
    -- Something like [Right, Down, Left, Left, Up, Up, Right, Right, Right]
    directions = concatMap (\(direction, steps) -> take steps $ repeat direction) (zip directionOrder steps)
    directionOrder = cycle [Right, Down, Left, Up]
    -- Ex. for a spiral up to 25, the steps are 1, 1, 2, 2, 3, 3, 4, 4, 5
    steps = concatMap (take 2 . repeat) [1 .. sq - 1] <> [sq]
    -- Assume the input is a perfect square of an odd number
    sq = ceiling $ sqrt (fromIntegral n)

walk :: [Direction] -> Location -> Int -> Grid -> Grid
walk (dir : dirs) loc@(Location x y) current grid = do
  let grid' = grid & (ix y . ix x) .~ current
  let loc' = moveLocation dir loc
  walk dirs loc' (current + 1) grid'
walk [] _ _ numbers = numbers

moveLocation Down (Location x y) = Location (x) (y + 1)
moveLocation Right (Location x y) = Location (x + 1) (y)
moveLocation Left (Location x y) = Location (x -1) (y)
moveLocation Up (Location x y) = Location (x) (y - 1)

I came across this problem on reddit and thought it'd be fun to try my hand at it in Haskell. The idea is to generate the grid before printing, and the insight to generate that grid was that the movement follows a predictable pattern, of right, down, left, up, and the # of steps taken in a given direction is 1, 1, 2, 2, 3, 3, 4, 4... , n - 1, n -1, n , where n is the square of the input number. So with that you can walk through the grid and fill in the numbers.
The function has no input checking, it assumes the input is a perfect square (of an odd number).


texts: Comparing version numbers with JavaScript

texts:
I have written a function that compares two version number strings (e.g. 1.2.0 and 1.2.2) and return 1 if the first string is greater, -1 if the second string is greater and 0 if the strings are equal for a code challenge that I'm attempting.
Also, it's guaranteed that both strings contain an equal number of numeric fields and all decimals are non-negative.
So,

1.2.0 and 1.2.2 should return -1.
1.05.4 and 1.5.3 should return 1.
1.2.6.76 and 1.2.06.0076 should return 0.

My logic for the function was to simply split the string at each occurrence of the period ., compare each number and then add a character (e for equal, m for more and l for less) to a temporary variable z depending on the comparison result.
I then simply use some basic regex to return 1, -1 or 0 based on the content of the z variable as can be seen in the following Code Snippet:

function checkVersion(a,b) {
    let x=a.split('.').map(e=> parseInt(e));
    let y=b.split('.').map(e=> parseInt(e));
    let z = "";

    for(i=0;i<x.length;i++) {
        if(x[i] === y[i]) {
            z+="e";
        } else
        if(x[i] > y[i]) {
            z+="m";
        } else {
            z+="l";
        }
    }
    if (!z.match(/[l|m]/g)) {
      return 0;
    } else if (!z.match(/[l]/g)) {
      return 1;
    } else {
      return -1;
    }
}

console.log(checkVersion("1.2.2","1.2.0")); // returns 1 as expected
console.log(checkVersion("1.0.5","1.1.0")); // returns -1 as expected
console.log(checkVersion("1.0.5","1.00.05")); // returns 0 as expected
console.log(checkVersion("0.9.9.9.9.9.9","1.0.0.0.0.0.0")) // returns -1 as expected;

The above function seems to be working fine with any random two version numbers that I've tried so far but when I try to submit the above function for the challenge, there is always one hidden test with two unknown version numbers that keeps failing. What logic am I missing in the above code?

EDIT:
Thanks to @RomanPerekhrest's comment below, I have found out that my regex is the problem. Instead of using the 2nd regex, I just remove any occurence of e from the z variable using the split() method and then just check if the first character is m or l and now the function is working correctly as seen in the following Code Snippet:

function checkVersion(a,b) {
    let x=a.split('.').map(e=> parseInt(e));
    let y=b.split('.').map(e=> parseInt(e));
    let z = "";

    for(i=0;i<x.length;i++) {
        if(x[i] === y[i]) {
            z+="e";
        } else
        if(x[i] > y[i]) {
            z+="m";
        } else {
            z+="l";
        }
    }
    if (!z.match(/[l|m]/g)) {
      return 0;
    } else if (z.split('e').join('')[0] == "m") {
      return 1;
    } else {
      return -1;
    }
}

console.log(checkVersion("2.0.5","1.0.15")); // returns 1 as expected
console.log(checkVersion("1.2.2","1.2.0")); // returns 1 as expected
console.log(checkVersion("1.0.5","1.1.0")); // returns -1 as expected
console.log(checkVersion("1.0.5","1.00.05")); // returns 0 as expected
console.log(checkVersion("0.9.9.9.9.9.9","1.0.0.0.0.0.0")) // returns -1 as expected;

However, I still feel like there must be a shorter, more concise and cleaner way of doing this though. Any suggestions?


texts: Converting 'list of Foo' into 'lists of Foo properties'

texts:
I'm looking at some code that goes a bit like this:

class Foo { public int Frob; public int Frib; }
class Bar { public Foo Left; public Foo Right; }

public void ProcessBars(Bar[] bars)
{
    this.LeftFrobs = new int[bars.Count];
    this.RightFrobs = new int[bars.Count];
    this.LeftFribs = new int[bars.Count];
    this.RightFribs = new int[bars.Count];
    //... you get the idea

    int counter = 0;
    foreach(Bar bar in bars)
    {
        LeftFrobs[counter] = bar.Left.Frob;
        LeftFribs[counter] = bar.Left.Frib;
        //...27 more lines of similar
        if(bar.Left.Frob == MAGICNUM_A) LeftFribs[counter] = MAGICNUM_B;

        RightFrobs[counter] = bar.Right.Frob;
        RightFribs[counter] = bar.Right.Frib;
        //...27 more lines of similar
        if(bar.Right.Frob == MAGICNUM_C) LeftFribs[counter] = MAGICNUM_D;

        counter++;
    }
}

Aesthetically, this bothers me, but so far, I haven't managed to come up with anything better.


texts: Reading and displaying an image from a folder

texts:
I have a question concerning the correctness of the reading and displaying the image in ASP.NET Core MVC web application.

This is the way I am reading image names from a specific folder (I am using IHostingEnvironment _hostingEnvironment to get the rootPath):

   public class GetRandomImageForGalleryView : IGetRandomImageFromFolder
    {
        private string rootPath;
        public GetRandomImageForGalleryView(string rootPath)
        {
            this.rootPath = rootPath;
        }
        public string[] getImage()
        {
            return ReadPhotosFromDirectory();
        }
        private string[] ReadPhotosFromDirectory()
        {

            string[] fileLocations = Directory.GetFiles(rootPath+"\\lib\\Images\\Nature").Select(path => Path.GetFileName(path))
                                     .ToArray();
            return fileLocations;
        }
    }

And this is the way I am displaying them:

@model IGetRandomImageFromFolder
@{
    ViewBag.Title = "Gallery";
}

        @{
            foreach (var item in Model.getImage())
            {

            }
        }

Basically I just replace the image name.

Is this a good way? If not, why? Any other remarks would be helpful as well.


texts: Calculation of next week number (constrained by max 3) with rollover

texts:
What I want my code to do is that if we're on day 3 then we want to increase the week by 1. But if week number is 3 we want to reset the week to 1. The code below works but can it be simplified?

Java code

public int calculateNextWeek(int week, int day) {
    if (day == 3) {
        if (week == 3) {
            return 1;
        } else {
            return week + 1;
        }
    }

    return week;
}

Example data and expected output:

day = 3, week = 1 => 2
day = 3, week = 3 => 1
day = 1, week = 1 => 1
day = 1, week = 3 => 3


texts: Adjust bootstrap dropdown menu based on page width

texts:
I'm using Twitter Bootstrap's navbar. While testing different screen resolutions, I noticed that on lower resolutions, sometimes the submenu would get cut off by the right side of the page.

In the code below, when a dropdown is opened, I'm getting the width of the dropdown menu and dropdown submenu, adding those together and checking them against the width of the window. If the width is greater than the window width, I add the class pull-right so the dropdown menu and/or dropdown submenu will extend to the left and not get cut off by the right side of the page.

In this jsFiddle, you can see what I'm talking about by increasing/decreasing the width of the Results section. When you increase the width of the Results section far enough, the submenu for 'Dropdown 2' will open to the right. When you decrease the size of the Results section enough that the submenu would get cut off, the 'pull-right' class is applied and it extends to the left.

For the most part, this code is doing what it should, but does anyone have any suggestions on how to improve it?

JavaScript

$('.dropdown-toggle').click(function() {
    var dropdownList = $('.dropdown-menu');
    var dropdownOffset = $(this).offset();
    var offsetLeft = dropdownOffset.left;
    var dropdownWidth = dropdownList.width();
    var docWidth = $(window).width();

    var subDropdown = $('.dropdown-menu').eq(1);
    var subDropdownWidth = subDropdown.width();

    var isDropdownVisible = (offsetLeft + dropdownWidth <= docWidth);
    var isSubDropdownVisible = (offsetLeft + dropdownWidth + subDropdownWidth <= docWidth);

    if (!isDropdownVisible || !isSubDropdownVisible) {
        $('.dropdown-menu').addClass('pull-right');
    } else {
        $('.dropdown-menu').removeClass('pull-right');
    }
});

Please let me know if I need to better my explanation or if any other details are needed.


texts: Extract Common Data From List of Objects

texts:
I have a list of orders and for some order fields I need get the data that is common among the orders. If the data is not in common, I should indicate null. I collect the common data in a CommonData object. In addition, I also store the order codes and order ids associated with the CommonData.

I have two approaches that I'm considering:

Approach 1:

public CommonData getCommonData(List<Order> orders) {
    Order firstOrder = order.get(0);

    LocalDate commonStartDate = firstOrder.getStartDate();
    LocalDate commonEndDate = firstOrder.getEndDate();
    List<Item> commonItems = firstOrder.getItems();

    CommonData commonData= new CommonData();

    for (Order order : orders) {

        commonData.addCode(order.getCode());
        commonData.addId(order.getId());

        if (commonStartDate != null &&
                !commonStartDate.equals(order.getStartDate())) {
            commonStartDate = null;
        }

        if (commonEndDate != null &&
                !commonEndDate.equals(order.getEndDate())) {
            commonEndDate = null;
        }

        if (!equalLists(commonItems, order.getItems())) {
            commonData.setDifferentItems(true);
            commonItems = null;
        }
    }

    commonData.setCommonStartDate(commonStartDate);
    commonData.setCommonEndDate(commonEndDate);
    commonData.setCommonItems(commonItems);
    return commonData;
}

Approach 2:

private boolean haveSameDate(List<Order> orders,
        Function<Order,LocalDate> getDate) {

    return orders.stream()
            .map(getDate)
            .distinct()
            .limit(2)
            .count() == 1;
}

public CommonData getCommonData(List<Order> orders) {
    CommonData commonData = new CommonData();

    if (haveSameDate(orders,
            Order::getStartDate)) {
        commonData.setCommonStartDate(orders.get(0).getStartDate());
    }

    if (haveSameDate(orders,
            Order::getEndDate)) {
        commonData.setCommonEndDate(orders.get(0).getEndDate());
    }

    commonData.setCodes(
            orders.stream()
                .map(order -> order.getCode())
                .collect(Collectors.toList()));

    commonData.setIds(
            orders.stream()
                .map(order -> order.getId())
                .collect(Collectors.toList()));

    List<Item> firstOrderItems = orders.get(0).getItems();
    if (orders.stream()
        .map(Order::getItems)
        .allMatch(x -> equalLists(x,firstOrderItems))) {

        commonData.setCommonItems(firstOrderItems);
    } else {
        commonData.setDifferentItems(true);
    }

    return commonData;
}

Even though approach 2 involves multiple iterations over orders, the order and item lists will always be small.

In approach 2, having operations on one piece of data is in one spot within the method but it is scattered in approach 1. Approach 1 also has negative logic. Approach 2 is more complex in finding common order items.

Can approach 1 be redesigned to have the benefits of approach 2 (such as remove negative logic and keep operations on a piece of data in a single spot)? Or should approach 2 be used and perhaps be improved to better handle finding common order items?


texts: Rails controller method to accept one rating per IP address via AJAX

texts:
My rating controller:

  def rate
    @ip = request.remote_ip
    @konkurrencer = Rating.where(:IP => @ip, :konkurrencer_id => params[:id])
    if @konkurrencer.empty?
      params[:kon][:IP] = request.remote_ip
      params[:kon][:konkurrencer_id] = params[:id]
      @konkurrencer = Rating.new(params[:kon])
      @konkurrencer.save
      @konkurrencer.konkurrencer.rating_score += params[:kon][:ratings].to_i
      @konkurrencer.konkurrencer.ratings += 1
      @konkurrencer.save
    else
      // render error message
    end
    render :nothing => true
   end
end

My AJAX:

 jQuery.ajax({
     url: frm.attr('action'), //your server side script
     data: frm.serialize(), //our data
     type: 'POST',
     success: function (data) {
          //write here something when everything went ok

     },
     error: function (jxhr, msg, err) {
         alert(msg); //something went wrong.
     }
 });

Have do I make my controller more DRY?


texts:
How can I improve this code? It takes a number in the range of [1,7] and prints its corresponding day.

#include "stdafx.h"
#include <iostream>     // std::cout
#include <vector>       // std::vector
#include <string>

using std::cin;
using std::cout;
using std::vector;
using std::string;

int main()
{
    vector<string> name_day = { "Saturday" ,"Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" };
    int n ;

    cout << "This program takes a number in the range of" << "\n" << "[1 , 7] and prints its corresponding day." << "\n" << "............................................................." << "\n";

    while (true)
    {
        bool flag = true;

        cout << "Input a number : ";
        cin >> n;

        if (!cin) //If input is wrong.
        {
            // reset failbit
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }

        //If the condition is not satisfied .

        else
        {
            for (int i = 0; i <= 6; i++)
            {
                if (n-1 == i)
                {
                    cout << name_day[i] << "\n" << "-----------------------" << "\n";;
                    flag = false;
                }

            }//end of for
        }

        if (flag) { cout << "Bad Entery !." << "\n" << "-----------------------" << "\n"; }

    }//end of while

    system("pause");
}


texts: Choosing between 2 Fibonacci alternatives

texts:
Task:
Return the fibonacci value at a given index.
e.g: input: 6, return: 8.

Algorithm 1:

public static fibonacci(input: number): any {
    if (input <= 1) return input;
    return this.fibonacci(input - 1) + this.fibonacci(input - 2);
}

  Time complexity: \$O(n^2)\$,
  Space complexity: \$O(1)\$

Algorithm 2:

public static fibonacci2(input: number): any {
    if (input <= 1) return input;

    let a = 0;
    let b = 1;
    let n = 0;
    for (let i=2; i<=input; i++) {
        n = a + b;
        a = b;
        b = n;
    }
    return n;
}

  Time complexity: \$O(n)\$,
  Space complexity: \$O(1)\$

Am I right regarding the complexities?

Can you suggest any alternatives that achieve the same result, with different time/space complexity?


texts:
I'm writing the markup for Corpora - A Business Theme:

And started from the header section:

Here is my markup for it:

<address>Phone: 1.800.corp</address>

<address>Email: office@corpora.com</address>

<address>Follow Us: </address>

        Home
go to start
        Services
what we do
        Gallery
our best products
        Our Clients
what we've done for others
        About Us
who we are
        Contact Us
let's keep in touch

Awesome business card design

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Curabitur eget metus ac diam laoreet luctus rhoncus non nisi. Aenean at lobortis augue.

                Buy it now or Find Out More

Awesome business card design

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Curabitur eget metus ac diam laoreet luctus rhoncus non nisi. Aenean at lobortis augue.

                Buy it now or Find Out More

Awesome business card design

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Curabitur eget metus ac diam laoreet luctus rhoncus non nisi. Aenean at lobortis augue.

                Buy it now or Find Out More

Does it semantically correct? Special attention for tags address, em, span, section.  Many thanks to you all.


texts:
Based on this question on math.SE regarding probabilities in variations on the Monty Hall problem, I cobbled up a simulator in Ruby to give myself an introduction to the language.

Since this is my first Ruby program, I'm especially looking for feedback regarding Ruby style, but I would love any general code improvement suggestions as well (all the results seem correct, so I think the math is good). I'm more comfortable with Python and shell scripting, so I'm sure my preferences show through here.

Current functionality:

The program allows simulations of the following scenarios:

The host (Monty Hall) opens all but 1 door and the player switches to the door Monty left closed (the classic version)
Monty opens 1 extra door, leaving the rest closed, and you decide to switch to a different closed door (the premise of the math.SE question)
You pick a door and don't switch no matter what Monty does

Currently, it's hard-coded to simulate scenario #2 with 5 doors 1000 times, but that can be changed by switching the comment on the second-to-last line.

puts "Hello Monty!"

$wins = 0.0
$goats = 0.0

def choose_doors(num_doors)
  door_range = (1..num_doors)

  winning_door = rand(door_range)
  player_choice = rand(door_range)

  losing_doors = door_range.to_a - [winning_door] - [player_choice]
  monty_open = losing_doors.sample  # used when Monty opens 1 non-winning door

  return player_choice, monty_open, winning_door
end

def switch_door_multiple(choice, revealed, num_doors)
  # Monty revealed only 1 other door
  door_range = (1..num_doors)
  door_choices = door_range.to_a - [choice] - [revealed]

  new_choice = door_choices.sample
end

def count_result(final_choice, winning_door)
  if final_choice == winning_door
    $wins += 1
  else
    $goats += 1
  end
end

def simulate(num_doors, runs, strategy)
  for i in 1..runs
    player_door, open_door, winning_door = choose_doors(num_doors)
    if strategy == 1 # switch, 1 choice
      if player_door != winning_door
        player_door = winning_door
      else
        player_door = -1
      end
    elsif strategy == 2 # switch, multiple choice
      player_door = switch_door_multiple(player_door, open_door, num_doors)
    else
      # keep initial door
    end
    count_result(player_door, winning_door)
  end

  puts "wins: " + $wins.to_s
  puts "goats: " + $goats.to_s
  puts "win percentage: " + (100 * ($wins / ($wins + $goats))).to_s + "%"
end

def prompt_user
  print "Number of doors: "
  input_num_doors = gets.chomp.to_i
  while input_num_doors < 3
    puts "This only works with 3 or more doors"
    print "Number of doors: "
    input_num_doors = gets.chomp.to_i
  end

  print "Number of runs: "
  input_runs = gets.chomp.to_i
  while input_runs < 1
    puts "Need 1 or more runs"
    print "Number of runs: "
    input_runs = gets.chomp.to_i
  end

  puts "Simulation: "
  puts "[1]: Monty opens all but 1 door and you decide to switch"
  puts "[2]: Monty opens 1 door and you switch to a different closed door"
  puts "[3]: Keep your door - you don't switch no matter what Monty does"
  print "Choose a game type (1/2/3): "
  input_strategy = gets.chomp.to_i

  while ![1, 2, 3].include? input_strategy
    print "Choose a game type (1/2/3): "
    input_strategy = gets.chomp.to_i
  end

  return input_num_doors, input_runs, input_strategy
end

# num_doors, num_runs, strategy = prompt_user
num_doors, num_runs, strategy = 5, 1000, 2

simulate(num_doors, num_runs, strategy)


texts: Handle data sent back over serial by Arduino

texts:
I have a machine that is being controlled by an Arduino.  If I send the machine the command '9' it will send back JSON with some sensor temperatures in the format {"temperatures":{"bean_temp":110.75,"env_temp":98.15}}.

I am exposing a function called getTemperatures() that I currently call from elsewhere every 1000ms. The serialport library provides a listener for all the data that gets sent back over the wire from the machine (machine.on('data', handleData)). There are other types of data that will get sent back from the machine, such as {"action":"handle_pulled"}. I am filtering the data that comes back over the serial and then assigning temperatures responses to a temperatures variable that I continuously overwrite. I then give a 999 ms delay before calling back that variable.

This works, but seems fragile (and not elegant).

var serialport = require('serialport');

var ports = require('./ports'),
    port = ports.arduino;

var machine = new serialport(port, {
  baudRate: 9600,
  parser: serialport.parsers.readline("\n")
});

machine.on('data', handleData);

var temperatures = {};

machine.getTemperatures = function(callback) {
    sendCommand('9');
    setTimeout(function(){
      callback(temperatures);
    }, 999)
}

function sendCommand(data) {
  machine.write(data);
}

function handleData(dataString){
  data = JSON.parse(dataString);

  if ('temperatures' in data) {
    temperatures = data;
  }
}

module.exports.getTemperatures = getTemperatures;


texts: Count how many times a value is referenced in a grid

texts:
I've got list of points: List<Point> seedPoints. Each Point contains x and y coordinates pointing to certain double value (let's call it pointValue). I would like to display how many times each pointValue is referenced in seedPoints list. To do so I've created following lambda expression:

seedPoints.stream()
    .collect(Collectors.groupingBy(p ->  pointGrid.get(p.x, p.y)))
    .entrySet()
    .stream()
    .map(entry -> "value:" + entry.getKey() + "   count: " + entry.getValue().size())
    .forEach(System.out::println);

The solution works fine, I get the following output:

value:0.0   count: 1
value:3.0   count: 2
value:4.0   count: 1
value:5.0   count: 4
value:6.0   count: 2

I don't find it very clean however. This solution requires two call to the stream() method (1st and 4th line of code), as collect() method is a terminal operation. Does anybody has any idea how could I improve my lambda expression?


texts: Properly disposing of a WCF connection using IDisposable

texts:
This is a follow up question to this question:

https://stackoverflow.com/questions/4573526/what-could-be-causing-a-cannot-access-a-disposed-object-error-in-wcf

I have created a WCF service and it is up and running. When I used it, I was closing the connection after each time I got a response in a finally.

Trying to use the client for a second time, I got the exception of the linked question - can not access a disposed object. I tried implementing the IDisposable pattern without closing the connection every time.

1) First of all - Did I implement the dispose pattern correctly?

the code (it's short, don't worry):

I got a singleton class which is responsible for the service communication in which it creates the client class:

public class WebService : IDisposable
{
    // Flag: Has Dispose already been called?
    bool disposed = false;
    private MyWebServiceContractClient client;
    private static readonly Lazy<WebService> webServiceHandler = new Lazy<WebService>(() => new WebService());

    private WebService()
    {
        client = new MyWebServiceContractClient();
    }

    public static WebService Instance
    {
        get
        {
            return webServiceHandler.Value;
        }
    }

    public double GetAnswer()
    {
        try
        {
            if (!(client.State == CommunicationState.Opened) && !(client.State == CommunicationState.Opening))
            {
                client.Open();
            }
            //do some work
            return answer;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return -1;
        }
        finally
        {
           // here i would normally call client.Close(); but now im not
        }
    }

    public void Dispose()
    {
        // Dispose of unmanaged resources.
        Dispose(true);
        // Suppress finalization.
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            client.Close();
        }

        disposed = true;
    }
}

2) If I'm only closing the connection in the dispose method, doesn't it mean I'm always keeping the connection alive? Isn't it a waste of resources and even a security risk to just keep it open?


texts: Number Of Matching Elements In Two Lists

texts:
I have many sets of 2 strings. I'm trying to determine the number of matching elements in these 2 strings. The rules are if the strings share a common letter, that's a point, order does matter, but each letter in the first string can only match one of the letters in the second string. So in the strings 'aaaab', 'acccc', only 1 point is awarded because there is only one 'a' to match in the second string. Here are a few examples:

aaabb  bbaaa  5
aabbb  bbbaa  5
aaabb  aabbb  4
aaabb  ccaaa  3
aaaaa  bbbbb  0
ababa  babab  4
aabcc  babaf  3
abcde  abfgh  2
bacde  abdgh  3

Hopefully that gets across how it works.

Here is the most efficient code I've been able to come up with, but its horribly convoluted. I hoping someone could think of something better.

def Score(guess, solution):
    guess = list(guess)
    solution = list(solution)
    c = 0
    for g in guess:
        if g in solution and g != "_":
            c += 1
            solution[solution.index(g)] = "_"
    return c

Surely this isn't the best way to do this, but I haven't been able to figure anything else out. I tried creating an algorithm with Counter and doing guess&solution, which worked, but ended up being way slower. Anyone have any ideas?


texts: Draw an outline of an upward-pointing triangle

texts:
I am beginner in C++ and I was given this assignment by my teacher.  The assignment is to print the following shape:

      *
     * *
    *   *
   *     *
  *       *
 *         *
*************

The following is what I have tried and basically it works, but I doubt my code is not simple, there's another way simpler than that. How can I make my code more simpler? Any hints are appreciated.

#include <iostream>

using namespace std;

int main() {
  /**
      *
     * *
    *   *
   *     *
  *       *
 *         *
*************
  */
  int spaces_before = 6; // spaces before printing the stars
  int spaces_after = 0; // spaces after printing the first star
  int stars = 1;
  for (int i = 1; i <= 7; i++) {
    for (int j = 1; j <= spaces_before; j++) {
      cout << ' ';
    }
    if (i == 1) {
      cout << "*";
    } else if (i != 7) {
      cout << '*';
      for (int j = 1; j <= spaces_after; j++) {
        cout << ' ';
      }
      cout << '*';
    } else {
      for (int j = 1; j <= stars; j++) {
        cout << '*';
      }
    }
    spaces_before--;
    if (i == 1) {
      spaces_after++;
    } else {
      spaces_after += 2;
    }
    cout << '\n';
    stars += 2;
  }
}


texts: Sort a list using a reverse helper function

texts:
The task:

  Given a list, sort it using this method: reverse(lst, i, j), which
  reverses lst from i to j.

My functional solution:

const reverse = (lst, i, j) => [...lst.slice(0, i), ...lst.slice(i, j + 1).reverse(), ...lst.slice(j + 1)];

console.log(reverse([0,1,2,3,4,5], 2, 4));

My imperative solution:

function reverse(lst, i, j) {
  const lstReversed = [];
  let x = j;
  for (let k = 0, len = lst.length; k < len; k++) {
    lstReversed.push(lst[k < i || k > j ? k : x--]);
  }
  return lstReversed;
}

console.log(reverse([0,1,2,3,4,5], 2, 4));

The algorithm using the reverse function:

let lst = [7,6,3,8,5,0,9,1,2,4];

const len = lst.length;
for (let x = 0; x < len; x++) {
  for (let y = 1; y < len; y++) {
    if (lst[y - 1] > lst[y]) { lst = reverse(lst, y - 1, y); }
  }
}

console.log(lst);


texts:
I need to implement a method that adds a "7-3-1" check digit to my id. The "7-3-1" method works as following:

Weights 7, 3, 1 are assigned to the original number from right to left. So if the original number is 12345, then 5 will have weight 7, 4 will have weight 3, 3 will have weight 1, 2 will have weight 7, 1 will have weight 3.
Numbers are multiplied by their weight and added to each other. So 5*7 + 4*3 + 3*1 + 2*7 + 1*3 = 67.
Sum is rounded to next full tenth and then from that sum is subsctracted to get the weight. So 70 - 67 = 3.

And the number with check digit would be 123453.

Here is what I have at the moment:

class ReferenceNumberUtil
{
    private static $offset = 0; // possiblity to set offset

    public static function referenceNumberFromId($id)
    {
        $id = $id + ReferenceNumberUtil::$offset;
        $weights = [7, 3, 1];
        $sum = 0;
        foreach (array_reverse(str_split($id)) AS $index => $digit) {
            $weightIndex = $index % 3;
            $sum += $digit * $weights[$weightIndex];
        }
        $checkDigit = (ceil($sum / 10) * 10) - $sum;
        return $id . $checkDigit;
    }

    public static function idFromReferenceNumber($number)
    {
        $numberWithoutCheckDigit = substr($number, 0, -1);
        return $numberWithoutCheckDigit - ReferenceNumberUtil::$offset;
    }
}

I've ran some tests and as far as i can tell this works correctly. But i'm still kind of hesitant. I would appreciate a review of this code to be certain that it works correct in all situations and also any ideas on how to improve it further are also welcome.


texts:
This code is to find expiring/expired documents. It was included in one of the models, say Document.

Is this good approach of using constant variables which holds the some data and used within this mixin only? Is there any better approach I could use instead the constants?

require 'active_support/concern'

module Expirable
  extend ActiveSupport::Concern

  BEFORE_EXPIRY_DURATION =
    eval(APP_CONFIG.timings.notification_of_expired.before_expiry)

  EXPIRING_DURATION =
    (BEFORE_EXPIRY_DURATION.ago..Date.today)

  included do
    scope :expirables,
      -> { where("expiry_date IS NOT NULL") }
    scope :ready_to_expire,
      -> { expirables.where(expiry_date: EXPIRING_DURATION) }
    scope :expired,
      -> { expirables.where("DATE(expiry_date) < ?", Date.today) }
  end

  module ClassMethods
  end

  def ready_to_expire?
    expiry_date.present? && !expired? && expiry_date.to_date.in?(EXPIRING_DURATION)
  end

  def expired?
    expiry_date.present? && (expiry_date.to_date < Date.today)
  end

end


texts: PANDAS DataFrame operations to analyze top Server Fault tags

texts:
I am working on learning how to do frequency analysis of Server Fault question tags to see if there is any useful data that I can glean from them. I'm storing the raw data in Bitbucket for global access, so this code will use the same dataset I am using, it's about 30Mb.

import pandas as pd

debiandf = pd.read_csv("https://bitbucket.org/lloydm/dataviz/raw/e84b9f9a7941d255483a81af98248b4fec8a36a8/data/LinuxSFPopularity/DebianQuestions.csv")
debiandf["CreationDate"] = pd.to_datetime(debiandf["CreationDate"], format="%Y-%m-%d %H:%M:%S")
debiandf = debiandf.set_index(["CreationDate"])

tag_df = pd.DataFrame(index=debiandf.index, data=debiandf["Tags"])
tag_df = tag_df.reset_index().drop_duplicates(subset='CreationDate', keep='last').set_index('CreationDate')
x = tag_df["Tags"].str.extractall(r'\<(.*?)\>').unstack()
x.columns = x.columns.droplevel(0)
# column names signify the index location of the tag when extracted.
# i.e. with <ubuntu><networking><tag3> you would have [ubuntu,networking,tag3]
x.rename(columns={0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, inplace=True)

x1 = x.groupby(x.index.year)[1].apply(lambda grp: grp.value_counts().head(5))
x2 = x.groupby(x.index.year)[2].apply(lambda grp: grp.value_counts().head(5))
x3 = x.groupby(x.index.year)[3].apply(lambda grp: grp.value_counts().head(5))
x4 = x.groupby(x.index.year)[4].apply(lambda grp: grp.value_counts().head(5))
x5 = x.groupby(x.index.year)[5].apply(lambda grp: grp.value_counts().head(5))

x6 = pd.concat([x1,x2,x3], axis=1)
x6 = x6.reset_index()
x6.rename(columns={"level_0": "Year", "level_1": "Tag"}, inplace=True)
print x6

I'm new to using pandas and I'm learning how to do data analysis on my own so I can produce original content for reddit. How can I simplify my x.groupby lines so I can get the top 5 value counts from every column in my x DataFrame?

I'm new to pandas, so if you could explain why it would be done that way, that would be really helpful.


texts:
When reigstering a user I request two reads from the database to see if there is a username and email and then I write if the checks pass.. Can anyone tell me if this code will block other users?

I am using node with express.js and mongojs.

I know I am saving passwords in plaintext.. This will be changed.

app.post('/register', function(req, res) {

    var checked = 0;
    var errors = [];

    var finishedCheck = function() {
        checked++;
        register();
    }

    var register = function() {

        if(checked === 2){

            if(errors.length > 0) {
                console.log('errors', errors);
                res.statusCode = 409;
                res.send(errors);
            } else {

                var newuser = {
                    username: req.body.username,
                    uppercase: req.body.username.toUpperCase(),
                    password:req.body.password,
                    email: req.body.email.toLowerCase(),
                    userLevel: 0,
                    createdOn: new Date()
                };

                db.users.save(newuser, function(err, val){
                    if(!err) {
                        req.session.userid = val['_id'];
                        res.end();
                    } else {
                        res.statusCode = 406;
                        res.end(['Something went wrong', err]);
                    }
                });
            }
        }
    }

    var check = function(username, email) {
        console.log('chekc');
        db.users.ensureIndex({email:1},{unique:true});
        db.users.ensureIndex({uppercase:1},{unique:true});
        if(!username.match(/^[A-Za-z0-9_]*$/)) {
            errors.push('Username is invalid');
            finishedCheck();
        } else {
            db.users.findOne({uppercase: username}, function(err, val) {
                if(val) {
                    errors.push('Username Taken');
                }
                finishedCheck();
            });
        }

        //check if the is a valid email address if so then check to see if its already registered
        if(!email.match(/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i)) {
            errors.push('Email is invalid');
            finishedCheck();
        } else {
            db.users.findOne({email: email}, function(err, val) {
                if(val) {
                    errors.push('Email is already in the database');
                }
                finishedCheck();
            });
        }

    };

    check(req.body.username.toUpperCase(), req.body.email.toLowerCase());

});


texts: Which solution is good to generate a list without None results from a function?

texts:
I'm relatively new to Python and learned, that function cannot return nothing, not even None. In my application I want to iterate over a list and keep all non-None results of a complicated function:

def complicated_function(x):
    if x < 0:
        return "a"
    elif x == 3.6:
        return "b"
    elif x == 4:
        return None  # Idealy here nothing should be returned
    elif x > 10:
        return "c"
    else:
        return "d"

I have three soltuions and my question is which would you recommend me to use and are there better ones?

First solution

tmp = [complicated_function(x) for x in [-1, 2, 3.6, 4, 5, 20]]
ret = [x for x in tmp if x]

Second solution

ret = [complicated_function(x) for x in [-1, 2, 3.6, 4, 5, 20] if complicated_function(x)]

Third solution

ret = []
for x in [-1, 2, 3.6, 4, 5, 20]:
    tmp = complicated_function(x)
    if tmp:
        ret.append(tmp)

I think the first solution is slow, if the list to iterate over is very large. The second solution seems to be bad if the complated_function is really expensive (in rumtime). The third solution seems to be ok, but append is said to be significantly slower than list comprehension.


texts:
I thought it would be fun to write a simple and small bash script which randomly chooses a wallpaper from a given directory of a set of wallpaper images. The code is as follows.
#!/bin/bash

# simple script to choose random image from
# Wallpaper directory and set it as desktop background

# cd into Wallpaper dir

cd /home/user/Pictures/Wallpapers

# using nano time mod # of imgs in Wallpapers (+1 b/c awk fields start at ind 1)
# to provide a semi-random field number for the awk statement

RAND=$(($(date +%N) % $(ls -h | wc -l) + 1))
IMG=$(ls -h | awk -v r=$RAND 'BEGIN{FS = "\n"; RS = ""} {print $r}')

# change the desktop with the img file provided from the awk statement
# (the way to set the background is system dependent but the gist is the same)

gsettings set org.gnome.desktop.background picture-uri "file:///home/user/Pictures/Wallpapers/$IMG"

This is really just a small, fun project, but I am almost certain I am not doing this the most efficient way, so any feedback would be great.


texts:
I wrote a module that calculates the area of shapes and I wanted to get feedback. Am I on the right track?

import math

# A python program to calculate the area of shapes

# area of a square is length multiplied by width
def area_of_square(length, width):
    _check_if_values_are_strings(length = length, width = width)
    _check_if_values_are_negitive(lenth = length, width = width)

    return length * width

# area of a triangle is base multiplied by height divided by 2
def area_of_triangle(base_value, height):
    _check_if_values_are_strings(base_value = base_value, height = height)
    _check_if_values_are_negitive(base_value = base_value, height = height)

    return (base_value * height) / 2

# area of a circle is radius squared times pi
def area_of_circle(radius):
    _check_if_values_are_strings(radius = radius)
    _check_if_values_are_negitive(radius = radius)

    return math.pow(radius,2) * math.pi

def _check_if_values_are_strings(**values):
    for k,v in values.items():
        if (isinstance(v,str)):
            raise TypeError("{0} is a string".format(k))

def _check_if_values_are_negitive(**values):
    for k,v in values.items():
        if v < 0:
            raise ValueError("{0} is a negitive".format(k))

My main concern is the use of the _check_if_values_are_strings and _check_if_values_are_negitive methods. Am I using them correctly, or is there a better approach to verifying the parameters before preforming the calculation?


texts:
I stumbled upon an unaswered question, which looked like a good fit for a functional programming language.

Here is the problem statement from codeeval:

  UGLY NUMBERS

  CHALLENGE DESCRIPTION:

  Credits: This challenge has appeared in a google competition before.

  Once upon a time in a strange situation, people called a number ugly
  if it was divisible by any of the one-digit primes (2, 3, 5 or 7).
  Thus, 14 is ugly, but 13 is fine. 39 is ugly, but 121 is not. Note
  that 0 is ugly. Also note that negative numbers can also be ugly: -14
  and -39 are examples of such numbers.

  One day on your free time, you are gazing at a string of digits,
  something like:

123456

  You are amused by how many possibilities there are if you are
  allowed to insert plus or minus signs between the digits. For example
  you can make:

1 + 234 - 5 + 6 = 236

  which is ugly. Or

123 + 4 - 56 = 71

  which is not ugly.

  It is easy to count the number of different ways you can play with the
  digits: Between each two adjacent digits you may choose put a plus
  sign, a minus sign, or nothing. Therefore, if you start with \$D\$ digits
  there are \$3^{D-1}\$ expressions you can make. Note that it is fine to
  have leading zeros for a number. If the string is 01023, then
  01023, 0+1-02+3 and 01-023 are legal expressions.

  Your task is simple: Among the \$3^{D-1}\$ expressions, count how many of
  them evaluate to an ugly number.

  INPUT SAMPLE:

  Your program should accept as its first argument a path to a filename.
  Each line in this file is one test case. Each test case will be a
  single line containing a non-empty string of decimal digits. The
  string in each test case will be non-empty and will contain only
  characters '0' through '9'. Each string is no more than 13 characters
  long. E.g.

1
9
011
12345

  OUTPUT SAMPLE:

  Print out the number of expressions that evaluate to an ugly number
  for each test case, each one on a new line. E.g.

0
1
6
64

And here is my solution (ignoring the part about reading from a file)

type Expression =
    | Plus of Expression * Expression
    | Minus of Expression * Expression
    | Leaf of int64

let rec eval = function
    | Plus (left, right) -> (eval left) + (eval right)
    | Minus (left, right) -> (eval left) - (eval right)
    | Leaf n -> n

let rec expressions (s : string) =
    seq {
        yield Leaf (Int64.Parse(s))
        let n = s.Length
        for i in 1 .. n - 1 do
            let leaf = Leaf (Int64.Parse(s.Substring(0, i)))
            for e in expressions(s.Substring(i, n - i)) do
                yield Plus (leaf, e)
                yield Minus (leaf, e)
    }

let rec isUgly (n : int64) : bool =
    if n < 0L then
        isUgly -n
    else
        n = 0L || n % 2L = 0L || n % 3L = 0L || n % 5L = 0L || n % 7L = 0L

let countUglyNumbers (s : string) =
    expressions s |> Seq.map eval |> Seq.filter isUgly |> Seq.length

for input in ["1"; "9"; "011"; "12345"; "123456"; "1234566543215"] do
    printfn "%d" <| countUglyNumbers input


texts:
My java code for CSES Introductory problem Number Spiral gives TLE for large inputs, like
Input :
100000
170550340 943050741
121998376 943430501
689913499 770079066
586095107 933655238 …
(First line/number being the number of inputs)
My code is as below:
import java.util.*;
public class numberSpiral {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long testN = scanner.nextLong();
        long r=0,c=0;
        while(testN-- > 0){
            r = scanner.nextLong();
            c = scanner.nextLong();
            if (c > r) {
                if (c % 2 == 0) {
                    System.out.println(((c - 1) * (c - 1)) + 1 + (r - 1));
                } else
                    System.out.println(((c) * (c)) - (r - 1));
            } else {
                if(r % 2 == 0){
                    System.out.println(((r) * (r)) - (c - 1));
                } else
                    System.out.println(((r - 1) * (r - 1)) + 1 + (c - 1));
            }
        }
    }
}

It works for small inputs. I can't figure out how to optimize it better to reduce time. Time limit is: 1.00 s


texts:
This is the problem:

  You are given queries. Each query is of the form two integers described below:

  1 x: Insert x in your data structure.
  2 y: Delete one occurrence of y from your data structure, if present.
  3 z: Check if any integer is present whose frequency is exactly z. If yes, print 1 else 0.

  The queries are given in the form of a 2-D array queries of size q where queries[i][0] contains the operation, and queries[i][1] contains the data element. For example, you are given array queries = [[1,1],[2,2],[3,2],[1,1],[1,1],[2,1],[3,2]]
  …

  Return an array with the output=[0,1].

I am getting a "Time Limit Exceeded" error on only one Test Case. How can I optimize and improve my code?

Here is my code in JavaScript:

function freqQuery(queries) {
    const resultArray = []
    const frequencyArray = [];
  for(let i=0 ; i<queries.length ; i++){
      const arr = queries[i]
      if(arr[0]== 1){
          frequencyArray[arr[1]] = (frequencyArray[arr[1]] || 0) + 1
      }
      else if(arr[0] == 2){
          if(frequencyArray[arr[1]]){
              frequencyArray[arr[1]] = frequencyArray[arr[1]] -1;
          }
      }
      else if(arr[0] == 3){
          resultArray.push(frequencyArray.includes(arr[1]) ? 1 : 0 );
      }
  }
  return resultArray;
}


texts:
I'm creating a simple MVC framework for a new version of my website I'm working on. Currently I have simple routing, such as /about-us etc ...

I've just implemented 'my version' of dynamic routing. I have no idea whether or not my implementation is idiotic or not. I made it up as I went along, so I've no idea if this is a horrible way to implement dynamic routing or not.

I'd be grateful if someone could review my implementation and provide some feedback.

  Here's 'Routes.php', this stores the user-defined routes.

// This is the index page. The first route.
Route::set('', function() {
  View::make('Root');
});
// This is a test route, leading to an about-us page.
Route::set('about-us', function() {
  View::make('AboutUs');
});
/*
 * This is an example of a dynamic route. In this example,
 * this route would display a users profile page.
*/
Route::set('user/<1>', function() {
  Route::dyn('user/<1>');
  View::make('UserProfile');
});

The method View::make() has nothing to do with the routing. It's just designed to create the HTML page and the Controller for the page.

The method Route::set() is how I create all routes. Simple routes are created entirely with Route::set(). The dynamic routes are created by executing the closure. Route::set() executes the closure for simple and dynamic routes, for simple routes the closure creates the view and for dynamic routes it swaps <1> for a parameter from the URL and then creates the view.

The reason the syntax is odd, <1>, is because if you want multiple dynamic parameters you can use <2> etc ...

  Here's an example

In this example the URL string might look like this user/francis/settings/something-else

Route::set('user/<1>/settings/<2>', function() {
  Route::dyn('user/<1>/settings/<2>');
  View::make('UserProfile');
});

  Here's the implementation of the Route::dyn() method

public static function dyn($dyn_routes) {
$route_components = explode('/', $dyn_routes);
$uri_components = explode('/', substr($_SERVER['REQUEST_URI'], strlen(BASEDIR)-1));
for ($i = 0; $i < count($route_components); $i++) {
  if ($i+1 <= count($uri_components)-1) {
    $route_components[$i] = str_replace("<$i>", $uri_components[$i+1], $route_components[$i]);
  }
}
$route = implode($route_components, '/');
self::registerRoute($route);
}

$route_components is what we pass to Route::dyn(). $uri_components is the string we get from the URL, i.e user/francis/settings/something-else. This function converts $route_components so that it is the same as $uri_components. The reason for doing so is that I add all routes to a global array called $Routes. When someone visits a page the URL is checked against the valid routes in the $Routes array.

When the user visits user/francis I want the method Route::set('user/<1>') to run so that the profile page is displayed. It all works with my implementation, I'm just wondering if there is a better way.

Thanks,
Francis


texts: Updating multiple svn repositories using powershell

texts:
I wrote a script to perform svn update on all the SVN repositories inside a folder. It would have been great if the folder containing all these repositories itself was a repository, but it was not setup like that, which is why I opted to write this script.

$timestamp = get-date -f "yyyy-M-d-h-m-s"
$SvnLogPath="C:\out\svnlogs\"

if(test-path -path $SvnLogPath)
{
    write-host "SVN Log path doesn't exist. So I am creating it . . ."
    new-item -type directory $SvnLogPath | out-null
}

$logfile = "${SvnLogPath}svn_update_${timestamp}.log"
new-item -type file $logfile | out-null

$BaseDir="C:\TRUNK\"

$RepositoryList = "Alpha","Bravo","Charlie","Delta","Echo","Foxtrot","Golf","Hotel"

# BUILDING FULL PATHS
$FullPaths = $RepositoryList | %{ $BaseDir+$_}

# ISSUING SVN UPDATE TO EACH DIR
$FullPaths | % {svn update $_ 2>&1 | ft -AutoSize -Wrap | Out-File -Append $logfile }

# OPEN LOG FILE AFTER THE COMPLETION
notepad $logfile

Can this script be further simplified and written more idiomatically?

PS: I am using only svn update without credentials as they are stored in the shell already.


texts: Verify if meeting datetime ranges overlap in an IEnumerable list of meetings

texts:
I have an assignment where I need to find out if any of the meetings in a list of meeting class object have overlapping datetime ranges. What I have so far is this:

public class Meeting
{
    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public Meeting(DateTime start, DateTime end)
    {
        this.Start = start;
        this.End = end;
    }
}

public static class StaffMeetings
{
    public static bool DoesNotOverlap(IEnumerable<Meeting> meetings)
    {
        DateTime start = new DateTime();
        DateTime end = new DateTime();
        foreach (Meeting meeting in meetings)
        {
            if (start != DateTime.MinValue && end != DateTime.MinValue)
            {
                if (start < meeting.End && end > meeting.Start)
                {
                    return false;
                }
            }
            start = meeting.Start;
            end = meeting.End;
        }
        return true;
    }

    public static void Main(string[] args)
    {
        var format = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat;

        Meeting[] meetings = new Meeting[]
        {
        new Meeting(DateTime.Parse("1/1/2015 20:00", format), DateTime.Parse("1/1/2015 21:30", format)),
        new Meeting(DateTime.Parse("1/1/2015 21:30", format), DateTime.Parse("1/1/2015 23:00", format)),
        new Meeting(DateTime.Parse("1/1/2015 23:10", format), DateTime.Parse("1/1/2015 23:30", format))
        };

        Console.WriteLine(StaffMeetings.DoesNotOverlap(meetings));
    }
}

Using the provided data set, I get the correct result but as I add more meetings, my results start to fail and performance drops.

I feel that the problem is in how I am iterating the list. However, if I sort the list first, I can most likely improve reliability but my performance would probably drop. I feel that there should be an algorithm for this, but so far, I have not had any luck finding one.


texts:
This code is supposed to be the "user" system for my app. This will ask you what you want to do...
If you want to add a user, remove a user or check the list of saved users.
With this I learned how to open and edit text files. And my goal doing projects is keep on learning and maybe someday I will be able to work or professionally use Python.
This code is working at the moment, but I wanted to know if is too basic or too complicated with some more professional eyes on it (please consider my 3 weeks knowledge).
snames = list()
f_n = (open('names.txt')).read()
print("Welcome to NAME.app")
##################    USER   LOGG IN        #######################
while True:
    name = input("\n - Insert name to logg in \n - ADD to save new user \n - LIST to see saved users \n - REMOVE to delete a user \n - EXIT to finish \n ...")
    if name.lower() == "add":
        n_input = input("Name:")
        with open('names.txt', 'a') as f:
            f.write(n_input + '\n')
            f.close()
        continue

    elif name.lower() == "list":
        with open('names.txt') as f:
            print(f.read().splitlines())

    elif name in f_n:
        print("Logged as", name.upper())
        nxt = input('Welcome, press enter to continue \n')
        if nxt == '':
            break

    elif name.lower() == 'remove':
        rem = input("Insert user name to remove \n ...")
        with open('names.txt', 'r+') as f:
            l=f.readlines()
            l=[z for z in l if rem not in z]
        with open('names.txt', 'w') as f:
            f.writelines(l)

    elif name.lower() == "exit":
        exit()


texts:
A project I am working on requires me to check the first character of an input string, to determine if it is a numeric character. I have developed the following code:

public static boolean IsLeadingCharNumfName(String fName)
{
    CharSequence[] numbs;
    numbs  = new CharSequence[10];
    numbs[0] = "0";
    numbs[1] = "1";
    numbs[2] = "2";
    numbs[3] = "3";
    numbs[4] = "4";
    numbs[5] = "5";
    numbs[6] = "6";
    numbs[7] = "7";
    numbs[8] = "8";
    numbs[9] = "9";

    if(fName.substring(0,1).equals(numbs[0]))
    {
        return true;
    }
    if(fName.substring(0,1).equals(numbs[1]))
    {
        return true;
    }
    if(fName.substring(0,1).equals(numbs[2]))
    {
        return true;
    }
    if(fName.substring(0,1).equals(numbs[3]))
    {
        return true;
    }
    if(fName.substring(0,1).equals(numbs[4]))
    {
        return true;
    }
    if(fName.substring(0,1).equals(numbs[5]))
    {
        return true;
    }
    if(fName.substring(0,1).equals(numbs[6]))
    {
        return true;
    }
    if(fName.substring(0,1).equals(numbs[7]))
    {
        return true;
    }
    if(fName.substring(0,1).equals(numbs[8]))
    {
        return true;
    }
    if(fName.substring(0,1).equals(numbs[9]))
    {
        return true;
    }
    else
    {
        return false;
    }
}

I feel that this code can be optimised for efficiency, but I'm not sure how. I'll have to do the same for checking if the name contains a number.

What I am looking for, is a way to lower the code footprint primarily, with efficiency as a secondary bonus.


texts: Use Promise to wait until DOM element exists

texts:
I need to create a JavaScript Promise that will not resolve until a specific HTML element is loaded on the page.

I don't have any way of knowing when this element will be loaded, other than to simply poll the DOM for it.

It seems there should be a more concise way to accomplish this task.  I don't want anything that's "clever" to the point of being difficult to understand, but I'm open to any feedback on this pattern.

The code must be ES5 compatible for the most part.  Polyfills are probably ok, but it has to run on IE10+.

function getContainer() {
    return new Promise(function (resolve, reject) {
        waitForContainerElement(resolve);
    });
}

function waitForContainerElement(resolve) {
    var $configElement = $("#container");
    if ($configElement.length === 0) {
        setTimeout(waitForContainerElement.bind(this, resolve), 30);
    } else {
        resolve($configElement);
    }
}

Usage:

getContainer.then(function($container){
    ...
});

I would normally implement a max poll time, but didn't want that to cloud the issue here.


texts: Getting a count of correct and incorrect test attempts

texts:
I need to get a count of correct and incorrect attempts per testID:

select
    AttempID,
    Test_ID,
    Date,
    SubjectID,
    Date,
    sum(Correct) as Correct,
    sum(InCorrect) as InCorrect
from tbldemo
group by
    AttempID,
    Test_ID,
    Date,
    SubjectID_name,
    Date

Do I need to group by each column other column, and then sum over Correct and Incorrect? AttempID, Test ID, date and subject ID combinations will remain constant.

  AttempID  Test ID   Date      Subject ID  Correct  Incorrect
   1          2      2014-05-12     2          0       1
   1          2      2014-05-12     2          0       1
   1          2      2014-05-12     2          1       0
   1          2      2014-05-12     2          0       1
   1          2      2014-05-12     2          1       0
   1          2      2014-05-12     2          0       1
   1          2      2014-05-12     2          1       0
   1          2      2014-05-12     2          1       0
   1          2      2014-05-12     2          0       1
   1          2      2014-05-12     2          1       0
   1          2      2014-05-12     2          0       1
   1          2      2014-05-12     2          0       1
   1          2      2014-05-12     2          0       1
   1          2      2014-05-12     2          0       1
   3          4      2014-05-12     2          0       1
   3          4      2014-05-12     2          1       0
   3          4      2014-05-12     2          1       0
   3          4      2014-05-12     2          0       1
   3          4      2014-05-12     2          0       1
   3          4      2014-05-12     2          0       1
   3          4      2014-05-12     2          1       0


texts:
I am sharing my Bowling Game Score Kata made in Java, it is available for whoever wants to code review it.
I appreciate any comments.

class BowlingGameScore {

    private int[] pinsKnockedDown = new int[21];
    private int currentRoll = 0;

    void roll(int pinsKnockedDown) {
        this.pinsKnockedDown[currentRoll++] = pinsKnockedDown;
    }

    int score() {
        int totalScore = 0;
        int rollNumber = 0;

        for (int frameNumber = 0; frameNumber < 10; frameNumber++) {
            int frameScore;

            if (isSpare(rollNumber)) {
                frameScore = 10 + getSpareBonus(rollNumber);
                rollNumber += 2;

            } else if (isStrike(pinsKnockedDown[rollNumber])) {
                frameScore = 10 + getStrikeBonus(rollNumber);
                rollNumber++;

            } else {
                frameScore = pinsKnockedDown[rollNumber] + pinsKnockedDown[rollNumber + 1];
                rollNumber += 2;
            }

            totalScore += frameScore;
        }

        return totalScore;
    }

    private int getStrikeBonus(int roll) {
        return pinsKnockedDown[roll + 1] + pinsKnockedDown[roll + 2];
    }

    private boolean isStrike(int roll) {
        return roll == 10;
    }

    private int getSpareBonus(int roll) {
        return pinsKnockedDown[roll + 2];
    }

    private boolean isSpare(int roll) {
        return pinsKnockedDown[roll] + pinsKnockedDown[roll + 1] == 10;
    }
}

And its tests:

class BowlingGameScoreTest {
    private BowlingGameScore game;

    @BeforeEach
    void setUp() {
        game = new BowlingGameScore();
    }

    @Test
    void
    game_no_pins_get_hit() {
        rollMany(0, 20);

        Assertions.assertEquals(0, game.score());
    }

    @Test
    void
    game_just_1_pin_get_hit() {
        rollMany(1, 20);

        Assertions.assertEquals(20, game.score());
    }

    @Test
    void
    game_with_1_spare() {
        rollSpare();
        game.roll(3);
        rollMany(0, 17);

        Assertions.assertEquals(16, game.score());
    }

    @Test
    void
    game_with_1_strike() {
        game.roll(10);
        game.roll(3);
        game.roll(4);
        rollMany(0, 16);

        Assertions.assertEquals(24, game.score());
    }

    @Test
    void
    game_of_strikes() {
        rollMany(10, 12);

        Assertions.assertEquals(300, game.score());
    }

    @Test
    void
    knockdown_nine_and_miss_ten_times() {

        int firstRollPinsKnockedDown = 9;
        int secondRollPinsKnockedDown = 0;
        int repeatTimes = 10;
        rollPair(repeatTimes, firstRollPinsKnockedDown, secondRollPinsKnockedDown);

        Assertions.assertEquals(90, game.score());
    }

    @Test
    void
    knockdown_five_and_spare_ten_times_and_fice() {
        rollPair(10, 5, 5);
        game.roll(5);

        Assertions.assertEquals(150, game.score());
    }

    private void rollPair(int repeatTimes, int firstRollPinsKnockedDown, int secondRollPinsKnockedDown) {
        for (int i = 0; i < repeatTimes; i++) {
            game.roll(firstRollPinsKnockedDown);
            game.roll(secondRollPinsKnockedDown);
        }
    }

    private void rollSpare() {
        game.roll(5);
        game.roll(5);
    }

    private void rollMany(int pins, int times) {
        for (int i = 0; i < times; i++) {
            game.roll(pins);
        }
    }
}


texts: Solving an ODE numerically with forward Euler method

texts:
The goal is to solve an ODE numerically with forward Euler method. The programs works well (numerical solution really near analytical one). The problem I see is that the Euler scheme don't jump to eyes, probably because of push_back() functions. This approach is the only one I found to let the time of simulation (number of steps) be variable (change only the t_max constant). Do you have any idea to improve the clarity of the program?

/*  R. M.
        20.08.2012
    Exercice 1.2 of Computational Physics, N. Giordano and H. Nakanishi
        Euler method to solve: dv/dt = a - bv
*/

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

void calculate(std::vector<double>& time, std::vector<double>& velocity, const double t_max, const double dt, const double a, const double b)
{
    const int iterations(t_max / dt);

    for(int i(1); i < iterations; i++)
    {
        time.push_back( time[i-1] + dt );
        velocity.push_back( a * dt + (1 - b*dt) * velocity[i-1] );
    }
}

void save(const std::vector<double>& time, const std::vector<double>& velocity, const std::string& filename)
{
    std::ofstream file_out(filename);

    for(int i(0); i < time.size(); i++)
    {
        file_out << time[i] << ' ' << velocity[i] << std::endl;
    }

    file_out.close();
}

int main()
{
    // Constants
    constexpr double t_max(8);          // Time to end simulation
    constexpr double dt(0.01);          // Time step
    constexpr double a(10.);            // Acceleration
    constexpr double b(1.);             // Air friction

    std::vector<double> time({0});      // Initial time (t = 0)
    std::vector<double> velocity({0});  // Initial velocity (v = 0)

    calculate(time, velocity, t_max, dt, a, b);
    save(time, velocity, "veocity.dat");

    return 0;
}