texts: Implementing an "Add Company" section in a project

texts:
I'm working on avoiding JavaScript that either directly modifies the DOM a ton, contains a ton of anonymous functions, or is encapsulated in giant $(document).ready... blocks.

This is one of my first attempts at writing a section of my project in a better way.  The code is commented and organized fairly well, so it should be easy to understand how it functions.  My main question is: Am I going about this the right way?

// Object literal for handling all aspects of adding a company
var addCompany = {

  // Initialize object
  init: function() {

    // Save elements references
    addCompany.elements = {
      openForm: $('#add-company-btn'),
      form: $('#add-company-form'),
      usernameField: $('#username'),
      usernameErrorField: $('#username-error div'),
      passwordField: $('#password'),
      passwordErrorField: $('#password-error div'),
      password2Field: $('#password2'),
      password2ErrorField: $('#password2-error div'),
    };

    // Run on click
    addCompany.elements.openForm.click(
      addCompany.focusFirst
    );

    // Run on focus
    addCompany.elements.form.submit(
      addCompany.validate
    );
  },

  // Focus the first input field
  focusFirst: function() {
    setTimeout(function(){
      addCompany.elements.usernameField.focus();
    }, 0);
  },

  // Validate the form
  validate: function() {

    // Store the error tests
    var noUsername = (addCompany.elements.usernameField.val().trim() === ''),
        noPassword = (addCompany.elements.passwordField.val().trim() === ''),
        differentPasswords = (addCompany.elements.passwordField.val() !== addCompany.elements.password2Field.val());

    // Return the results of running the tests
    return addCompany.handleError(addCompany.elements.usernameErrorField, noUsername) &&
           addCompany.handleError(addCompany.elements.passwordErrorField, noPassword) &&
           addCompany.handleError(addCompany.elements.password2ErrorField, differentPasswords);
  },

  // Given an error, handle the display of error fields
  handleError: function(error_field, error) {
    if(error) {
      error_field.show();
      return false;
    } else {
      error_field.hide();
      return true;
    }
  }
};


texts: Prim's Lazy Minimum Spanning Tree Algorithm in Haskell (Project Euler# 107)

texts:
I have implemented Lazy version of Prim's Minimum Spanning Tree Algorithm. I want to improve the code structure, follow prevalent conventions and reduce code size. I am solving Project Euler #107.

Explanation:

I do as follows for MST:

Initialize an adjacency list, visited set with vertice #0, min-priority heap/queue for edges with shortest edge from vertice #0, sum of edges in MST as 0.
Find next edge, if it is not a crossing edge, recurse.
Otherwise I include that edge (by updating visited and heap/queue) and add to MST sum the edge's weight.

Note: Non-existent edges have been assigned value -1.

Code:

import           Data.Array
import qualified Data.Heap       as Heap
import           Data.List.Split
import           Data.Maybe
import qualified Data.Set        as Set

dim = 40 :: Int

main :: IO ()
main = print . maximumSaving . toAdjacencyMatrix . map (wordsBy (==',')) . lines
    =<< readFile "txt/107.txt"
    where
        toAdjacencyMatrix mat = array ((0,0),(dim-1,dim-1))
            [ ((i,j), if val == "-"  then -1 else read val)
                | i <- [0..dim-1], j <- [0..dim-1], let val = mat !! i !! j]
        totalWeight network = sum [network ! (i,j) | i <- [0..dim-1], j <- [0..dim-1], i < j, network ! (i, j) > 0]
        maximumSaving network = totalWeight network - minimumSpanningTreeEdgeSum network

minimumSpanningTreeEdgeSum :: Array (Int, Int) Int -> Int
minimumSpanningTreeEdgeSum adj =
    minimumSpanningTree'
        adj
        (Set.singleton 0)
        (Heap.fromList [(adj!(0,a),(0, a)) | a <- [1..dim-1], adj ! (0,a) > 0])
        0
    where
        minimumSpanningTree' :: Array (Int, Int) Int -> Set.Set Int -> Heap.MinPrioHeap Int (Int, Int) -> Int -> Int
        minimumSpanningTree' adj visited queue sm = case Heap.viewHead queue of
            Nothing          -> sm
            (Just (weight, edge)) ->
                if isCrossingEdge edge then
                    let sm' = sm + weight in
                    let nextVertice = if Set.notMember (fst edge) visited then fst edge else snd edge in
                    let visited' = Set.insert nextVertice visited in
                    let newEdges = [(i, j) | a <- [0..dim-1], let i = min nextVertice a, let j = max nextVertice a, Set.notMember i visited, adj ! (i,j) > 0 ] in
                    let queue'' = foldl (flip Heap.insert) queue' $ map (\e -> (adj ! e, e)) newEdges
                    in minimumSpanningTree' adj visited' queue'' sm'
                else
                    minimumSpanningTree' adj visited queue' sm
            where
                queue' = fromJust $ Heap.viewTail queue
                isCrossingEdge edge = Set.notMember (fst edge) visited ||
                    Set.notMember (snd edge) visited


texts: Abstract factory design for different cars

texts:
Is there anything wrong with this?

    namespace WindowsFormsApplication1
    {
      public interface ICarfactory
      {
        ICar getCar(CarType carType);
      }

      public interface ICar
      {
      }

      public class Sedan: ICar
      {
      }

      public class Hatchback : ICar
      {
      }

      public class SUV : ICar
      {
      }

      public class HondaSUV : SUV
      {
      }

      public class HondaSedan : Sedan
      {
      }

      public class HondaHatchback : Hatchback
      {
      }

      public class HyundaiSUV : SUV
      {
      }

      public class HyundaiSedan : Sedan
      {
      }
      public class HyundaiHatchback : Hatchback
      {
      }

      public class MarutiHatchback : Hatchback
      {
      }

      public class MarutiSUV : SUV
      {
      }

      public class MarutiSedan : Sedan
      {
      }

      public class Hyundai : ICarfactory
      {
        public ICar getCar(CarType carType)
        {
          switch (carType)
          {
            case CarType.Sedan:
              return new HyundaiSedan();
            case CarType.HatchBack:
              return new HyundaiHatchback();
            case CarType.SUV:
              return new HyundaiSUV();
            default:
              return null;
          }
        }

      }

      public class Maruti : ICarfactory
      {
        public ICar getCar(CarType carType)
        {
          switch (carType)
          {
            case CarType.Sedan:
              return new MarutiSedan();
            case CarType.HatchBack:
              return new MarutiHatchback();
            case CarType.SUV:
              return new MarutiSUV();
            default:
              return null;
          }
        }
      }

      public class Honda : ICarfactory
      {
        public ICar getCar(CarType carType)
        {
          switch (carType)
          {
            case CarType.Sedan:
               return new HondaSedan();
            case CarType.HatchBack:
               return new HondaHatchback();
            case CarType.SUV:
              return new HondaSUV();
            default:
              return null;
          }
        }
      }

      public enum CarType
      {
        Sedan,
        HatchBack,
        SUV
      }
    }

 private void button4_Click(object sender, EventArgs e)
  {
  ICar myCar;
  ICarfactory carfactory;
  carfactory = new Hyundai();
  myCar = carfactory.getCar(CarType.SUV);
  myCar = carfactory.getCar(CarType.HatchBack);
  myCar = carfactory.getCar(CarType.Sedan);

  carfactory = new Honda();
  myCar = carfactory.getCar(CarType.SUV);
  myCar = carfactory.getCar(CarType.HatchBack);
  myCar = carfactory.getCar(CarType.Sedan);

  carfactory = new Maruti();
  myCar = carfactory.getCar(CarType.SUV);
  myCar = carfactory.getCar(CarType.HatchBack);
  myCar = carfactory.getCar(CarType.Sedan);
  }


texts: C++ reduce repetitions of code for similar classes

texts:
I have the following two classes to make appending strings - and wstrings respectively - easier:

#include <string>
#include <sstream>

class StringBuilder
{
public:
    template <typename T>
    StringBuilder& operator<<(const T& t)
    {
        this->stream << t;
        return *this;
    }

    operator std::string() const;

private:
    std::ostringstream stream;
};

StringBuilder::operator std::string() const
{
    return this->stream.str();
}

class WStringBuilder
{
public:
    template <typename T>
    WStringBuilder& operator<<(const T& t)
    {
        this->stream << t;
        return *this;
    }

    explicit operator std::wstring() const;

private:
    std::wstringstream stream;
};

WStringBuilder::operator std::wstring() const
{
    return this->stream.str();
}

Now, as you see, pretty much all of the code (except for the concrete string and stringstream types) is repeated, especially the operators.

The question is:

Is there any way to reduce the duplicated code? I thought about a base class, templates and specialization, but the problem is I don't know how to determine the correct stringstream type depending on the string type then.


texts:
I am solving some questions on HackerRank for practice purposes. This morning I solved one called Maximum sum of hourglass in an array.

Given an array:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

the hourglass sum is 7 and we need to find the maximum sum of all hourglass in an array.

My implementation:

#include <vector>
#include <iostream>
#include <climits>

using std::vector;

int hourglassSum(vector<vector<int>> &arr) {
    int highestSum = INT_MIN;
    for (size_t i = 1; i < arr.size() - 1; ++i) {
        int sum = 0;
        for (size_t j = 1; j < arr.at(i).size() - 1; ++j) {
            sum = arr.at(i - 1).at(j - 1) +
                  arr.at(i - 1).at(j) +
                  arr.at(i - 1).at(j + 1) +
                  arr.at(i).at(j) +
                  arr.at(i + 1).at(j - 1) +
                  arr.at(i + 1).at(j) +
                  arr.at(i + 1).at(j + 1);
            if (sum > highestSum) {
                highestSum = sum;
            }
        }
    }
    return highestSum;
}

int main() {
    vector<vector<int>> nums =
        {{1, 1, 1, 0, 0, 0}, // 0
         {0, 1, 0, 0, 0, 0}, // 1
         {1, 1, 1, 0, 0, 0}, // 2
         {0, 0, 2, 4, 4, 0}, // 3
         {0, 0, 0, 2, 0, 0}, // 4
         {0, 0, 1, 2, 4, 0}}; // 5
    vector<vector<int>> nums2 =
        {{0, -4, -6, 0, -7, -6},
         {-1, -2, -6, -8, -3, -1},
         {-8, -4, -2, -8, -8, -6},
         {-3, -1, -2, -5, -7, -4},
         {-3, -5, -3, -6, -6, -6},
         {-3, -6, 0, -8, -6, -7}};
    std::cout << hourglassSum(nums) << std::endl;  // expected 19
    std::cout << hourglassSum(nums2) << std::endl;  // expected -19
}

My questions:

I think the runtime of this code is O(n*m), does anyone think there is a better way of doing this?
Does the code look efficient and readable?

Thanks


texts:
After scanning some of the questions here about resource managers I've made some changes, and while it is much improved I still feel it's not quite up to snuff.

It tried to make it work for all data types that inherit from resource and load the resource automatically if not yet available.

Resource.h

class Resource {
public:
    Resource() {};
    virtual ~Resource() {};

    virtual void load(const std::string& path) = 0;
    virtual void unload() = 0;

protected:
    unsigned mResourceId;
    std::string mResourcePath;

};

// Custom destructor for smart pointer
struct ResourceFree {
    void operator()(Resource* resource) {
        resource->unload();
        delete resource;
    }
};

class Texture : public Resource {
public:
    int width;
    int height;
    int channels;
    unsigned char* data;

    void load(const std::string& path);
    void unload();
};

And ResourceManager.h

class ResourceManager {
public:
    template <typename T>
    T& load(const std::string& name) {
        static_assert(std::is_base_of<Resource, T>::value, "T must inherit from Resource");

        auto found = resources.find(name);
        if (found == resources.end()) {
            T* resource_instance = new T;
            Resource* resource_base = dynamic_cast<Resource*>(resource_instance);
            resource_base->load(name);
            resources.emplace(name, resource_base);

            return *resource_instance;
        } else {
            return *dynamic_cast<T*>(found->second.get());
        }
    }

    void unload(const std::string& path) {
        resources.erase(path);
    }
private:
    std::unordered_map<std::string, std::unique_ptr<Resource, ResourceFree>> resources;
};

I'm doing a lot of dynamic casting, but I don't see how to do it differently. Maybe there are some C++17 things that make this a little nicer? Or perhaps I'm going at it the wrong way


texts: Find all substrings that contain k specific characters in a string

texts:
Given a string, return the count of the number of substrings that contains characters A, B and C. Two substrings are considered different if the starting, ending or both positions differ.

Example - s = "ABBCZBAC", there are 13 substrings which are "ABBC", "ABBCZ", "ABBCZB", "ABBCZBA", "ABBCZBAC", "BBCZBA", "BBCZBAC", "BCZBA", "BCZBAC", "CZBA", "CZBAC", "ZBAC", "BAC".

My code in Java is giving timeout error for large inputs. my code is

public static long find(String s)
{
    for(int i=0;i<s.length()-2;i++)
    {
        int j=i+3;
        while(j<=s.length() && !(s.substring(i,j).contains("A") && s.substring(i,j).contains("B") && s.substring(i,j).contains("C"))
            j++;
        count += s.length()-j+1;
    }
    return count;
}

I tried to improve this code by finding indexes directly and storing them but still, I was getting timeout errors for large inputs. Can anyone give me a better approach to solve this question may be in O(n)?


texts: Handle concurrent HTTP requests with a generic .ashx

texts:
I have created a .ashx file that is able to handle concurrent http requests.

Works great, but now I'd like to create a base class that does the common work in order to not repeat myself each time I need to create a new .ashx of the same kind.

Here is my current code for the http handler:

public class BaseAsyncHandler : IHttpAsyncHandler, IRequiresSessionState
{
    public bool IsReusable
    {
        get { return false; }
    }

    public BaseAsyncHandler()
    {
    }

    public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
    {
        BaseAsynchOperation asynch = new BaseAsynchOperation(cb, context, extraData);
        asynch.StartAsyncWork();
        return asynch;
    }

    public void EndProcessRequest(IAsyncResult result)
    {
    }

    public void ProcessRequest(HttpContext context)
    {
        throw new InvalidOperationException();
    }
}

public class BaseAsynchOperation : IRequiresSessionState, IAsyncResult
{
    private bool _completed;
    private Object _state;
    private AsyncCallback _callback;
    public HttpContext _httpContext;

    bool IAsyncResult.IsCompleted
    {
        get { return _completed; }
    }

    WaitHandle IAsyncResult.AsyncWaitHandle
    {
        get { return null; }
    }

    Object IAsyncResult.AsyncState
    {
        get { return _state; }
    }

    bool IAsyncResult.CompletedSynchronously
    {
        get { return false; }
    }

    public BaseAsynchOperation(AsyncCallback callback, HttpContext context, Object state)
    {
        _callback = callback;
        _httpContext = context;
        _state = state;
        _completed = false;
    }

    public void StartAsyncWork()
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(StartAsyncTask), null);
    }

    protected virtual void OnBeforeStartAsyncTask()
    {
    }

    public void StartAsyncTask(Object workItemState)
    {
        OnBeforeStartAsyncTask();

        _httpContext.Response.ContentType = "application/json";

        _completed = true;
        _callback(this);
    }
}

My new test that inherits from the base class:

public class TestAsyncHandler : BaseAsyncHandler
{
    public TestAsyncHandler()
    {

    }
}

public class TestAsyncOperation : BaseAsynchOperation
{
    public TestAsyncOperation(AsyncCallback callback, HttpContext context, object state) : base(callback, context, state)
    {
    }

    protected override void OnBeforeStartAsyncTask()
    {
        var test = _httpContext.Request["test"]; // code never ends up here...
    }
}

Since all my work is done in the StartAsyncTask() method (similar to ProcessRequest() in a regular generic handler .ashx), I thought that I add a method there which can be overridden. However, it never seems to get called.

What did I miss? Do you have any other suggestions on improvments?


texts: PHP: checking for $_GET variables with if statements

texts:
This code gets me where I need to be, but my word it is ugly.

I am checking for the existence of two $_GET variables with if() statements. I am setting the variables to empty strings first so I do not get an error when I echo them back.

$getvar1 ='';
$getvar2 ='';
$np ='';

if(isset($_GET['getvar1'])) $page_id = $_GET['getvar2'];
if(isset($_GET['getvar2'])) $route = $_GET['getvar2'];

if(($getvar1 == '' && $getvar1 == '') || $getvar1 == '4')  $np = 'np';

    echo "$getvar1 $getvar2 $np";

Is there a better way to declare the variables than setting them to empty strings?

Is there a better way to check and set the $_GET variables?


texts: INSERTing a student info record based on form inputs

texts:
I want to improve my coding skills. How do I write this code with concatenation

string query = "insert into StudentInfo values ('" + textBox1.Text.Trim() + "', '" + Name.Trim() + "', '" + comboBox1.SelectedItem.ToString() + "') ";
SqlCommand command = new SqlCommand(query, cn);
command.ExecuteNonQuery();


texts:
I am doing a coding exercise in codility and I came across this question:

  A binary gap within a positive integer N is any maximal sequence of
  consecutive zeros that is surrounded by ones at both ends in the
  binary representation of N.

  For example, number 9 has binary representation 1001 and contains a
  binary gap of length 2. The number 529 has binary representation
  1000010001 and contains two binary gaps: one of length 4 and one of
  length 3. The number 20 has binary representation 10100 and contains
  one binary gap of length 1. The number 15 has binary representation
  1111 and has no binary gaps.

  Write a function:

  class Solution { public int solution(int N); } that, given a positive
  integer N, returns the length of its longest binary gap. The function
  should return 0 if N doesn't contain a binary gap.

  For example, given N = 1041 the function should return 5, because N
  has binary representation 10000010001 and so its longest binary gap is
  of length 5.

  Assume that:

  N is an integer within the range [1..2,147,483,647]. Complexity:

  expected worst-case time complexity is O(log(N)); expected worst-case
  space complexity is O(1).

My code looks like this:

import java.util.*;

class Solution {
    public static int solution(int N) {
        return Optional.ofNullable(N)
        .map(Integer::toBinaryString)
        .filter(n -> n.length() > 1)
        .map(t -> {
            List<Integer> counts = new ArrayList<>();
            int count = 0;
            for(int i = 0; i < t.length(); i++)
            {
                if(t.charAt(i) == '0') {
                    count += 1;
                } else if(count > 0) {
                    counts.add(count);
                    count = 0;
                }
            }
            if(counts.size() > 0) {
                Collections.sort(counts);
                return counts.get(counts.size() - 1);
            }
            return 0;
        })
        .orElse(0);
    }
}

What else can I do to improve the performance of the aforementioned code? How do I determine the big-O complexity of this program?


texts: Greatest difference between numbers in list

texts:
I found this problem today and eventually came up with a solution. I'm interested in knowing other ways to solve it. You have a list of unsorted integers, and have to compute the greatest difference between list[j] - list[i] such that i < j.

Here's my code:

#include <stdio.h>

// remember the minimum to the left
static int _cached_max(int min, int n, int const* list)
{
  if(n < 1){
    return 0x80000000;
  }

  int max_index = 0;
  for(int i = 1; i < n; ++i){
    if(list[i] >= list[max_index]){
      max_index = i;
    }
  }

  // I know you can check this condition inside the loop above by keeping
  // some extra variables, keeping it here for readability
  for(int i = 0; i < max_index; ++i){
    if(list[i] < min){
      min = list[i];
    }
  }

  int this = list[max_index] - min;
  int next = _cached_max(min, n - max_index - 1, list + max_index + 1);

  return this > next ? this : next;
}

int custom_max(int n, int const* list)
{
  return _cached_max(list[0], n - 1, list + 1);
}

int main(int argc, char* argv[])
{
  int list[] = {12,21,10,20,9,18};
  int max = custom_max(sizeof list / sizeof list[0], list);

  printf("max = %d\n", max);

  return 0;
}

What is the optimal solution to this problem?

Update:

Here's some sample inputs and outputs:

F( [10;4;5;0;8] ) = 8
F( [10;7;16;5;11;3;9;0] ) = 9
F( [4;5;0;1;2;3;1;8] ) = 8
F( [12;21;10;20;9;18] ) = 10
F( [5;4] ) = -1


texts: Rails passing in params to association on create method

texts:
I am currently using a belongs_to relationship in my Rails application to link a map and a group an object that way I can assign those maps to the user based on the group they are in.

I have this mapgroup model.

class Mapgroup < ApplicationRecord
  belongs_to :map, optional: true
  belongs_to :group, optional: true
end

I am getting the map from a dropdown menu in the form but I don't want a dropdown for the group because the use is already in that group.

I opted to assign the group_id in the url to the mapgroup in the create method.

def create
  @mapgroup = Mapgroup.create(mapgroup_params)
  @mapgroup.group_id = params[:group_id] <-- right here

  respond_to do |format|
    if @mapgroup.save
      format.html { redirect_to groups_path, notice: 'Mapgroup crated' }
    else
      format.html { render :new, notice: 'That shit failed' }
    end
  end
end

Is this a good practice? I have done this in previous apps but it seems a bit...smelly. Is there a more elegant way to do this?


texts: Select records between the first and last time the speed was positive

texts:
I have the following table:

id   speed   date
1    0       01/01/2015
2    0       01/01/2015
3    0       01/01/2015
4    0       01/01/2015
5    0       01/01/2015
6    0       01/01/2015
7    25      01/01/2015
8    78      01/01/2015
9    13      01/01/2015
10   45      01/01/2015
11   0       01/01/2015
12   80      01/01/2015
13   86      01/01/2015
14   10      01/01/2015
15   0       01/01/2015
16   0       01/01/2015
17   0       01/01/2015
18   0       01/01/2015

This is just a small part of the table, it has many dates. Each new date starts and ends with an unknown amount of zeros. And I have to skip these zeros and get only what's between them. So I came up with the following solution:

Get the ID of the first row whose speed is positive (in our table it's id number 4).
Get the ID of the last row whose speed is positive (in our table it's id number 12).
Get lines between these two IDs (4 and 12).

I get the id of the first row whose speed is positive:

$q1=$conn->prepare("SELECT * FROM tableX WHERE speed > 0 order by date asc LIMIT 1");
$q1->execute();
$r1=$q1->fetch();
$first_id = $r1['id'];

And then get the id of the last row whose speed is positive:

$q2=$conn->prepare("SELECT * FROM tableX WHERE speed > 0 order by date desc LIMIT 1");
$q2->execute();
$r2=$q2->fetch();
$last_id = $r2['id'];

And then use those ids to get what I want:

$q3=$conn->prepare("SELECT * FROM tableX WHERE id between '$first_id' and '$last_id'");
$q3->execute();
while($r3=$q3->fetch(){}

Expected result:

id   speed   date
7    25      01/01/2015
8    78      01/01/2015
9    13      01/01/2015
10   45      01/01/2015
11   0       01/01/2015
12   80      01/01/2015
13   86      01/01/2015
14   10      01/01/2015

My code is actually working but I think this solution of mine is lame, so I am looking for an improvement, kind of all these three queries in one!


texts: Apply additions on a base array based on date ranges

texts:
please roast my code, I hope this is the good place to look for some advice on where I can improve.

Problem definition:

Apply modifications on values depending on date ranges.

Data:

Base array - holds dictionaries in the following format:

[{'date': 20200101, 'value': 1}, {'date': 20200102, 'value': 2}]

Modifier array - holds dictionaries with similar format:

[{'date': 20200101, 'value': 1}, {'date': 20200201, 'value': 2}]

Edit: Both arrays are holding values with dates sorted in ascending order.

Goal:
Add the respective value of the modifier array to the base array lining up the date ranges. Dates are exclusive, for example when the modifier array contains 2020-01-01 you have to add the value '1' to all values in the base array that have a date less than 2020-01-01. Base array has a lot of elements while modifier array relatively few. In practice this splits the base array into a couple of date ranges. If the last modification date is less than the date in base array no modification is required.

My solution:

This is assuming the comparing of dates will work, I have translated this from perl for an easier read.

mod_index = 0
mod_size = len(mod_arr)

for elem in base_arr:
  if elem['date'] > mod_arr[mod_size - 1]['date']:
    break
  else:
    if elem['date'] < mod_arr[mod_index]['date']:
      elem['value'] += mod_arr[mod_index]['value']
    else:
      elem['value'] += mod_arr[mod_index + 1]['value']
      mod_index += 1


texts: Bisect Insertion Container for Calculating Running Median

texts:
I'm looking for general feedback on this implementation. What issues might it  have? How could it be improved?

public class FindRunningMedian
{
    public void Run(string[] args)
    {
        var bound = 100000;
        var rando = new Random();
        var values = new[] { bound.ToString() }.Concat((from i in Enumerable.Range(0, bound)
                                                        select rando.Next(int.MaxValue / 2).ToString())).ToArray();

        RunBiSect(values);
    }

    public void RunBiSect(string[] args)
    {
        var count = Convert.ToInt32(args.First());
        var valus = args.Skip(1).Select(s => Convert.ToInt32(s)).ToArray();
        var sortd = new MedianList(count);

        foreach (var value in valus)
        {
            Console.WriteLine($"{sortd.InsertForMedian(value):F1} ");
        }
    }

    public class MedianList
    {
        private int _count;
        private float _iters;
        private int[] _values;

        public MedianList(int capacity)
        {
            _values = new int[capacity];
        }

        public int Count { get { return _count; } }

        public float Iterations { get { return _iters; } }

        public float IterationsPer { get { return _iters / Math.Max(1, _count); } }

        public int[] GetValues()
        {
            var copy = new int[_values.Length];
            _values.CopyTo(copy, 0);
            return copy;
        }

        public float InsertForMedian(int value)
        {
            Insert(value);
            var median = 0.0f;
            var middle = _count / 2;

            if (_count == 1) { median = _values[0]; }
            else if (_count % 2 == 0) { median = (_values[middle] + _values[middle - 1]) / 2.0f; }
            else { median = _values[middle]; }

            return median;
        }

        public void Insert(int value)
        {
            if (_count == 0) { _values[0] = value; }
            else
            {
                var index = FindDestinationIndex(value);
                Array.Copy(_values, index, _values, index + 1, _count - index);
                _values[index] = value;
            }
            _count++;
        }

        public int FindDestinationIndex(int value)
        {
            var max = _count - 1;
            int mid = 0, cmp = 0, min = 0;

            if (value.CompareTo(_values[0]) <= 0) { return 0; }
            else if (value.CompareTo(_values[_count - 1]) >= 0) { return _count; }

            while (max > (min + 1))
            {
                mid = Convert.ToInt32(Math.Min(Math.Ceiling((max - min) / 2.0f) + min, _count - 1));
                cmp = value.CompareTo(_values[mid]);

                if (cmp == 0) { return mid; }
                else if (cmp > 0) { min = Math.Max(mid, min + 1); }
                else if (cmp < 0) { max = Math.Min(mid, max - 1); }

                _iters++;
            }

            mid = value.CompareTo(_values[min]) > 0 && value.CompareTo(_values[max]) <= 0 ? max : min;

            cmp = value.CompareTo(_values[mid]);

            var index = cmp > 0 ? mid + 1 : mid;
            return index;
        }
    }
}


texts:
I'm using node-ftp to download some files from an FTP server; due to nodeback difficulty and nested calls I'm promisified some of the calls, hoping that this will help get me out of pyramid code hell, but I think I'm still mis-applying something.

Before I get to my code pasted below, conceptually the pseudo-code of what I'm trying to do is:

foreach directory in a list:
    list files in directory
    filter to only files of interest
    download those files, save them to /tmp/whatever.

The objective is to end with a list of files downloaded and local paths.

I have code that works, but it's god-awful ugly and is not living up to the "promise of promises".  How can I re-arrange this to be more like the pseudo code above, and aggregate the results?   Part of the trouble is that the "list files in directory" is a promise, and each download returns a promise of a data stream.  So unless I do this smartly, it's a 3-level nested array of promises that all have to be resolved, with the very bottom level promise results the intended return value.

//Main handler: when the connection is ready, start doing stuff.
c.on('ready', function() {
    config.clientCheckPaths
    .map(function (lookInPath) {
        console.log('Examining ' + lookInPath);

        // Go get directory contents.
        listAsync(lookInPath)
        .then(function (files) {
            console.log('Files: ' + files.map(function (i) { return i.name; }));

            var wantedFiles = files.filter(function (item) {
                return config.isFileWanted(item.name);
            });

            // Filter it down to only the files we want.
            var arrayOfDownloadPromises = wantedFiles.map(function (x) {
                // For each file, go download it.
                return new Promise(function (resolve, reject) {
                    var fullPath = lookInPath + '/' + x.name;

                    console.log("Wanted file: " + lookInPath + '/' + x.name + ", " + Object.keys(x));

                    getAsync(fullPath)
                    .then(function (stream) {
                        // With the stream, name it something reasonable on the disk.
                        var localFileName = '/tmp/' + fullPath.replace(/[^A-Za-z0-9\.]/g, '_');
                        console.log("Writing stream to " + localFileName);
                        stream.once('close', function() {;});
                        stream.pipe(fs.createWriteStream(localFileName));

                        resolve(localFileName);
                    }, function(err) {
                        var msg = 'Getting file ' + fullPath + ' failed with ' + err;
                        console.error(msg);
                        reject(msg);
                    })
                });
            });

            // We then need to re-join all of the download promises and proceed
            // when they're all finished.
            return Q.all(arrayOfDownloadPromises);
        }, function(err) {
            console.error('Listing directory ' + lookInPath + ' failed with ' + err);
        });
    })
    .map(function (promise) {
        console.log('Final: ' + promise);
    });
});

This code performs the right actions now, but doesn't aggregate the results correctly, and is ugly.  How to refactor this when I have multi-level nested promises?


texts: I am learning how to properly use Java parameters and arguments

texts:
I am learning to use parameters and arguments in Java to make my coding efficient. I am open to suggestion if I've done something wrong with this code of mine.
import java.util.Scanner;

public class paramsAndArgs {

    static String name, feeling;

    public static void main(String[] args) {
        doesSomething(name, feeling);
    }

    private static void doesSomething(String name, String feeling) {
        Scanner scan = new Scanner(System.in);

        System.out.println("What is your name?");
        name = scan.nextLine();
        System.out.println("How are you today?");
        feeling = scan.nextLine();

        System.out.println("Hello, " + name + ". I am feeling " + feeling + " too.");
    }
}
```


texts: Select box to highlight choice deviation

texts:
I have a select box that in default state looks as default (white, etc)
but when I select a different value, I want the entire table row to highlight in yellow.

I did this, but I want to make it better and more concise and more efficient.  Can you help?

Also I will have several such boxes, not just one.  Feel free to change/add/remove identifiers, I am looking for a better solution overall.

$(document).ready(function() {

  $("#closedRow").on('change', function() {
    if ($("#closedRow").val() != 0)
      $("#trRow").css('background-color', 'yellow');
    else
      $("#trRow").css('background-color', 'white');
  })

    $("#serviceRow").on('change', function() {
    if ($("#serviceRow").val() != 0)
      $("#trRow2").css('background-color', 'yellow');
    else
      $("#trRow2").css('background-color', 'white');

  })
})

    Closed:
    <select name="closed" id="closedRow">
            <option value="0">Show All</option>
            <option value="1">Hide Closed</option>
        </select>

    Service:
    <select name="service" id="serviceRow">
            <option value="0">Show All</option>
            <option value="1">Hide Service</option>
            <option value="2">Another Service</option>
        </select>


texts: Generating a QuestionID Using a Nested Loop for a Quiz Game

texts:
So I started learning OOs and code refactoring and decided to do some project. It just some simple quiz game.

Here are some mechanics

There are 3 sets
Each set have 8 Brands (types)
Each brand have 10 questions

So what I did was this

Set Class

public class Set{
    public string setName;
    public Brand[] brands;
}

Brand Class

public class Brand{
    public string brandName;
    public Question[] questions;
}

Question Class

public class Question {
    public string question;
    public string[] choices = new string[3];  //choices for each question
    public string correctAnswer;  //will hold the correct answer for a question

    public string questionID(){
       // making a id for question
        string qID = "";

        qID += question + "|";

        foreach(string choice in choices){
            qID += choice + "|";
        }

        qID += correctAnswer + "|";

        qID += fontSize;

        return qID;
    }

}

So what I need is to create some kind of id for each question, what I did is this

public class QuestionManager : MonoBehaviour {
public void saveToDB(){
    int setID = 0;
      foreach(Set set in sets){

          int brandID = 0;
          foreach(Brand brand in set.brands){

              int questionID = 0;
             foreach(Question question in brand.questions){

                string questionKey = "s" + setID + "|" + "b" + brandID + "|" + "q" + questionID;
                string questionAnswer =  "value:"+ set.setName + "|" + brand.brandName + "|" + question.questionID() ;

                PlayerPrefs.SetString(
                key: questionKey,
                value: questionAnswer
                );  // save to the database

                questionID++;
          }
            brandID++;
          }
          setID++;
      }

}
}

I'm really curious if there are some good refactoring for this kind of loop. Also I should add that I'll be using this ids for getting the questions later.


texts:
Online challenge on Hacker Rank.

  Shashank likes strings in which consecutive characters are different.
  For example, he likes ABABA, while he doesn't like ABAA. Given a
  string containing characters A and B only, he wants to change it
  into a string he likes. To do this, he is allowed to delete the
  characters in the string.

  Your task is to find the minimum number of required deletions.

  Input Format

  The first line contains an integer T, i.e. the number of test cases.
  The next T lines contain a string each.

  Output Format

  For each test case, print the minimum number of deletions required.

public class Solution {
    private static int countChanges(String text) {
        char[] chars = new char[text.length()];
        int top = -1;

        int count = 0;
        for (char c : text.toCharArray()) {
            if (top < 0 || c != chars[top]) {
                chars[++top] = c;
            } else {
                // top >= 0 or c == chars[top]
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        for (int i = 0; i < N; i++) {
            System.out.println(countChanges(s.next()));
        }
    }
}


texts:
I am a beginner in Java and I have a hobby project to create a tool for statistical calculations.
Users can upload csv with results of a survey. The responses stored in a Response object which has two maps: Map<Integer, String> questionMap, Map<Integer, String> answerMap, where the integer(questionID) links the question and answer.

I would like implement an extra feature: to filter the responses to certain values. Therefore the Filter class stores a questionID (int) and a filterValue (String).
Now I would like to calculate the averages of the fields. I have a working implementation but I hope you can help me to make it better:

public List<AverageResult> calculateAverage(List<Response> responses,     List<Filter> filters){
    List<Response> responsesCopy = new ArrayList<>(responses);
    List<AverageResult> averages = new LinkedList<>();
    Set<Integer> questionIDSet = responses.get(0).getAnswerMap().keySet();
    for(Integer questionID :questionIDSet) {
        double sum = 0;
        int count=0;
        for(Iterator<Response> iter = responsesCopy.iterator(); iter.hasNext();) {
            Response actualResponse = iter.next();
            if(filterMatch(actualResponse,filters)) {
                if(isNumber(actualResponse, questionID)) {
                    sum += Double.valueOf(actualResponse.getAnswerMap().get(questionID));
                    count += 1;
                }
            }else {
                iter.remove();
            }
        }
        Double average = null;
        if(count != 0) {
            average = sum/count;
            AverageResult avRes = new AverageResult();
            avRes.setAverage(average);
            avRes.setQuestionID(questionID);
            avRes.setCount(count);
            averages.add(avRes);
        }
    }
    return averages;
}

private boolean isNumber(Response response, int questionID) {
    Pattern p = Pattern.compile("[0-9]*\\.?[0-9]+");
    return (p.matcher(response.getAnswerMap().get(questionID)).matches());
}

private boolean filterMatch(Response response, List<Filter> filters) {
    for(Filter filter: filters) {
        if(!response.getAnswerMap().get(filter.getQuestionID()).equals(filter.getFilterValue())) {
            return false;
        }
    }
    return true;
}


texts:
Is there a better way to write the following code fragment?

I can't have more than 10 conditional statement in my method as it gives cyclomatic complexity.

private List<AutoDto> getFilteredAutoList()
{
    List<AutoDto> autoList = getAutoListForCoverage();
    List<AutoDto> filteredAutoList = new ArrayList<AutoDto>();

    for(AutoDto auto : autoList)
    {
        if("FAQ025".equals((auto.getCarCode()))
                ||"FAQ025".equals((auto.getCarCode()))
                ||"QEF025".equals((auto.getCarCode()))
                ||"QEF037AB".equals((auto.getCarCode()))
                ||"FAQ037AB".equals((auto.getCarCode()))
                ||"FAQ045".equals((auto.getCarCode()))
                ||"QEF045".equals((auto.getCarCode()))
                ||"NBEF028".equals((auto.getCarCode()))
                ||"OPCF028".equals((auto.getCarCode()))
                //20 more OR conditions
                )
        {
            filteredAutoList.add(auto);
        }
    }
    return filteredAutoList;
}

The following two approaches came to my mind:

Using HashSet

private List<AutoDto> getFilteredAutoList()
{
    List<AutoDto> autoList = getAutoListForCoverage();
    List<AutoDto> filteredAutoList = new ArrayList<AutoDto>();

    Set<String> carCodeSet = getCarCodeSet();

    for(AutoDto auto : autoList)
    {
        if(carCodeSet.contains(auto.getCarCode()))
        {
            filteredAutoList.add(auto);
        }
    }
    return filteredAutoList;
}

private Set<String> getCarCodeSet()
{
    Set<String> carCodeSet = new HashSet<String>();

    carCodeSet.add("FAQ025");
    carCodeSet.add("QEF025");
    carCodeSet.add("QEF037AB");
    carCodeSet.add("FAQ037AB");
    carCodeSet.add("FAQ045");
    carCodeSet.add("QEF045");
    carCodeSet.add("NBEF028");
    carCodeSet.add("OPCF028");
    //20 more codes to be added

    return carCodeSet;
}

Using String contains method

private List<AutoDto> getFilteredAutoList1()
{
    List<AutoDto> autoList = getAutoListForCoverage();
    List<AutoDto> filteredAutoList = new ArrayList<AutoDto>();

    String carCodeString = "FAQ025,QEF025,QEF037AB,FAQ037AB,FAQ045,QEF045,NBEF028,OPCF028";
    for(AutoDto auto : autoList)
    {
        if(carCodeString.contains(auto.getCarCode()))
        {
            filteredAutoList.add(auto);
        }
    }
    return filteredAutoList;
}

Which approach should I follow and why?


texts: Persist data by serializing/deserializing objects that are sent to it

texts:
I've created the following class to persist data by serializing/deserializing objects that are sent to it. I would like to know if there is a better way of writing this class, or if my class is fine the way it is.

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;

namespace Education_PersistingData
{
public class PersistData<T>
{
    private readonly T _obj;
    private readonly string _filePath;
    private readonly string _fileName;

    public PersistData(T obj, string filePath, string fileName)
    {
        this._obj = obj;
        this._filePath = filePath;
        this._fileName = fileName;
    }

    /// <summary>
    /// Serializes objects to a SOAP .xml format
    /// </summary>
    public void SerializeToSoapFormat()
    {
        try
        {
            SoapFormatter soapFormatter = new SoapFormatter();
            Stream dataStream = File.Create(_filePath + _fileName);
            soapFormatter.Serialize(dataStream, _obj);
            dataStream.Close();
        }
        catch (IOException ex)
        {
            throw new IOException(ex.Message);
        }
    }

    /// <summary>
    /// Serializes objects to a Binary .txt format
    /// </summary>
    public void SerializeToBinaryFormat()
    {
        try
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            Stream dataStream = File.Create(_filePath + _fileName);
            binaryFormatter.Serialize(dataStream, _obj);
            dataStream.Close();
        }
        catch (IOException ex)
        {
            throw new IOException(ex.Message);
        }
    }

    /// <summary>
    /// Deserializes a SOAP .xml file format
    /// </summary>
    /// <returns>Deserialized object</returns>
    public T DeserializeSoapFormat()
    {
        try
        {
            SoapFormatter soapFormatter = new SoapFormatter();
            Stream dataStream = File.OpenRead(_filePath + _fileName);
            T result = (T)soapFormatter.Deserialize(dataStream);
            dataStream.Close();
            return result;
        }
        catch (IOException ex)
        {
            throw new IOException(ex.Message);
        }
    }

    /// <summary>
    /// Deserializes a Binary .txt file format
    /// </summary>
    /// <returns>Deserialized object</returns>
    public T DeserializeBinaryFormat()
    {
        try
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            Stream dataStream = File.OpenRead(_filePath + _fileName);
            T result = (T)binaryFormatter.Deserialize(dataStream);
            dataStream.Close();
            return result;
        }
        catch (IOException ex)
        {
            throw new IOException(ex.Message);
        }
    }
}
}


texts: Collect maximum fruits in two baskets of at most 2 types of fruits

texts:
The task

is taken from LeetCode

  In a row of trees, the i-th tree produces fruit with type tree[i].
  You start at any tree of your choice, then repeatedly perform the
  following steps:

  Add one piece of fruit from this tree to your baskets.  If you cannot, stop.
  Move to the next tree to the right of the current tree.  If there is no tree to the right, stop.

  Note that you do not have any choice after the initial choice of
  starting tree: you must perform step 1, then step 2, then back to step
  1, then step 2, and so on until you stop.

  You have two baskets, and each basket can carry any quantity of fruit,
  but you want each basket to only carry one type of fruit each. What is
  the total amount of fruit you can collect with this procedure?

  Example 1:

Input: [1,2,1]
Output: 3
// Explanation: We can collect [1,2,1].

  Example 2:

Input: [0,1,2,2]
Output: 3
// Explanation: We can collect [1,2,2].
// If we started at the first tree, we would only collect [0, 1].

  Example 3:

Input: [1,2,3,2,2]
Output: 4
// Explanation: We can collect [2,3,2,2].
// If we started at the first tree, we would only collect [1, 2].

  Example 4:

Input: [3,3,3,1,2,1,1,2,3,3,4]
Output: 5
// Explanation: We can collect [1,2,1,1,2].
// If we started at the first tree or the eighth tree, we would only collect 4 fruits.

  Note:

  1 <= tree.length <= 40000
  0 <= tree[i] < tree.length

My solution:

has time and space complexity of \$O(n)\$. At first I thought it was easy. But then, I got confused with the one of the test cases (i.e. I = [3,3,3,1,2,1,1,2,3,3,4];) and everything inside the else-block is a bit hacky afterwards. Maybe there is a more elegant solution to that.

/**
 * @param {number[]} tree
 * @return {number}
 */
var totalFruit = function(tree) {
    const set = new Set(tree);
    if (set.size <= 2) {
        return tree.length;
    }

    const fruits = new Set();
    let i = 0;
    let j = 0;
    let max = 0;
    let count = 0;
    while (j < tree.length) {
        if (fruits.size <= 2 && !fruits.has(tree[j])) {
            fruits.add(tree[j]);
        }

        if (fruits.size <= 2) {
            count++;
            max = Math.max(max, count);
            j++;
        } else {
            fruits.delete(tree[i]);
            const lastIndex = tree.slice(i, j - 1).lastIndexOf(tree[i]);
            i += lastIndex + 1;
            count-= lastIndex + 1;
        }
    }
    return max;
};

let I = [1,2,1];
I = [0,1,2,2];
I = [3,3,3,1,2,1,1,2,3,3,4];
console.log(totalFruit(I));

Update: I made a mistake. This should be the accurate solution:

/**
 * @param {number[]} tree
 * @return {number}
 */
var totalFruit = function(tree) {
    let max = 0, count = 0;
    for (let i = 0, first = 0, second = -1; i < tree.length; i++) {
        count++;
        if (tree[i] === tree[first]) {
            first = i;
        } else if (second === -1 || tree[i] === tree[second]) {
            second = i;
        } else {
            max = Math.max(count - 1, max);
            count = Math.abs(first - second) + 1;
            first = i - 1;
            second = i;
        }
    }
    return Math.max(count, max);
};

Time complexity \$O(n)\$ and space complexity \$O(1)\$


texts: What to do with the Exception when you fail to close() a resource?

texts:
I am happy to receive all recommendations for improvement.  But below I am mostly interested in a review of my handling of the exception thrown by the close() method of RandomAccessFile.

The FileNotFoundException thrown by the opening of a file (in the constructor of RandomAccessFile) is declared as thrown by my method, because the caller can act on it.

But the exception thrown by the close() method on that file cannot be handled the caller, so I repackage it in a RuntimeException.

private boolean includeArticle(File articleFile, Map<String, String> conditionMap)
  throws FileNotFoundException
{
  if (doesFileQualifyAsArticle(articleFile)) {
    /* This can throw a FileNotFoundException, which the caller should know about. */
    RandomAccessFile raFile = new RandomAccessFile(articleFile, "r");
    if (this.isToInclude(raFile, conditionMap)) {
      return true;
    }
    try {
      raFile.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  return false;
}


texts:
I am building a website that uses Amazon S3 to host its image (and other) files.

I require that images displayed on the website look like they come from my site and not from Amazon (so we are talking on the request/response level).  What I have done is created a controller which all these files will pass through.  The controller should request the file from Amazon and pass it on, as if it's from the local website.

My concern is my usage of the response stream and error-handling.  Basically, if anything happens, I want it to simply return a 404.

public class RequestState
{
    public RequestState()
    {
        BufferSize = 1024;
        BufferRead = new byte[BufferSize];
        Request = null;
        ResponseStream = null;
    }

    public int BufferSize { get; private set; }
    public byte[] BufferRead { get; set; }
    public HttpWebRequest Request { get; set; }
    public HttpWebResponse Response { get; set; }
    public Stream ResponseStream { get; set; }
}

public class MediaController : AsyncController
{
    public void IndexAsync(string key)
    {
        if (string.IsNullOrWhiteSpace(key))
            throw new HttpException((int)HttpStatusCode.NotFound, "File not found.");

        AsyncManager.OutstandingOperations.Increment();

        var request = (HttpWebRequest)WebRequest.Create(string.Format(Constants.Urls.AmazonFileGetUrlFormat, AppSettings.AmazonS3BucketName, key));
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";

        var state = new RequestState { Request = request };

        request.BeginGetResponse(ResponseCallback, state);
    }

    private void ResponseCallback(IAsyncResult result)
    {
        try
        {
            var state = (RequestState)result.AsyncState;
            HttpWebRequest request = state.Request;

            state.Response = (HttpWebResponse)request.EndGetResponse(result);
            Stream responseStream = state.Response.GetResponseStream();
            state.ResponseStream = responseStream;

            AsyncManager.Parameters["imageInBytes"] = ReadFully(responseStream);
            AsyncManager.Parameters["contentType"] = state.Response.ContentType;
        }
        catch (WebException ex)
        {
            var state = (RequestState)result.AsyncState;

            if (state.Response != null)
                state.Response.Close();

            AsyncManager.Parameters["webException"] = ex;
        }
        catch (Exception ex)
        {
            var state = (RequestState)result.AsyncState;

            if (state.Response != null)
                state.Response.Close();

            throw;
        }
        finally
        {
            AsyncManager.Parameters["key"] = "key";
            AsyncManager.OutstandingOperations.Decrement();
        }
    }

    public static byte[] ReadFully(Stream input)
    {
        var buffer = new byte[16 * 1024];

        using (var stream = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                stream.Write(buffer, 0, read);
            }
            return stream.ToArray();
        }
    }

    [OutputCache(Duration = 600, VaryByParam = "key")]
    public FileContentResult IndexCompleted(string key, byte[] imageInBytes, string contentType, WebException webException)
    {
        if (webException != null && webException.Status == WebExceptionStatus.ProtocolError)
        {
            var response = webException.Response as HttpWebResponse;

            if (response != null)
            {
                throw new HttpException((int)response.StatusCode, response.StatusDescription);
            }

            throw new HttpException((int)HttpStatusCode.NotFound, "File not found.");
        }

        if (imageInBytes == null || imageInBytes.Length == 0)
        {
            throw new HttpException((int)HttpStatusCode.NotFound, "File not found.");
        }

        return File(imageInBytes, contentType);
    }
}


texts: How do I divide Dao and Dao-Cache into different modules?

texts:
I want to improve performance for api. I design cache in dao layer. I use caffine cache. Basic code is:
CacheConfig.java
@Configuration
public class CacheConfig {

    @Autowired
    private AppDao appDao;

    @Bean(value = "appCache")
    public LoadingCache<String, App> appCache() {
        return Caffeine.newBuilder()
                .maximumSize(1000)
                .refreshAfterWrite(5, TimeUnit.MINUTES)
                .build(key -> appDao.getByKeyFromDB(key));
    }
}

AppDao.java
@Repository
public class AppDao {

    @Autowired
    @Qualifier(value = "appCache")
    private LoadingCache<String, App> appCache;

    @Autowired
    private AppMapper appMapper;

    // service call getByAppKey
    public App getByKey(String appKey) {
        App app = appCache.get(appKey);
        return app;
    }

    // appCache load data by getByKey
    public App getByKeyFromDB(String appKey) {
        LambdaQueryWrapper<App> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(App::getAppKey, appKey);
        return appMapper.selectOne(queryWrapper);
    }
}

I maybe divide getByKey and getByKeyFromDB to two file, but I have no idea.
How do I divide getByKey and getByKeyFromDB to different modules?


texts: Swapping two elements of a singly-linked list

texts:
Similarly to Learning Rust With Entirely Too Many Linked Lists, I'm trying to learn Rust by working with linked lists. Currently I'm trying to implement a function bubble(...) that takes 2 elements of a singly-linked list and swaps them.

Any feedback is greatly appreciated! (Rust playground link here.)

#![allow(dead_code)]

use ::std::mem::replace;
use ::std::mem::swap;

#[derive(Debug)]
pub struct List<T> {
    list: Node<T>,
}

type Node<T> = Option<Box<Link<T>>>;

#[derive(Debug)]
struct Link<T> {
  head: T,
  tail: Node<T>,
}

impl<T> List<T> {
  pub fn push(&mut self, elem: T) {
    self.list = Some(Box::new(
      Link{ head: elem, tail: replace(&mut self.list, None) }));
  }

  pub fn pop(&mut self) -> Option<T> {
    match replace(&mut self.list, None) {
      Some(next_box) => {
        let next = *next_box;
        self.list = next.tail;
        Some(next.head)
      }
      _ => None
    }
  }

  // First attempt: Use push+pop. Not perfect, as we move the values
  // in and out, and if they're larger, we waste resources.
  pub fn bubble(&mut self) -> bool {
    if let Some(first) = self.pop() {
      if let Some(second) = self.pop() {
        self.push(first);
        self.push(second);
        return true;
      } else {
        self.push(first);
      }
    }
    false
  }

  // Learning from the above attempt, I created another push+pop
  // functions that don't move values, just Boxes instead.

  // Any tail of 'singleton' is silently discarded.
  fn push_singleton(&mut self, mut singleton: Box<Link<T>>) {
    swap(&mut self.list, &mut singleton.tail);
    self.list = Some(singleton);
  }

  fn pop_singleton(&mut self) -> Node<T> {
    match replace(&mut self.list, None) {
      Some(mut next_box) => {
        swap(&mut self.list, &mut next_box.tail);
        Some(next_box)
      }
      _ => None
    }
  }

  // Otherwise the implementation is very similar to 'bubble' above.
  pub fn bubble2(&mut self) -> bool {
    if let Some(first_box) = self.pop_singleton() {
      if let Some(second_box) = self.pop_singleton() {
        self.push_singleton(first_box);
        self.push_singleton(second_box);
        return true;
      } else {
        self.push_singleton(first_box);
      }
    }
    false
  }

  // Third attempt: Directly unpack the first two nodes and combine them
  // back together.
  pub fn bubble3(&mut self) -> bool {
    if let Some(mut first_box) = replace(&mut self.list, None) {
      if let Some(mut second_box) = replace(&mut first_box.tail, None) {
        first_box.tail = replace(&mut second_box.tail, None);
        second_box.tail = Some(first_box);
        *self = List{ list: Some(second_box) };
        return true;
      } else {
        *self = List{ list: Some(first_box) };
      }
    }
    false
  }
}

fn main() {}


texts:
With some advice from SO, I developed this system, which I think is quite strong for bots to automatically post comments.

index.php

 <form name="f" action="poster.php" method="post">
  <input type="text" name="text"/>

  <input type="text" name="key" id="key" value=""/>

  <input type="submit">
 </form>

getToken.php

<?php
 $key=date("Y-m-d H:i:s");
 $hash=sha1($key.'mySecretKey');
 echo $key.'#'.$hash;
?>

poster.php

<?php
if (!isset($_POST['key']))
 exit;

$parts = explode('#',$_POST['key'],2);
$key = $parts[0];
$hash = $parts[1];

$date1 = $key;
$date2 = date("Y-m-d H:i:s");
$diff = abs(strtotime($date2) - strtotime($date1));
$years   = floor($diff / (365*60*60*24));
$months  = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days    = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$hours   = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
$minuts  = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60);
$seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60));

if ($seconds < 5)
 echo $seconds.' Too fast, must be a naughty bot
';
else if ($seconds>5 && $seconds < 600)
 echo $seconds.' In time
';
else
 echo $seconds.' time out
';

if ($hash == (sha1($key.'sou')))
 echo $_POST['text'];
else
 echo 'You are a bot !';
?>


texts: LeetCode heater binary search solution (w recursion) optimisation

texts:
I was doing LeetCode heater problem.
Question: https://leetcode.com/problems/heaters/

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.
Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.
So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Example Input
Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

The solution I wrote is accepted by leetcode but it isn't optimal

Runtime: 656 ms, faster than 39.02% of JavaScript online submissions
for Heaters. Memory Usage: 48.2 MB, less than 12.20% of JavaScript
online submissions for Heaters.

My solution with comments
function findClosest (house, heaters) {
// if only one heater in array of heaters, subtract it with house number to get the difference and return it
if (heaters.length === 1) return Math.abs(house - heaters[0])
  const middleIndex =  Math.floor((heaters.length - 1)/2)
  // if middle heater is equal to house, heater exist on that house number, difference would be zero
  if (house === heaters[middleIndex]) return 0
  // heater on the leftside and rightside of the middle Heater, if leftside and rightside does not contain any elements (undefinned) then middle would be the left and right most element
  const left = heaters[middleIndex - 1] || heaters[middleIndex]
  const right = heaters[middleIndex + 1] || heaters[middleIndex]
  // if the left side heater location is greater than current house location, we need to move to left
  if (left > house) {
   return findClosest(house, heaters.slice(0, middleIndex+1))
  }
    // if the right side heater is less than current house, we need to move to right
  if (house>right) {
    return findClosest(house, heaters.slice(middleIndex + 1, heaters.length))
  }
 // finding diff b/w left, right and middle index and returning the ones with lease distance
  const middleDiff = Math.abs(house-heaters[middleIndex])
  const leftDiff = house - left
  const rightDiff = right - house
  return Math.min(middleDiff, leftDiff, rightDiff)
}

function findRadius  (houses, heater) {
  let maxIndex = 0
  houses.sort((a,b) => a-b)
  heater.sort((a,b) => a-b)
  for (let i=0; i<houses.length; i++) {
    const currentIndex = findClosest(houses[i], heater)
    if (currentIndex > maxIndex) maxIndex = currentIndex // if the current returned distance is the highest, set that as maxIndex
  }
  return maxIndex
}

Can someone help me in optimising it?


texts: Validate if either or both of two fields has been provided, as a ValidationAttribute

texts:
I have a binding model where at least one of two fields must be specified. I can't just set them both as [Required]. Here is what I came up with:

using System;
using System.ComponentModel.DataAnnotations;

namespace MyApp.Utils.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    public class EitherRequiredAttribute : ValidationAttribute
    {
        private readonly string _field1;
        private readonly string _field2;

        public EitherRequiredAttribute(string field1, string field2) => (_field1, _field2) = (field1, field2);

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var property1 = validationContext.ObjectType.GetProperty(_field1);
            if (property1 == null)
                return new ValidationResult(string.Format("Unknown property: {0}", _field1), new[] { _field1 });
            var property2 = validationContext.ObjectType.GetProperty(_field2);
            if (property2 == null)
                return new ValidationResult(string.Format("Unknown property: {0}", _field2), new[] { _field2 });

            var value1 = property1.GetValue(validationContext.ObjectInstance);

            if (value1 != null)
                return ValidationResult.Success;

            var value2 = property2.GetValue(validationContext.ObjectInstance);

            if (value2 != null)
                return ValidationResult.Success;

            return new ValidationResult(string.Format("Either or both of \"{0}\" and \"{1}\" are required", _field1, _field2), new[] { _field1, _field2 });
        }
    }
}

Use case:

[EitherRequired("A", "B")]
public class SomeModel
{
    public int? A {get; set;}
    public int? B {get; set;}
}


texts:
About

I'm trying to implement a simple virtual machine. Now it supports only three operations:

ADD(reg0, reg1, reg2) -> reg0 = reg1 + reg2
LOAD(reg, value) -> reg = value
EXIT -> finish process

It has 8 registers and no memory (for now).

Source code

main.rs:

use std::process;

mod opcodes;
mod utils;

const REGISTERS_COUNT: usize = 8;

#[derive(Copy, Clone)]
struct Program<'a> {
    code: &'a Vec<u8>,
    pos: usize
}

impl<'a> Program<'a> {
    pub fn new(code: &'a Vec<u8>) -> Program<'a> {
        Program { code: code, pos: 0 }
    }

    pub fn fetch(&mut self) -> u8 {
        self.pos += 1;
        if self.pos > self.code.len() {
            process::exit(0);
        }
        return self.code[self.pos - 1];
    }
}

fn eval(mut program: Program, mut registers: [u64; REGISTERS_COUNT]) {
    loop {
        let operator = program.fetch();
        let operands = (
            program.fetch(),

            vec![
                program.fetch(), program.fetch(),
                program.fetch(), program.fetch(),
                program.fetch(), program.fetch(),
                program.fetch(), program.fetch()
            ]
        );

        match operator {
            opcodes::EXIT => {
                process::exit(0);
            }
            opcodes::LOAD => {
                registers[operands.0 as usize] = utils::concat_bytes(&operands.1);
            }
            opcodes::ADD => {
                registers[operands.0 as usize] = registers[utils::concat_bytes(&operands.1[..4]) as usize]
                    + registers[utils::concat_bytes(&operands.1[4..]) as usize];
            }
            _ => {
                println!("error: invalid instruction code");
                process::exit(1);
            }
        }

        println!("{:?}", registers);
    }
}

fn main() {
    let registers: [u64; REGISTERS_COUNT] = [0; REGISTERS_COUNT];
    let code = vec![
        opcodes::LOAD,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64,
        opcodes::LOAD,
            0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC8,
        opcodes::ADD,
            0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
        opcodes::EXIT,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    ];
    let program = Program::new(&code);

    eval(program, registers);
}

utils.rs:

pub fn concat_bytes(bytes: &[u8]) -> u64 {
    let mut result = bytes[0] as u64;
    for i in 1..bytes.len() {
        result = (result << 8) | (bytes[i] as u64)
    }
    return result;
}

opcodes.rs:

pub const EXIT: u8 = 0x00;
pub const LOAD: u8 = 0x01;
pub const ADD:  u8 = 0x02;

Output

[100, 0, 0, 0, 0, 0, 0, 0]
[100, 200, 0, 0, 0, 0, 0, 0]
[100, 200, 300, 0, 0, 0, 0, 0]

Disadvantages:

No memory
Only integers
All operators require the same number of arguments (even if they don't need any, like EXIT)

Anything else?


texts:
I've tried this problem on Codeforces.  Given a set of string patterns, all of which are the same length, and which consist of literal lowercase ASCII characters and ? wildcards, find a pattern that satisfies them all.

I want to optimize and simplify it further and make it a more elegant solution, if possible.

import sys

def main():
    n = int(sys.stdin.readline())
    t = sys.stdin.readlines()
    l = len(t[0])
    result = ''
    if n==1:
        result = t[0].replace('?', 'x')
    else:
        for y in range(0,l-1):
            let = t[0][y]
            for x in range(1,n):
                if let == '?' and t[x][y]!= '?':
                    let = t[x][y]
                if t[x][y] != let and t[x][y] != '?':
                    result += '?'
                    break
                elif x == n-1:
                    if let == '?':
                        result += 'x'
                    else:
                        result += let
    print result

main()


texts: Compile-time-fixed templated integer range

texts:
This is a follow-up of an old question by @LokiAstari, modified for the current community challenge. The idea is to provide a compile-time integer range. I applied all the modifications that I proposed to Loki at the time and tried to write a class as close as possible to the standard library class std::integer_sequence:

This is a [begin, end) range instead of a [begin, end] one.
The range can be ascending or descending.
The class is templated so that it is possible to choose the integer type to use.
In order to match the standard library utilities, I also provide the template index_range which is an alias of integer_range for the type std::size_t.

Here is the implementation:

#include <cstddef>
#include <tuple>
#include <type_traits>
#include <utility>

namespace details
{
    ////////////////////////////////////////////////////////////
    // implementation details

    template<typename Int, typename, Int Begin>
    struct increasing_integer_range;

    template<typename Int, Int... N, Int Begin>
    struct increasing_integer_range<Int, std::integer_sequence<Int, N...>, Begin>:
        std::integer_sequence<Int, N+Begin...>
    {};

    template<typename Int, typename, Int Begin>
    struct decreasing_integer_range;

    template<typename Int, Int... N, Int Begin>
    struct decreasing_integer_range<Int, std::integer_sequence<Int, N...>, Begin>:
        std::integer_sequence<Int, Begin-N...>
    {};
}

////////////////////////////////////////////////////////////
// integer_range

template<typename Int, Int Begin, Int End,
         bool Increasing=(Begin<End)>
struct integer_range;

template<typename Int, Int Begin, Int End>
struct integer_range<Int, Begin, End, true>:
    details::increasing_integer_range<
        Int,
        std::make_integer_sequence<Int, End-Begin>,
        Begin>
{};

template<typename Int, Int Begin, Int End>
struct integer_range<Int, Begin, End, false>:
    details::decreasing_integer_range<
        Int,
        std::make_integer_sequence<Int, Begin-End>,
        Begin>
{};

template<std::size_t Begin, std::size_t End>
using index_range = integer_range<std::size_t, Begin, End>;

I don't ask for a specific kind of review. If you see anything that can be improved, do not hesitate.

And as a bonus, take this test cases. Since integer_range uses some heavy template wizardry, I had troubles coming with decent test cases that are easy enough to read, write and understand. They are not really beautiful, but they work as expected; that may help you if you want to try modifications:

template<std::size_t N>
void test(std::integer_sequence<int>)
{
    static_assert(N == 0, "");
}

template<std::size_t N>
void test(std::integer_sequence<int, 0, 1, 2, 3, 4>)
{
    static_assert(N == 1, "");
}

template<std::size_t N>
void test(std::integer_sequence<int, 5, 4, 3, 2, 1>)
{
    static_assert(N == 2, "");
}

template<std::size_t N>
void test(std::integer_sequence<int, -3, -2, -1, 0, 1>)
{
    static_assert(N == 3, "");
}

template<std::size_t N>
void test(std::integer_sequence<int, -1, -2, -3>)
{
    static_assert(N == 4, "");
}

template<std::size_t N>
void test(std::integer_sequence<int, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7>)
{
    static_assert(N == 5, "");
}

int main()
{
    using namespace polder;

    test<0>(integer_range<int, 8, 8>());
    test<1>(integer_range<int, 0, 5>());
    test<2>(integer_range<int, 5, 0>());
    test<3>(integer_range<int, -3, 2>());
    test<4>(integer_range<int, -1, -4>());
    test<5>(integer_range<int, 3, -8>());
}

Note: if you're interested, I wrote a follow-up to this question which incorporates most of the suggestions from the accepted answer and adds the possibility to specify a Step parameter.


texts: Sorting entities by Z in every call to Draw

texts:
My implementation contains a SpriteComponent class which has a Z property; I use this to determine the order in which to draw my entities (higher Z = drawn on top). It's a simple integer.

What I'm worrying about (premature optimization, I suspect) is the runtime complexity of the function which gets the list of all the SpriteComponents to draw, in order of their Z attribute:

List<IEntity> entitiesToDraw = currentScreen.Entities
    .Where(e => e.HasComponent<SpriteComponent>())
    .OrderBy(e => e.GetComponent<SpriteComponent>().Z)
    .ToList();

From what I've read, OrderBy uses QuickSort, which is \$O(n log n)\$, but I'm not sure about Where.

I can reasonably assume:

1000+ entities can concurrently exist
90% or more of entities have a SpriteComponent in them
Changing the Z of a sprite happens fairly infrequently for most sprites

My questions are:

Should I be worrying about this call at all?
If so, how can I reduce the runtime complexity, and/or cache the results reliably?


texts:
Is there a way to collapse multiple_get into as few lines as possible?

def single_get(target):
    return [some list of objects] # might be an empty list

def multiple_get(targets):
    result = []
    for target in targets:
        result.extend(single_get(target))
    return result


texts: Calculating multiple car prices from a file - follow-up

texts:
My application needs to read a file, which includes a list of cars from different factories, and calculate the prices (by this I mean mean add up their prices).

I suppose my solution is efficient.  Is there any better approach to it?

 String factories = "Benz,10000,BMW,3000,Benz,5,Toyota,500,BMW,50000,RR,100000,BMW,100000,Jaguar,100000,Benz,4,Next,100,Benz,3,Benz,2,Benz,1,Toyota,100000,Polo,10,Gall,1000";
        String[] fac = factories.split(",");
        List<Company> trn = new ArrayList();
        for(int i=0;i<fac.length-1;i=i+2){
            trn.add(new Company(fac[i],fac[i+1]));
        }
        Map<String, BigDecimal> map = new HashMap();

        BigDecimal counter = new BigDecimal("0");
        BigDecimal target = new BigDecimal("10000");
        for (Company c : trn) {
            String name = c.getName();
            if (!map.containsKey(name)) {
                counter = new BigDecimal("0");
                for (Company com : trn) {
                    if (com.getName().equalsIgnoreCase(name)) {
                        counter = counter.add(com.getPrice());
                        if ((counter.compareTo(target)) == 1) {
                            map.put(name, counter);
                        }

                    }
                }

            }
        }
        Set<String> set = map.keySet();
        System.err.println(">>" + set.toString());

Output

[RR, Toyota, BMW, Jaguar, Benz]


texts: Test whether the edit-distance of two strings is at most 1

texts:
There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character.

EXAMPLES:

pale, ple returns true

pales, pale returns true

pale, bale returns true

pale, bake returns false

My solutions seems to work for any case I could think of (like ("", "s") but I feel like I'm checking conditions too much in it (mainly my final if/else statement had to be tacked on when I saw my solution wouldn't work for ("pales", "pale"))

bool oneAway(string s1, string s2)
{
    //loop through smaller string size
    decltype(s1.size()) size = (s1.size() < s2.size()) ? s1.size() : s2.size();

    for (decltype(s1.size()) i = 0; i < size; ++i)
    {
        if (s1[i] != s2[i])
        {
            string temp1 = s1.substr(i + 1);
            string temp2 = s2.substr(i + 1);

            //if rest of the string is equal we do 1 replacement.
            if (temp1 == temp2)
            {
                s1[i] = s2[i];
                break;
            }

            //otherwise we will try to insert or remove a character
            else
            {
                if (s1.size() < s2.size())
                {
                    s1.insert(i, 1, s2[i]);
                    break;
                }
                else
                {
                    s1.erase(i, 1);
                    break;
                }
            }
        }
    }

    //check equality
    if (s1 == s2)
        return true;

    //otherwise try to erase last character in s1 and check again (since for loop may not check this character if s2 was smaller string size)
    else
    {
        s1.erase(s1.size() - 1, 1);
        if (s1 == s2)
            return true;
    }
    return false;

}

This question is from the book "Cracking the Code Interview" by Gayle McDowell.


texts: Logging class in Qt library for foreign language calls

texts:
I have a small C++/Qt library that interfaces with an application in another language (so interfacing must be performed using primitives, notably pointers to Handler objects). To implement debug logging, each Handler has its own debug file, managed by a Log object. These are both constructed in the initializeHandler function.

To make use of RAII, I didn't want Log objects to have a default constructor - they have a copy-constructor, and a constructor that takes a QString to open a QFile with. If the Log can't open the file, I want the initializeHandler function to fail, so I made it throw a LogExceptFailedOpen exception. To interact with the application using my library, I have to catch that exception and re-interpret it as a returned error code (I can't just let the exception propogate - the calling application can't catch it). But I want to use the Log object if construction succeeds. Which leads me to my problem.

If I declare and initialize the Log in the try block, I can't access it after the catch block. I can get around this by using a QSharedPointer<Log> with a scope larger than the try block, then using the Log copy-constructor to create another Log object afterwards (or I could just use the Log stored in logPtr, but that's not the point). However, this feels like a hack, and I feel that the code structure could instead be reworked somehow.

There's some discussion here around someone with a similar problem, which suggests that I should either

do all my work within the try block, or
abandon RAII for Log objects.

Neither option appeals to me very much. RAII is important for Log objects, as they get passed around and copied a lot and it would be a major hassle to look for all the places where they could go out of scope.

How can I improve my code to avoid this problem?

initializeHandler function:

typedef int ErrorCode;
#define ERROR_FILE_FAILED_OPEN   -12
#define ERROR_INVALID_ARGS       -1
#define ERROR_OK                 0

ErrorCode initializeHandler(Handler*& handler, const char * logFile, int x, int y)
{
    QSharedPointer<Log> logPtr;
    try {
        logPtr.reset(new Log(QString(logFile)));
    } catch (const LogExceptFailedOpen& e) {
        return ERROR_FILE_FAILED_OPEN;
    }
    Log logger(*logPtr);

    logger.log("Log started.");
    logger.log("Initializing handler...");

    Handler* temp;
    try {
        temp = new Handler(logger, x, y);
    } catch (const HandlerExceptInvalidArgs& e) {
        logger.log("Arguments invalid. x = " + QString::number(x)
                   + ", y = " + QString::number(y));
        return ERROR_INVALID_ARGS;
    }
    handler = temp;

    logger.log("Successfully initialized handler.");

    return ERROR_OK;
}

Log class:

class Log
{
private:
    QSharedPointer<QFile> file;
    QSharedPointer<QTextStream> stream;
public:
    void log(const QString& message)
    {
        (*stream) << (message + "\r\n");
    }

    // file constructor
    Log(const QString& fileName) : file(fileName)
    {
        if (!file->open(QFile::WriteOnly)) {
            throw LogExceptFailedOpen();
        }
        stream = QSharedPointer<QTextStream>(new QTextStream(file.data()));
    }

    // copy-constructor
    Log(const Log& other) : file(other.file), stream(other.stream) {}

}


texts:
The code below works. The timings are as close as I can get to the system not packing out.

Basically telnet to a server to play tic-tac-toe. Automated it. Bottom left is 1, middle left is 2, middle right is 3 etc

Once a game is finished, I say "yes" and go again.

Anyway I can optimise it?

#!/usr/bin/env python
from telnetlib import Telnet
import sys
from pprint import pprint
from random import randint

HOST = '127.0.0.1'
PORT = 6666

tn = Telnet(HOST, PORT)
board=['','','','','','','','','']
winLines = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]

def main():
   startup()
   while True:
      readBoard()
      selectMove()

   tn.close()

def startup():

   print tn.read_until("WordsWeNeverSee",0.1)
   tn.write("O\n")
   print tn.read_until("go first.", 0.1)

def foobar():

   tn.write("yes\n")
   print tn.read_until("WordsWeNeverSee",0.1)
   tn.write("O\n")
   readBoard()

def readBoard():
   tIn = tn.read_until("WordsWeNeverSee",0.3)

   tLines = tIn.split('\n')
   sys.stdout.write(tIn)
   tLines = tLines[::-1]
   if len(tLines)==13:
       row = tLines[3].replace(' ', '').split('|')
       #X|X|O
       board[0] = row[0]
       board[1] = row[1]
       board[2] = row[2]

       row = tLines[7].replace(' ', '').split('|')
       #X|X|O
       board[3] = row[0]
       board[4] = row[1]
       board[5] = row[2]

       row = tLines[11].replace(' ', '').split('|')
       #X|X|O
       board[6] = row[0]
       board[7] = row[1]
       board[8] = row[2]
   elif len(tLines)==14:
       row = tLines[3].replace(' ', '').split('|')
       #X|X|O
       board[0] = row[0]
       board[1] = row[1]
       board[2] = row[2]

       row = tLines[7].replace(' ', '').split('|')
       #X|X|O
       board[3] = row[0]
       board[4] = row[1]
       board[5] = row[2]

       row = tLines[11].replace(' ', '').split('|')
       #X|X|O
       board[6] = row[0]
       board[7] = row[1]
       board[8] = row[2]
   else:
      readBoard()

   if tIn.find("play again") != -1:
      foobar()

def countCharInCells(char, tup): # X, [2,4,6]
   count = 0
   for n in tup:
      if board[n] == char:
         count += 1

   return count

def findEmpty(tup): # [2,4,6]
   for n in tup:
      if board[n] == '':
         return n

   return -1

def selectMove():

   xCount = board.count('X')

   # Strong first turn move
   if xCount == 0:
      tn.write('9')
      return

   # Best response to center start
   if board.count('X') == 1:
      if board[4] == 'X':
         tn.write('9')
         return

   # See if we can win
   for wl in winLines: #[[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]
      if countCharInCells('O', wl) == 2:
         choice = findEmpty(wl)
         if choice != -1:
            tn.write(str(choice+1))
            return

   # Try to block opposition winning moves
   for wl in winLines:
      if countCharInCells('X', wl) == 2:
         choice = findEmpty(wl)
         if choice != -1:
            tn.write(str(choice+1))
            return

   # Try to snag a corner
   choice = findEmpty([0,2,6,8])
   if choice != -1:
      tn.write(str(choice+1))
      return

   # Pick a random valid square when stumped
   while True:
      choice = randint(0,8)
      if board[choice] == '':
         tn.write(str(choice+1))
         return

if __name__ == "__main__":
    main()
    main()


texts:
I wanted to know how I can improve it. I mainly want to look at speed and performance, but if there are any improvements please give a suggestion.

<?php
defined("SECURE") or exit('Please define SECURE keyword to continue.');
class template
{
    private $templateParams;

    public function __construct()
    {
        $templateParams = array();
    }

    public function loadTemplate($configClass)
    {
        $this->organiseParams($configClass);
        $this->displayContent($configClass);
    }

    private function organiseParams($configClass)
    {
        $values = $configClass->getAll();

        while(list($title, $value) = each($values))
            $this->addParameter('[config ' . $title . ']', $value);
    }

    private function displayContent($configClass)
    {
        if (strlen($_GET['page']) >= 1)
        {
            ob_start();

            if (file_exists(ROOT . $configClass->getConfig("style.folder") . '/' . $configClass->getConfig("style.name") . '/' . $_GET['page'] . '/public_html/content.php'))
                include ROOT . $configClass->getConfig("style.folder") . '/' . $configClass->getConfig("style.name") . '/' . $_GET['page'] . '/public_html/content.php';
            else
                include ROOT . $configClass->getConfig("style.folder") . '/' . $configClass->getConfig("style.name") . '/error/public_html/content.php';

            $htmlOutput = ob_get_contents();
            ob_end_clean();

            while (list($paramTitle, $paramValue) = each($this->templateParams)) {
                $htmlOutput = str_replace($paramTitle, $paramValue, $htmlOutput);
            }

            echo $htmlOutput;
        }
        else
        {
            header("location: " . $configClass->getConfig("website.url") . "/index");
        }
    }

    private function addParameter($title, $value)
    {
        $this->templateParams[$title] = $value;
    }
}
?>


texts: Check array contains element at compile time

texts:
We have a modifyCoefficient(const char* name, int value) function that updates the value of a coefficient in a container. The names are known at compile time, they are read from an XML file in a pre-build step and stored in an array.
Usage: data.modifyCoefficient("ADAPTIVE", 1);
Compiler: MSVC 2017 v15.8

I would like to get a compile time error when the coefficient name does not exist.
With the following code that happens, but is there a way to do it without a macro?

#include <array>

#define COEFF(name) returnName<coefficientExists(name)>(name)

constexpr std::array<const char*, 3> COEFFICIENTS = { "VERSION", "CHANNELS", "ADAPTIVE" };

constexpr bool coefficientExists(const char* name)
{
    for (auto coefficientIndex = 0U; coefficientIndex < COEFFICIENTS.size(); ++coefficientIndex)
    {
        if (COEFFICIENTS[coefficientIndex] == name)
            return true;
    }
    return false;
}

template<bool CoefficientTest>
constexpr const char* returnName(const char* name)
{
    static_assert(CoefficientTest, "coefficient does not exist");
    return name;
}

int main()
{
    static_assert(coefficientExists("VERSION"), "should exist");
    static_assert(coefficientExists("TEST") == false, "should not exist");
    static_assert(COEFF("ADAPTIVE") == "ADAPTIVE", "should return name");
    COEFF("CHANNELS");
    // data.modifyCoefficient(COEFF("ADAPTIVE"), 1);
    return 0;
}

https://godbolt.org/z/kpGcMS


texts:
I'm looking into Administration Elevation and I've come up with a solution that seems like it's perfectly sane, but I'm still in the dark about the professional methods to accomplish this.

Is there a better way to do this or is this fine?

using System;
using System.Diagnostics;
using System.Security.Principal;
using System.Windows.Forms;

namespace MyVendor.Installation
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (!IsRunAsAdmin())
            {
                Elevate();
                Application.Exit();
            }
            else
            {
                try
                {
                    Installer InstallerForm = new Installer();
                    Application.Run(InstallerForm);
                }
                catch (Exception e)
                {
                    //Display Exception message!

                    Logging.Log.Error("Unrecoverable exception:", e);
                    Application.Exit();
                }
            }
        }

        internal static bool IsRunAsAdmin()
        {
            var Principle = new WindowsPrincipal(WindowsIdentity.GetCurrent());
            return Principle.IsInRole(WindowsBuiltInRole.Administrator);
        }

        private static bool Elevate()
        {
            var SelfProc = new ProcessStartInfo
                {
                    UseShellExecute = true,
                    WorkingDirectory = Environment.CurrentDirectory,
                    FileName = Application.ExecutablePath,
                    Verb = "runas"
                };
            try
            {
                Process.Start(SelfProc);
                return true;
            }
            catch
            {
                Logging.Log.Error("Unable to elevate!");
                return false;
            }
        }
    }
}


texts:
let generatorButton = document.getElementById("generator");

generatorButton.addEventListener("click", () => {
    let passwordLength = 16;
    let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_";
    let password = "";

    for (i = 0;i < passwordLength;i++){
        password = password + characters.charAt(Math.floor(Math.random() * Math.floor(characters.length - 1)));
    }

    document.getElementById("textField").value = password;
});
:root {
    --gray: #CBC4C4;
    --blue: #029DF1;
    --white: #FFF;
}

* {
    font-family: Roboto, sas-serif;
    margin: 0;
    padding: 0;
    margin-top: 15px;
}

body {
    background: var(--blue);
}

.container {
    width: 300px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: var(--gray);
    font-size: large;
    border-radius: 30px;
}

button {
    background: var(--blue);
    color: var(--white);
    padding: 20px 20px;
    margin: 10px 5px;
    font-size: large;
    cursor: pointer;
}

button:focus {
    border: 2px solid var(--blue);
    outline: none;
}

input {
    font-size: large;
    border: 3px solid var(--blue);
    outline: none;
    margin-bottom: 15px;
}

input::placeholder {
    opacity: 0.6;
}
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Password Generator</title>

Password Generator

        <button id="generator">Generate!</button>
        <input type="text" id="textField" placeholder="Your password goes here...">

I could add a few things onto this, like having a way to copy onto the clipboard and such. But really what I want to know is, how can I make this code shorter and more efficient? Specifically, my CSS is long. Maybe I should start using a CSS framework? Let me know.


texts: Is this a good way of managing parallel go routines when I care about ordering of results?

texts:
I have a process with a number of stages that need to be completed in sequence. Each stage is largely parallelisable, involving looping over a large data structure and processing each item independently, and collating the results into the data structure used by the next stage.

My approach is like the following:

var wg sync.WaitGroup
var control_routine sync.WaitGroup
stage_complete = make(chan bool)
stage_one_channel := make(chan map[typeFoo][]typeBar, 16)
stage_two_channel := make(chan map[typeBaz][]typeQux, 16)
stage_one_results := make(map[typeFoo][]typeBar)
stage_two_results := make(map[typeBaz][]typeQux)

// A routine to receive results as they arrive from each stage
go func() {
    for  {
        select {
        case new_stage_one_results := <- stage_one_channel:
            // merge new_stage_one_results into stage_one_results...
        case new_stage_two_results := <- stage_two_channel:
            // merge new_stage_two_results into stage_two_results...
        ...
        case stay_alive := <-stage_complete:
            control_routine.Done()
            if !stay_alive {
                return
            }
        }
    }
}()

// Begin stage One
control_routine.Add(1)
for i, some_data := range my_data {
    wg.Add(1)
    go func(i, datum){
        defer wg.Done()
        some_stage_one_results = make(map[typeFoo][]typeBar)
        // do some heavy lifting with some_data which populates some_stage_one_results...
        stage_one_channel <- some_stage_one_results
    }()
}
wg.Wait()
stage_complete <- true
control_routine.Wait()
// End stage one

// More stages much like the first...

// Finally send the control routine a terminal signal and wait for it to finish
stage_complete <- false
control_routine.Wait()

This basically seems to work, but I need to be sure of the following assumption (which some behaviour is causing me to doubt).

Can I be sure that all go routines in stage N will completely finish and the data sent through stage_N_channel will all be processed in the control routine before the stage_complete channel is read from?

What I'm seeing is that sometimes, it looks like one or two results from a stage go missing, as if the control routine were moving on before processing them. Adding a one second sleep to the main routine after wg.Wait(), seems to help but I'm not sure is this is right.

Is there anything else unusual or potentially dangerous about this pattern? Is there another pattern I should consider using?

I finally settled on a solution where each stage resembles the following.

for i, some_data := range my_data {
  wg.Add(1)
  go func(i, some_data){
    // stage logic
    ...
    stage_one_channel <- some_stage_one_results
  }(i, some_data)
}

go func() {
    wg.Wait()
    close(stage_one_channel)
}()
for new_stage_one_data := <- stage_one_channel {
  // integrate received data
  ...
  wg.Done()
}


texts: Listing blog posts, each of which may belong to multiple categories

texts:
I have 3 tables like this:

CREATE TABLE IF NOT EXISTS blog_post (
  id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  title varchar(100) NOT NULL,
  image varchar(250),
  content TEXT NOT NULL,
  created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  edited DATETIME ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 DEFAULT COLLATE utf8_general_ci;

CREATE TABLE IF NOT EXISTS blog_category (
  id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  name varchar(100) NOT NULL UNIQUE,
  icon varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 DEFAULT COLLATE utf8_general_ci;

CREATE TABLE IF NOT EXISTS blog_post_blog_category (
  blog_post_id int(11) NOT NULL,
  blog_category_id int(11) NOT NULL,
  CONSTRAINT blog_post_blog_category_pkey PRIMARY KEY (blog_post_id, blog_category_id),
  CONSTRAINT blog_post_blog_category_fkey FOREIGN KEY (blog_post_id) REFERENCES blog_post (id)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT blog_category_blog_post_fkey FOREIGN KEY (blog_category_id) REFERENCES blog_category (id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
) ENGINE=INNODB CHARACTER SET ascii COLLATE ascii_general_ci;

So basically one blog post can be part of many categories and one category can be part of many posts, pretty straight forward, my question is what is best way to get list of all posts with their categories. As result I'm expecting array of posts and I want every post to have array of categories like this.

{
  "4": {
    "id": "4",
    "title": "first post",
    "image": "https://image.flaticon.com/icons/svg/102/102833.svg",
    "content": "this should be some content",
    "created": "2017-09-24 16:21:28",
    "edited": null,
    "categories": [{
      "id": 1,
      "icon": 'www.url.com',
      "name": 'category name'
    }, {
      "id": 5,
      "icon": 'www.url1.com',
      "name": 'category6 name'
    }]
  },
  "6": {
    "id": "6",
    "title": "second post",
    "image": "https://image.flaticon.com/icons/svg/102/102833.svg",
    "content": "this is some text from post",
    "created": "2017-09-24 16:29:53",
    "edited": null,
    "categories": [{
      "id": 5,
      "icon": 'www.url.com',
      "name": 'category name'
    }, {
      "id": 3,
      "icon": 'www.url1.com',
      "name": 'category6 name'
    }]
  }
}

This is how i did it, is this correct and good solution i feel like i'm missing something and i'm pretty sure this could be done way better?
Also i would like to get this list with correct indexes starting from 0 and not array with IDs like i have in my solution.

$app->get('/blog/posts', function (Request $request, Response $response, array $args) {
    $QUERY = 'SELECT bp.id, bp.title, bc.name FROM blog_post bp
              LEFT JOIN blog_post_blog_category bpbc ON bpbc.blog_post_id = bp.id
              LEFT JOIN blog_category bc ON bc.id = bpbc.blog_category_id ORDER BY bp.id';

    $result = R::getAll( $QUERY );
    $resultMap = array();

    foreach ($result as $value) {
        if(empty($resultMap[$value['id']])) {
            unset($value['name']);
            $resultMap[$value['id']] = $value;
            $resultMap[$value['id']]['categories'] = array();
        }
    }

    foreach ($result as $value) {
        $category = array();
        $category['name'] = $value['name'];
        array_push($resultMap[$value['id']]['categories'], $category);
    }

    echo json_encode($resultMap);
});