texts: Setting up require.js for a static website and loading custom code

texts:
I am a new SO/SE user and I initially asked this question on SO, but i was 'sent' here -for some reason i don't clearly understand but anyway- so here I am..! I was actually curious about my require.js setup, cause it is the  first time I 'm using it and having seen many different approaches/examples, I am not sure if what I 've done so far is correct.
So, on my index I have on the "head"

<script data-main="js/app" src="js/vendor/require-2.2.0-min.js"></script>

and at the end of my 'body' I have the Google Analytics snippet. No other script is loaded directly from index.

On app.js that is inside my $projectroot/js folder I have:

requirejs.config({
   "baseUrl": "js/vendor",
   "paths": {
      "app": "..",
      "jquery" : ['//code.jquery.com/jquery-1.12.4.min','jquery-1.12.4.min'],
      "modernizr" : 'modernizr-2.8.3-respond-1.4.2.min',
      "bootstrap" : ['//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min','bootstrap.min'],
      "plugins": '../plugins'
    },
    "shim": {
       "bootstrap": ["jquery"],
       "plugins": ["bootstrap"]
    }
});

requirejs(["app/main"]);

Also, my main.js which is on the same folder with app.js contains:

define([
   "jquery",
   "modernizr",
   "bootstrap",
   "plugins"
], function($)
{
$(function()
{
console.log('required plugins loaded...');
});
});

Finally, my plugins.js (again, on the same folder with main.js and app.js) is NOT a library, but some custom js code that I need to be loaded last. Is this ok so far? Any drawbacks with this approach? Would it be ok to add the rest of my custom js code on a similar manner?


texts: Eager load additional data about some instructors

texts:
Below is a snippet of code of a little practice project. I am still pretty new to EF and I was wondering if there is a way to write the below statement so that all required data is eager loaded since I have the ID parameter.

public ActionResult Index(int? id)
    {
        var viewModel = new InstructorIndexData
        {
            Instructors = _db.Instructors
                .Include(i => i.OfficeAssignment)
                .Include(i => i.Courses.Select(c => c.Department))
                .OrderBy(i => i.LastName)
        };

        if (id != null)
        {
            ViewBag.InstructorId = id.Value;
            viewModel.Courses = viewModel.Instructors.Single(i => i.InstructorId == id.Value).Courses;
        }

        return View(viewModel);
    }

When this action runs it grabs the instructor data and includes a few other collections because they are required for the initial view of the page. After selecting an instructor the page comes back with the instructor and the course the instructor is assigned to but this requires two calls to the database. Is there a way I can simple add the course to the initial query before it goes out to pull the instructor since that doesnt occur till the return?


texts: Task scheduler for a particular application

texts:
This isn't meant as a scheduler for just any job. The job that I need to schedule here is very specific for an application I'm writing for one of my clients.

The scheduler will run as a console application because it's comparatively lightweight. The application will be started with Windows (startup items in the Registry) and should always be running - much like a Windows service but not (mostly because I don't have a project template for a Windows service in VS 2013 Community).

The task this scheduler runs should be done at 4am every day.

Does it look like the code below matches this description of the requirements?

class MyScheduledTask
{
    private static Timer _timer;

    static void Main(string[] args)
    {
        SetTime();
    }

    private static void SetTime()
    {
        DateTime currentTime = DateTime.Now;
        int interval = 0;
        DateTime scheduleTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, 12, 45, 0);

        if (currentTime <= scheduleTime)
        {
            interval = (int)scheduleTime.Subtract(currentTime).TotalSeconds;
        }
        else
        {
            interval = (int)scheduleTime.AddDays(1).Subtract(currentTime).TotalSeconds;
        }

        _timer = new Timer(interval);
        _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
        _timer.Start();
    }

    void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        StartTaskWork();
        _timer.Interval = (24 * 60 * 60 * 1000);
    }
}


texts: Cleaning up a multi-model view in Rails3

texts:
I'm new to rails and have built a multi-model form. It's working, but some of the code doesn't feel right.

The model code is below. I'm using Devise for my user authentication:

# models/signup.rb
class Signup < ActiveRecord::Base
  has_one :company
  accepts_nested_attributes_for :company
end

# models/company.rb
class Company < ActiveRecord::Base
  belongs_to  :signup
  has_many    :users

  accepts_nested_attributes_for :users
end

# models/user.rb
class User < ActiveRecord::Base
  devise :database_authenticatable, :confirmable, :recoverable,
    :rememberable, :trackable, :validatable, :registerable

  attr_accessible :email, :password, :password_confirmation

  belongs_to :company
end

My view is fairly standard and follows the typical pattern for multiple models. The most important code is the initial Signup creation which is done via the following helper:

# signup is created via signups#new
def setup_signup(signup)
  signup.company ||= Company.new
  if signup.company.users[0] == nil
    1.times { signup.company.users.build }
  end
  signup
end

I had to add a condition to not create additional users, because if the form validation failed it would create another user.

Finally my controller code looks like this:

# controllers/signups_controller.rb
class SignupsController < ApplicationController
  respond_to :html

  def new
    @signup = Signup.new
  end

  def create
    @signup = Signup.new(params[:signup])

    # The first user to signup for a company should be an admin user
    # But this feels really awkward
    @signup.company.users.first.admin = true

    # Skip confirmation for the first user to signup
    @signup.company.users.first.skip_confirmation!

    if @signup.save
      sign_in_and_redirect(@signup.company.users.first)
    else
      render :action => "new"
    end
  end
end

This is what feels wrong to me:

When signing up to my website, there will only ever be a single User created. However, because a user is associated via a Company, and a Company has_many users I have to access this user in an awkward manner: signup.company.users.first. Obviously I could create an instance variable user = signup.company.users.first, and if that's the best solution, I'll take it, but it feels like there should be a better solution.
The setup_signup helper method requires checking if a user has already been created so a second user isn't created: if signup.company.users[0] == nil. To me if feels like Rails ought to have a cleaner way of handling this.
It feels like my create action is too fat for a controller, and that there ought to be a better way to set the admin boolean.

Am I right? Are there cleaner ways to accomplish these tasks?


texts:
I wrote this program to determine the Greatest Common Factor of any 2 given numbers, and would like to know of any improvements that can be made. I have tested it using a loop and 2 randomly generated numbers and it seems to work perfectly:

import java.util.ArrayList;
import java.util.Scanner;

public class GreatestCommonFactor
{
    public static void main(String[] args)
    {
        System.out.println("Please enter 2 numbers:");
        Scanner in = new Scanner(System.in);

        int a = Integer.parseInt(in.nextLine());
        int b = Integer.parseInt(in.nextLine());
        int greatestCommonFactor = gcf(a,b);

        System.out.println(greatestCommonFactor);
        in.close();
    }

    public static int gcf(int a, int b)
    {
        int result = 0;
        ArrayList<Integer> factorsA = factorise(a);
        ArrayList<Integer> factorsB = factorise(b);

        for (int i = 0; i < factorsA.size(); i++)
            if (factorsB.contains(factorsA.get(i)))
                result = factorsA.get(i);
        return result;
    }

    public static ArrayList<Integer> factorise(int num)
    {
        ArrayList<Integer> factors = new ArrayList<Integer>();
        int bounds = num/2;
        for (int i = 1; i <= bounds; i++)
            if (num % i == 0)
                factors.add(i);
        factors.add(num);
        return factors;
    }
}


texts:
Hello I made this calculator in Python, I know it's pretty basic but I want your opinions if I made it well or not, and if you find any mistakes or not.
P.S ( I know I could do another better than this one if I looked in internet but I want to evolve that's why I'm here )

#Commands
print("Operations that you can use:")
print("Addition: +")
print("Subtraction: -")
print("Multiplication: *")
print("Division: /")
print("Exponentiation: **")
print("Radicalization: **(1/")
print("\n")

#Variables
x = None
y = None
z = None
ce = 0

while ce < 1:

# Inputs
    x = float(input("First Value: "))
    y = input("Operation: ")
    z = float(input("Second Value: "))

# If
    if '+' == y:
        add = float(x) + float(z)
        print(add)
    elif '-' == y:
        sub = float(x) - float(z)
        print(sub)
    elif '/' == y:
        div = float(x) / float(z)
        print(div)
    elif "**(1/" == y:
        rad = float(x) **(1/float(z))
        print(rad)
    elif "**" == y:
        exp = float(x) ** float(z)
        print(exp)
    elif '*' == y:
        mul = float(x) * float(z)
        print(mul)
    print("Continue or Exit?")
    ce = int(input("    0    or   1  : "))


texts:
I'm currently working on some SQL code within Oracle Fusion BIP but it's not very optimised as it's using multiple LEFT,RIGHT and FULL OUTER joins to link tables together.

Unfortunately this is making the query timeout as there's roughly 80k lines and this will be the norm over a rolling 12 month period give or take a few thousand.

Is there any tips on how to optimise the below code to run quicker when ran.

SELECT DISTINCT
AID.INVOICE_ID,
LINES.AMOUNT,
AID.PERIOD_NAME,
GCC.SEGMENT1 AS Organisation,
GCC.SEGMENT2 AS ServiceArea,
GCC.SEGMENT3 AS AccountCode,
GCC.SEGMENT4 AS SubAccount,
INV.INVOICE_NUM,
INV.CREATION_DATE,
PO.SEGMENT1 as PO_Number,
SUP.VENDOR_NAME AS Supplier_Name,
--AID.LINE_TYPE_LOOKUP_CODE,
LINES.LINE_NUMBER,
LINES.DESCRIPTION,
SUP.SEGMENT1 as Supplier_Number,
FVV1.DESCRIPTION As OrganisationDesc,
FVV2.DESCRIPTION As ServiceAreaDesc,
FVV3.DESCRIPTION As AccountCodeDesc,
FVV4.DESCRIPTION As SubAccountDesc
FROM
AP_INVOICES_All INV
INNER JOIN
  AP_INVOICE_LINES_ALL LINES
  ON INV.INVOICE_ID = LINES.INVOICE_ID
INNER JOIN
  AP_INVOICE_DISTRIBUTIONS_ALL AID
  ON INV.INVOICE_ID = AID.INVOICE_ID
  --LEFT JOIN AP_INVOICE_LINES_ALL LINES
  --ON PO_HEADERS_ALL.PO_HEADER_ID = LINES.PO_HEADER_ID
FULL OUTER JOIN
  PO_HEADERS_ALL PO
  ON LINES.PO_HEADER_ID = PO.PO_HEADER_ID
LEFT JOIN
  PO_DISTRIBUTIONS_ALL PDA
  ON PO.PO_HEADER_ID = PDA.PO_HEADER_ID
INNER JOIN
  GL_CODE_COMBINATIONS GCC
  ON GCC.CODE_COMBINATION_ID = nvl(PDA.CODE_COMBINATION_ID, AID.DIST_CODE_COMBINATION_ID)
INNER JOIN
  POZ_SUPPLIERS_V SUP
  ON INV.VENDOR_ID = SUP.VENDOR_ID
LEFT JOIN
  FND_VS_VALUES_VL FVV1
  ON GCC.SEGMENT1 = FVV1.VALUE
LEFT JOIN
  FND_VS_VALUES_VL FVV2
  ON GCC.SEGMENT2 = FVV2.VALUE
LEFT JOIN
  FND_VS_VALUES_VL FVV3
  ON GCC.SEGMENT3 = FVV3.VALUE
LEFT JOIN
  FND_VS_VALUES_VL FVV4
  ON GCC.SEGMENT4 = FVV4.VALUE
WHERE
AID.LINE_TYPE_LOOKUP_CODE NOT IN
(
  'REC_TAX',
  'NONREC_TAX'
)
AND LINES.LINE_TYPE_LOOKUP_CODE NOT IN
(
  'TAX'
)
AND trim(TRANSLATE(FVV3.DESCRIPTION, '0123456789-,.', ' ')) is not null
ORDER BY
AID.INVOICE_ID,
LINES.LINE_NUMBER


texts:
I have just written the following "hello world" program in Prolog. Although it is as simple as it can be, I would like your feedback as Prolog is very new to me.

#!/usr/bin/swipl -q -t main -f

main :-
    write("Hello world!"), nl, fail.

Questions

Shebang: I am used to use #!/usr/bin/env python in Python. This is the
prefered method, because it does not rely (so much) on a specific system.
write: it seems as if I could also use format. Are there other options?
Style guide: I have not found any style guide regarding indentation or spaces after ,.
Is quitting with fail to usual way? I have seen halt, too.
File ending: I saved it as helloworld.pro. What file extensions are common?

As the code is short and I have difficulties with even getting that to work with Prolog, I would admire it if you could add the complete code when you make suggestions.


texts:
I want to make some VHDL code open source. But before I do, I want to make sure that it is as readable as possible. Things to improve upon could for example be naming and the use of comments.

The code is adding two binary-coded-decimal numbers. The algorithm behind it will come in the documentation. Note that this isn't the default way to add BCD numbers.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity BCD_adder is
    generic(
        --BCD_ADD_DEC_SIZE is the amount of decimal digits. e.g. BCD_ADD_DEC_SIZE = 4 means the highest representable integer is 9999
        BCD_ADD_DEC_SIZE : integer := 3
    );
    port(
        --input and output ports
        BCD_add_a_i, BCD_add_b_i : in STD_LOGIC_VECTOR(4*BCD_ADD_DEC_SIZE-1 downto 0);
        BCD_add_sum_o : out STD_LOGIC_VECTOR(4*BCD_ADD_DEC_SIZE-1 downto 0);
        BCD_add_clk_i, BCD_add_cin_i : in STD_LOGIC;
        BCD_add_cout_o : out STD_LOGIC
    );
end entity;
architecture behavioral of BCD_adder is
    signal BCD_a, BCD_b : unsigned(4*BCD_ADD_DEC_SIZE downto 0);
    signal BCD_sum : STD_LOGIC_VECTOR(4*BCD_ADD_DEC_SIZE-1 downto 0);
    signal BCD_cout : STD_LOGIC;

    --increment6: a function to increment a 4 bit STD_LOGIC_VECTOR by 6.
    function increment6 (number : STD_LOGIC_VECTOR(3 downto 0)) return STD_LOGIC_VECTOR is
    begin
        return ((number(3) or number(2) or number(1)) & ((number(2) or number(1)) nand (number(2) nand number(1))) & not(number(1)) & number(0));
    end function;

    --decrement6: a function to decrement a 4 bit STD_LOGIC_VECTOR by 6.
    function decrement6 (number : STD_LOGIC_VECTOR(3 downto 0)) return STD_LOGIC_VECTOR is
    begin
        return ((number(3) and number(2) and number(1)) & (number(2) xor number(1)) & not(number(1)) & number(0));
    end function;
begin
    process(BCD_add_clk_i)

        --BCD_SIZE is the amount of binary digits that are needed for the BCD number. Each decimal digit is 4 bits, so 4*BCD_ADD_DEC_SIZE.
        constant BCD_SIZE : integer := 4*BCD_ADD_DEC_SIZE;
        variable cin : STD_LOGIC;
        variable a, b, sum : unsigned(BCD_SIZE downto 0);
    begin
        if rising_edge(BCD_add_clk_i) then

            --Put the inputs in the variables, add a leading '0' to store a later carry.
            BCD_a <= unsigned('0' & BCD_add_a_i);
            BCD_b <= unsigned('0' & BCD_add_b_i);
            cin := BCD_add_cin_i;
            a := BCD_a;
            b := BCD_b;

            --increment every decimal digit of operand b by 6
            for i in 0 to BCD_ADD_DEC_SIZE-1 loop
                b(4*i+3 downto 4*i) := unsigned(increment6(STD_LOGIC_VECTOR(b(4*i+3 downto 4*i))));
            end loop;

            --add a, b and the carry_in to form a temporary sum that needs to be corrected
            sum := a + b + ("" & cin);

            --correction: if the sum of two decimal digits exceeded 9, subtract 6 from the temporary sum
            for j in 0 to BCD_ADD_DEC_SIZE-1 loop
                if (sum(4*j+4) = (a(4*j+4) xor b(4*j+4))) then
                    sum(4*j+3 downto 4*j) := unsigned(decrement6(STD_LOGIC_VECTOR(sum(4*j+3 downto 4*j))));
                end if;
            end loop;

            BCD_sum <= STD_LOGIC_VECTOR(sum(BCD_SIZE-1 downto 0));
            BCD_cout <= sum(BCD_SIZE);
        end if;

        --assign outputs. If the sum has a carry out of '1', BCD_add_cout_o will be set to '1'.
        BCD_add_sum_o <= BCD_sum;
        BCD_add_cout_o <= BCD_cout;
    end process;
end behavioral;


texts:
Description:

  You’re given the pointer to the head node of a linked list and a
  specific position. Counting backwards from the tail node of the linked
  list, get the value of the node at the given position. A position of 0
  corresponds to the tail, 1 corresponds to the node before the tail and
  so on.

Code:

int GetNode(Node head,int n) {
     // This is a "method-only" submission.
     // You only need to complete this method.
    Node current = head;
    int count = 0;
    while (current != null) {
        count++;
        current = current.next;
    }
    current = head;
    for (int i = 0; i < count - n - 1; i++) { // extra -1 to avoid going out of linked list.
        current = current.next;
    }
    return current.data;
}


texts:
def alphabetlist():
    print("alphabet1 = [a,b,c,d,e,f]")
    print("alphabet2 = [g,h,i,j,k,l]")
    print("alphabet3 = [m,n,o,p,q,r]")
    print("alphabet4 = [s,t,u,v,w,x]")
    print("alphabet5 = [y,z]")
print("Guess a word.")
print("Now i will try to figure out the word you guessed.")
totalletters=int(input("total number of letters in your guessed words are: "))
def chooselist(x):
    if x == 1:
        print(alphabet1)
    elif x == 2:
        print(alphabet2)
    elif x == 3:
        print(alphabet3)
    elif x == 4:
        print(alphabet4)
    elif x == 5:
        print(alphabet5)
list=[ ]
def listtranspose(w):
    if w == 1:
        i=int(input());list.append(alphabet1[i-1])
    elif w == 2:
        i=int(input());list.append(alphabet2[i-1])
    elif w == 3:
        i=int(input());list.append(alphabet3[i-1])
    elif w == 4:
        i=int(input());list.append(alphabet4[i-1])
    elif w == 5:
        i=int(input());list.append(alphabet5[i-1])
alphabetlist()
alphabet1 = ["a","b","c","d","e","f"]
alphabet2 = ["g","h","i","j","k","l"]
alphabet3 = ["m","n","o","p","q","r"]
alphabet4 = ["s","t","u","v","w","x"]
alphabet5 = ["y","z"]
step_1=[ ];h=0
while totalletters>h:
    print("your letter is from which list 1,2,3,4,5")
    x = int(input())
    step_1.append(x);h+=1
print("***\n  1    2    3    4    5    6   ")
g=0
while totalletters>g:
    chooselist(step_1[g]);g+=1
print("*******");e=0
while totalletters>e:
    print("choose from these lists again now 1,2,3,4,5,6")
    listtranspose(step_1[e]);e+=1
print("the word you guessed is: ",end=" ")
for i in range(0,len(list),1):
print(list[i],end="")

This program is a word guessing game. The user thinks of a word and this program guesses it. through a series of list I want to know if there are other ways to write this, more easily actually I get all the functions used but not the next part


texts: Returning result and error status for number type conversions

texts:
Looking for review of design strategy of using a struct to return the functional result and error status.  Your experience of how my design approach may succeeded or failed is especially welcomed.

In constructing a library of functions, I've tried various error handling approaches, none completely satisfactory and was about to embark on this 5th strategy. (1-4 below.) Identifying any pitfalls or referencing any existing like-designed specification is sought.

Return result as a struct bundled with the status.

Below is a small portion of a much larger conversion set of functions.  The style/correctness of the function bodies is primarily illustrative of how functions may construct the combined struct result.  In main(), one example use the returned structures value and status. The next just uses the value, showing a functional usage.

#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct {
  errno_t error;
  double retval;
} e_double_type;

typedef struct {
  errno_t error;
  unsigned retval;
} e_unsigned_type;

e_double_type string_to_double(const char *src) {
  char *endptr;
  errno = 0;
  e_double_type y = { 1, strtod(src, &endptr) };
  if (endptr == src) return y;
  if (errno && fabs(y.retval) > 1.0) return y;
  y.error = 0;
  return y;
}

e_unsigned_type longlong_to_unsigned(long long x) {
  e_unsigned_type y = { 1, 0 };
  if (x < 0) return y;
  if (x > UINT_MAX) {
    y.retval = UINT_MAX;
    return y;
  }
  y.retval = (unsigned) x;
  return y;
}

int main(void) {

  // Error status and value
  e_double_type y = string_to_double("123");
  printf("%d %le\n", y.error, y.retval);

  // Just value - status not of concern
  // e_unsigned_type variable not needed
  printf("%u\n", longlong_to_unsigned(123456789012345).retval +
     longlong_to_unsigned(12345).retval);

  return 0;
}

Typical other methods to receive a function result and error status include which I have tried.

Global errno:

errno = 0;
char *endptr;
long num = strtol(some_string, &endptr, 10);
if (errno) Handle_RangeError();

Return special value:

int ch = fgetc(stdin);
if (ch == EOF) Handle_Problem();

Pass address of error status and return result:

int status;
y = foo(x, &status);
if (status) Handle_fooFailure();

Pass address to store result and return error status:

FILE *stream;
errno_t status = fopen_s(&stream, filename, "r");
if (status) Handle_OpenFailure();

The above methods, except #2, fail to keep the result and status together.  #2 requires a wider return type that is often not available.  The program model of using a function, where the parameters are only the inputs, and the result is the output is very appealing.


texts:
I have written code to add a node to the head of the list. Criticisms and feedback are welcome.

typedef struct sList
{
    void *data;
    struct sList *nextNode;
}sList;

sList *addNode2Head(sList *psList,void *data)
{
    if(psList == NULL)
        psList = newNode();
    else
    {
        psList = addHeadNode(psList);
        psList->data = data;
    }
    return psList;
}

sList *newNode(void)
{
    sList *psList =(sList *) malloc(sizeof(sList));
    //sList *psList = malloc(sizeof *sList); //Is it correct way ? if so why ?
    psList->nextNode = NULL;
    return psList;
}

sList *addHeadNode(sList *psList)
{
   sList *psListTemp = newNode();
   psListTemp->nextNode = psList;
   return psListTemp;
   //Another way ,
   //psList = psListTemp; //No return needed
}


texts: Evaluating a hashing function used to create secure API key

texts:
What are your thoughts on the following code? is it secure enough?

Note: $password is used to represent the secret, which would essentially be a SHA512 hash of

username . password . signupdate(unixtime)

Do you think I'm covered?

Here's a demo for the testing purposes.

error_reporting(E_ALL & ~E_NOTICE | E_STRICT);
ini_set("display_errors", "1");
echo '
';
$break = '
';
$password = trim("password");
echo 'step1 the password is posted
';
echo $password;
echo $break;
echo $break;
$time = date("F j, Y, g:i a");
echo 'step2 get the time in human readable format
';
echo $time;
echo $break;
echo $break;
$salt1 = $time . hash('sha512', (sha1 .$time));
echo 'step3 create salt1
';
echo $salt1;
echo $break;
echo $break;
$salt2 = substr(md5(uniqid(rand(), true)), 0, 25);
echo 'step4 create salt2
';
echo $salt2;
echo $break;
echo $break;
$hash = str_split($password);
echo 'step5 split the password into an array
';
print_r($hash, false);
echo $break;
echo $break;
echo 'step6 hash each charachter of the password in the array
';
foreach($hash as $key => $value) {
$hashed[] = $salt2 . hash('sha512', ($salt . $value)) . $salt . hash('sha256', (salt2 . $key));
}
print_r($hashed, false);
echo $break;
echo $break;
$hashed_2 = implode($hashed);
echo 'step7 implode the array into a single hash
';
echo $hashed_2;
echo $break;
echo $break;
$hashfinal = str_shuffle($hashed_2);
echo 'step8 shuffle the hash to decrease entropy
';
print_r($hashfinal, false);


texts: Find the integer representing the last sub-string of a string

texts:
I came across a question at the Udacity Intro to Computer Science course:

Define a procedure, find_last, that takes as input two strings, a search string and a target string, and returns the last position in the search string where the target string appears, or -1 if there are no occurrences.
Example: find_last('aaaa', 'a') returns 3

I think there should be a much cleaner (shorter, fewer words) way of writing this function:
def find_last(s, t):
    count = 0
    if s.find(t) >= 0:
        while s.find(t, count + 1) >= 0:
            count += 1
        return count
    else:
        return s.find(t)


texts:
I have surrounded my initials with a circle. This is intended to be a re-usable component in a responsive layout. (When it is re-used the text will always be two letters, and the font won't change. It behaves sensibly when the browser zooms in and out, but I haven't yet considered if a different component size is needed for very small screens.)

I tried two approaches, firstly with flex layout, and secondly using the box model, and I'm not sure which I prefer.

.flex-profile-icon {
  display: flex;
  flex: 0 0 auto;
  width: 6em;
  height: 6em;
  border-style: solid;
  border-radius: 50%;
  justify-content: center;
}

.flex-profile-icon-text {
  align-self: center; /* center on cross-axis, i.e. vertically */
  font-size: 300%;
}

.trad-profile-icon {
  width: 6em;
  border-style: solid;
  border-radius: 50%;
  line-height: 0;
  position: relative;
}
.trad-profile-icon:after {
  content: "";
  display: block;
  padding-bottom: 100%; /* hack for equal height to width */
}
.trad-profile-icon-text {
  position: absolute;
  bottom: 50%;
  width: 100%;
  text-align: center;
  font-size: 300%;
}

/*
Copyright 2019-2020 by dcorking and Code Boxx
*/

  Aim is for the text to be centered in the circle

Flexbox layout

    DC

Traditional box layout

    DC

  Credit for the traditional box layout approach due to How to Create CSS Circles (And Add Text To It), W.S. Toh of Code Boxx

I will be interested in your recommendations on maintainability, cross-browser compatibility, and compatibility with layout frameworks such as Foundation (XY Grid or Float Grid) and Bootstrap.
Codepen


texts: bash script to organize files and cleanup files

texts:
I have been working on a bash script for a while now to organize my movie files.  I can do it by hand, but at the time I was taking a bash scripting class and thought I would like to use it to create this project.  I don't know if there is a better way of doing it or not, but I would like you to take a look at my script and give me feedback on it.  I believe it works, but I haven't put it through the paces yet.

#!/bin/bash

MovieList="points to .txt file with name of files"
DirList="points to a .txt file with the name to use to create the directory"
dest_Dir="where to put the files "
src_Dir="where to look for the files"
CreateLogFile="log file of directory created"
MoveLogFile="log file of move files"

# Will read in a list of movies and make the directories for them

createDirectory()
{
    while read -r line
    do
    if [ ! -d $dest_Dir"$line" ]
    then
            mkdir -v $dest_Dir"$line" >> $CreateLogFile
    else
            :
    fi
done < "$DirList"
}
# end createDirectory

# After directories have been created will go and find those movies and move
# them to their proper directory

movieMovies()
{
    while read -r line
do
    find $src_Dir  -type f \( -iname "$line" ! -iname ".*" \) | xargs -I '{}' mv -v {} $dest_Dir"$line" >> $MoveLogFile
done < "$MovieList"
}
# end of moveMovies

# Time to tidy up by going back and seeing if there is any empty directory
# and if so removing said directory

DirectoryEmpty()
{
while read -r line
do
    if [ $(ls -A $dest_Dir"$line" | wc -l) -eq 0 ]
    then
        rmdir $dest_Dir"$line"
    else
        :
    fi
done < "$DirList"
}
# end of DirectoryEmpty

# ---------------------------------Main---------------------------------------
createDirectory
moveMovies
DirectoryEmpty
# ----------------------------------End---------------------------------------


texts: Cross validation of gradient boosting machines

texts:
I am fairly new to Python. I implemented a short cross-validation tool for gradient boosting methods.

import numpy as np

from sklearn.metrics import roc_auc_score as auc
from sklearn import cross_validation
from time import time

def heldout_auc(model, X_test, y_test):
    score = np.zeros((model.get_params()["n_estimators"],), dtype=np.float64)
    for i, y_pred in enumerate(model.staged_decision_function(X_test)):
        score[i] = auc(y_test, y_pred)
    return score

def cv_boost_estimate(X,y,model,n_folds=3):
    cv = cross_validation.StratifiedKFold(y, n_folds=n_folds, shuffle=True, random_state=11)
    val_scores = np.zeros((model.get_params()["n_estimators"],), dtype=np.float64)
    t = time()
    i = 0
    for train, test in cv:
        i = i + 1
        print('FOLD : ' + str(i) + '-' + str(n_folds))
        model.fit(X.iloc[train,], y.iloc[train])
        val_scores += heldout_auc(model, X.iloc[test,], y.iloc[test])
    val_scores /= n_folds
    return val_scores,(time()-t)

Then I can look for the optimal number of trees with the following:

print('AUC : ' + str(max(auc)) + ' - index : ' + str(auc.tolist().index(max(auc))))

Everything is working, but the syntax feels uneasy and "not Pythonic". Does someone have improvements to suggest?


texts: The sniper: a Zombie searcher for specific tags

texts:
Sometimes, it's not enough to know what the easy prey is. You also need to know whether you will be able to hunt it down. What good is an almost turned haskell zombie if you cannot read the functional incantations of the language? How will you as a vba guru handle a python behemoth?

That's why I present to you the tag-based zombie sniffer:

SELECT
  q.Id AS [Post Link],
  q.Tags
FROM
  Posts q
    INNER JOIN Posts a   ON q.Id           = a.ParentId
    INNER JOIN PostTags  ON q.Id           = PostTags.PostId
    INNER JOIN Tags      ON PostTags.TagId = Tags.id
WHERE
      q.AnswerCount > 0
  AND q.AcceptedAnswerId IS NULL
  AND Tags.TagName   = '##TagName##'
GROUP BY
  q.Id, q.Tags
HAVING
      MAX(a.Score) >= ##MinScore:int?0##
  AND MAX(a.Score) <= ##MaxScore:int?0##

-- TagName: Tag name "as you would use in your post"
-- MinScore: Highest answer has at least votes:
-- MaxScore: Highest answer has at most votes:

You can find it on SEDE.

As it's predecessor, it looks for easy prey by default:

questions that have at least one answer
no answer has a score of more than 0
the highest scored answer has a score of at least 0
has no accepted answer

However, this one also takes a tag name so that you can search for C++ zombies or similar. This is the first time I've ever written an SQL query with three JOINs, so I have no idea whether this is considered good style. Also, I group by the q.Tags to show them in the result, but I think that's a hack and not really good style.


texts: Verifying if one list contains a string from another list

texts:
I am trying to validate that when given two lists,

List<String> models;
List<String> titleOfVehicle;

that one of the models must be contained in each of the titleOfVehicle.

For example, given the following:

models = {Accord, Civic, Element}
titleOfVehicle1 = {2014 Honda Accord, 2011 Toyota Camry}
titleOfVehicle2 = {2013 Honda Accord, 2015 Honda Element, 2011 Honda Civic}

then when comparing models and titleOfVehicle1 it will fail since 2011 Toyota Camry does not contain one of the models provided. However, titleOfVehicle2 will pass since it contains a model for each vehicle titles.

Here is my code:

public boolean compareTwoList(List<String> models, List<String> titleOfVehicles) {
    boolean flag = false;

    for(int i = 0; i < titleOfVehicles.size(); i++) {
        flag = false;
        int k = 0;
        for(int j = 0; j < models.size(); j++) {
            if(titleOfVehicles.get(i).contains(models.get(j))) {
                flag = true;
                break;
            } else if(k == models.size() - 1 && flag == false) {
                return false;
            }
            k++;
        }
    }
    return flag;
}


texts: Optimal string literal tokenizing algorithm

texts:
I have a tokenizer, where one of the token types happens to be a C# string type. It takes a TextReader as its input, which is created from a StringReader, and it needs to support the basic stuff C# strings supports, such as "jo dude", "joe \"dudes\"", "this is a backslash \\ token" and of course "this is carriage return \r\nthis is next line"

Currently my method looks like this;

private string ReadSingleLineStringLiteral ()
{
    StringBuilder buffer = new StringBuilder ();
    int nextChar = _reader.Read ();
    while (nextChar != -1) {
        buffer.Append ((char)nextChar);
        if (nextChar == '"' &&
            (buffer.Length == 1 ||
                 buffer [buffer.Length - 1] != '\\' ||
                 (buffer.Length - buffer.ToString ().TrimEnd ('\\').Length) % 2 == 0)) {
            break;
        }
        nextChar = _reader.Read ();
    }
    if (buffer [buffer.Length - 1] != '"')
        throw new ArgumentException ("unclosed string literal in hyperlisp file");
    return buffer.ToString ().Substring (0, buffer.Length - 1)
        .Replace ("\n", "\r\n") // normalizing carriage returns
        .Replace ("\r\r\n", "\r\n")
        .Replace ("\\\"", "\"")
        .Replace ("\\\\", "\\");
}

It works I think, however, I suspect this is far from optimal, among other things, I hate that buffer.ToString ().TrimEnd ('\\').Length) % 2 part of it.

The _reader is the TextReader object, that at the entry of my methods are at the first character within the content of my string literal.

Can anyone figure out the optimal solution for parsing a C# type of string literal, and optimize my method?

Please don't tell me to use some library, since I don't want to bring in the overhead of any libraries to perform a task I think should be easily possible to implement with some 10-20 lines of code.

For bonus points, I'd love to also have a solution to my "multiline string literal algo" too. This method should read string the same way C# reads them when given @"some string". Currently it looks like this:

private string ReadMultiLineStringLiteral ()
{
    StringBuilder buffer = new StringBuilder ();
    int nextChar = _reader.Read ();
    while (nextChar != -1) {
        buffer.Append ((char)nextChar);
        nextChar = _reader.Peek ();
        if (nextChar != '"' && (buffer.Length - buffer.ToString ().TrimEnd ('"').Length) % 2 == 1)
            break;
        nextChar = _reader.Read ();
    }
    if (buffer.Length == 0 || buffer [buffer.Length - 1] != '"')
        throw new ArgumentException ("unclosed multiline string literal in hyperlisp close to end of hyperlisp");
    return buffer.ToString ().Substring (0, buffer.Length - 1)
        .Replace (@"""""", @"""")
        .Replace ("\n", "\r\n") // normalizing carriage returns
        .Replace ("\r\r\n", "\r\n");
}

Both methods starts on the first character of the actual string content, e.g. for string @"xyz" the multiline method has the TextReader reader position being at "x", for string "abc" the singleline string literal method has the reader position being at "a".

This is probably unnecessary to say, but obviously Regex is a no-no.


texts: Render multiple SSRS reports in parallel

texts:
This service takes in a report request object that can contain multiple reports that need to be rendered. This code works but I'm not sure if I've implemented anything wrong. Note the exportedImage.Result makes this synchronous but when I tried adding async and await to the Parallel.ForEach it doesn't seem to work so this was essentially a workaround, that's why I'm looking to figure out if I've implemented this correctly or not. _exporter.Export is an asynchronous method.
Just FYI, when I tried to add async and await, I added it like so:
await Task.Run(() => Parallel.ForEach(request.Reports, async report =>
var exportedImage = await _exporter.Export(_reportServerUrl, reportPath, export, reportParameters);
var reportDictionary = new ConcurrentDictionary<int, string>();

await Task.Run(() => Parallel.ForEach(request.Reports, report =>
{
    var (reportPath, bindingOrder, reportParameters) = report;

    var exportedImage = _exporter.Export(_reportServerUrl, reportPath, export, reportParameters);

    if (exportedImage.Result == null)
    {
        throw new InvalidOperationException($"Could not render report {reportIdentifier} with binding order {bindingOrder}.");
    }

    reportDictionary.GetOrAdd(bindingOrder, exportedImage.Result);
}));


texts: Find property and value pairs between two objects

texts:
I have a function that looks through an array of objects and returns an array of all objects that have matching property and value pairs. This works fine but I always get the notification: "Don't make functions within a loop".

So is this a bad approach to use a function within a loop?

function where(collection, source) {
  var arr = [];
  var keys = Object.keys(source);
  // What's in a name?
  for(var i = 0; i < collection.length; i++){
     if(keys.every(function(x){return x in collection[i] && source[x] == collection[i][x];})){
       arr.push(collection[i]);
     }
  }

  return arr;
}

where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });


texts: Nested object to hierarchical object list

texts:
I have a C# type to generate Layer SubLayer:

public class Layer
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
}

And simulated a list with a Db class:

public static class Db
    {
        public static IList<Layer> GetLayers()
        {
            return new List<Layer>
                   {
                       new Layer{Id = 1, ParentId = 0, Name = "First Layer" },
                       new Layer{Id = 2, ParentId = 1, Name = "First SubLayer1" },
                       new Layer{Id = 3, ParentId = 1, Name = "First SubLayer2" },
                       new Layer{Id = 4, ParentId = 1, Name = "First SubLayer3" },
                       new Layer{Id = 5, ParentId = 0, Name = "Second Layer" },
                       new Layer{Id = 6, ParentId = 5, Name = "Second SubLayer1" },
                       new Layer{Id = 7, ParentId = 5, Name = "Second SubLayer2" },
                       new Layer{Id = 8, ParentId = 7, Name = "Sub -3" }
                   };
        }
    }

I want to get a serialized JSON object, so I created a service class to generate and changed the Layer class:

public class Layer
{
    public int Id { get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
    public IList<Layer> ChildLayers { get; set; }

    public Layer()
    {
        ChildLayers = new List<Layer>();
    }
}

public class LayerService
{
    public IList<Layer> GetLayers()
    {
        IList<Layer> data = Db.GetLayers();

        IList<Layer> hierarcy = new List<Layer>();

        foreach (var layer in data)
        {
            var layer1 = layer;

            var sublayers = data.Where(i => i.ParentId == layer1.Id && i.ParentId !=0);

            var enumerable = sublayers as Layer[] ?? sublayers.ToArray();

            if(enumerable.Any() && layer.ParentId ==0)
                hierarcy.Add(layer);

            foreach (var sublayer in enumerable)
            {
                layer.ChildLayers.Add(sublayer);
            }
        }

        return hierarcy;
    }
}

But this LayerService code is ugly. Is there any practical way with Linq or else? Is there a cleaner way?


texts:
Long story short: I wanted some of the time-saving functionality of jQuery without the bulk of the entire library. So, I wrote a lightweight shorthand library inspired by jQuery I'm calling Mozart JS, and I'd like to see how I can further enhance it without major impact on load times.

Thoughts? Full library on GitHub.

Mozart JS

Element Retrieval

Fairly straightforward.

function $get(e, t) {
    if (void 0 === t) t = document;
    if (e.startsWith('#')) return t.getElementById(e.substring(1));
    if (e.startsWith('.')) return t.getElementsByClassName(e.substring(1));
    if (e.startsWith('-')) return t.getElementsByName(e.substring(1));
    return t.getElementsByTagName(e);
}

Example:

var foo = $get('#bar'); //returns element with the Id of "bar"
var zed = $get('.cop'); //returns collection with the classname "cop"

Element Creation

Slightly more complicated; allows the assignment of common properties and all attributes.

function $make(t, p) {
    var o = document.createElement(t);
    if (p.style) o.style.cssText = p.style;
    if (p.class) o.className = p.class;
    if (p.text) o.textContent = p.text;
    if (p.value) o.value = p.value;
    Object.keys(p).forEach((e) => {
        if(e.startsWith("@")) {
            o.setAttribute(e.substring(1), p[e]);
        }
    });
    return o;
}

Example:

var h = $make('a', {
    'class': 'myClass',
    'text': 'Google',
    '@id': 'googleLink',
    '@href': 'https://google.com',
    '@target': '_blank'
});

//Equivalent to:

var h = document.createElement('a');
h.className = 'myClass';
h.textContent = 'Google';
h.setAttribute('id','googleLink');
h.setAttribute('href', 'https://google.com');
h.setAttribute('target', '_blank');

Element Sibling Insertion

Designed to mimic most of jQuery's insertBefore() method. Equivalent function exists for insertAfter(); omitted here in order to save space.

function $addBefore(e, t) {
    if (typeof t === 'string' || t instanceof String) {
        if (t.startsWith('#')) {
            $get(t).parentNode.insertBefore(e, $get(t));
        } else {
            var arr = $get(t);
            for (var i in arr) {
                var f = e.cloneNode(true);
                arr[i].parentNode.insertBefore(f, arr[i]);
            }
        }
    } else {
        t.parentNode.insertBefore(e, t);
    }
}

Example:

var foo = $make('div', {'text': 'This is a test'});
$addBefore(foo, '.myClass'); //adds an instance of foo before each myClass

Element Removal

Removes an element. Still uses basic jQuery syntax.

function $remove(e) {
    if (typeof e === 'string' || e instanceof String) {
        $remove($get(e));
    } else if (e.nodeType === 1 || e.nodeType === 3) {
        e.parentNode.removeChild(e);
    } else {
        for (var i in e) {
            e[i].parentNode.removeChild(e[i]);
        }
    }
}

Example:

$remove('#myId');
$remove('.myClass');

//Equivalent to:

var rem = document.getElementById('myId');
rem.parentNode.remove(rem);
for (var i in document.getElementsByClassName(myClass)) {
    var elm = document.getElementsByClassName(myClass)[i];
    elm.parentNode.remove(elm);
}


texts: Storing variables to a map by splitting a text file

texts:
I'm currently making a social media app that contains profile details such as interests in a text file. The following code works by using markers in the text file to upload these details to map data structures. I'm wondering if there is a more efficient way of doing this.

textList = ReadFile(FileName);
System.out.println("File Length" + textList.size());
for (int i = 0; i < textList.size(); i++){
    String[] split = splitTxt(textList.get(i), "\\s+");
    List<String> friends = new ArrayList<>();
    List<String> interests = new ArrayList<>();
    if (split.length >= 2){
        String[] interestArray = splitTxt(split[2], ";");
        for(int j = 0; j < interestArray.length; j++){
            interests.add(interestArray[j]);
        }
        Accounts.put(split[0],split[1]);
        intrestDic.put(split[0],interests);
        for(int j= 3; j < split.length; j++){
            friends.add(split[j]);

        }
        FriendsDic.put(split[0],friends);
        System.out.println(FriendsDic.get(split[0]));
    }

}

I've created a split function that looks for marker to split it on

public static String[] splitTxt(String text, String type){
    String[] parsedText = text.split(type);
    return parsedText;
}


texts:
I've made a simple implementation of a bank ATM machine in pure Ruby. I'd like to hear some recommendations to make my code more idiomatic.

atm.rb

This is the startup file. I didn't use a class and I'm getting the user input using  gets.chomp and a case statement for the flow control.

require_relative 'account'

account = Account.new

loop do
  puts "What you want to do?\n1- Deposit\n2- Withdraw\n3- Check balance\n4- Check statement\n5- Exit"
  option = gets.chomp
  case option
  when '1'
    puts "How many dollars do you want to deposit?"
    amount = gets.chomp.to_f
    account.deposit(amount)
  when '2'
    puts "How many dollars do you want to withdraw?"
    amount = gets.chomp.to_f
    account.withdraw(amount)
  when '3'
    puts "You have #{account.balance} USD."
  when '4'
    puts account.statement.join("\n")
  when '5'
    break
  else
    "Wrong option. Try again."
  end
end

account.rb

I used an array to store the transactions. To check the balance, I'm iterating through the array using the inject function.

require_relative 'transaction'

class Account
  def initialize
    @transactions = []
  end

  def balance
    @transactions.inject(0) { |sum, transaction| sum + transaction.value }
  end

  def deposit(amount)
    add_transaction(amount, :deposit)
  end

  def withdraw(amount)
    add_transaction(amount, :withdraw)
  end

  def statement
    @transactions.map { |transaction| transaction.to_s }
  end

  private
  attr_accessor :transactions

  def add_transaction(amount, type)
    @transactions << Transaction.new(amount, type)
  end
end

transaction.rb

This is the transaction class. I don't know if it's ok to validate the constructor parameters the way I did.

class Transaction
  attr_accessor :amount, :type, :timestamp

  def initialize(amount, type)
    raise 'Invalid type' unless POSSIBLE_TYPES.include? type
    @amount = amount
    @type = type
    @timestamp = Time.now.getutc
  end

  def value
    return @amount if type == :deposit
    -@amount
  end

  def to_s
    "#{@timestamp} - #{type} - #{amount} USD"
  end

  private
  POSSIBLE_TYPES = [:deposit, :withdraw]
end

I'm aware that I'm not validating the user input type or value, I'm ok with that.

See it running in repl.it.


texts:
A few functions to let me manage TAGS files more easily. Typically, my projects contain at least one sub-folder. I got sick of manually updating, so I wrote this to help me update a single TAGS file per project (always in the projects' root directory).

Please share your thoughts (aside from "Why are you using Emacs?", you're not likely to change my mind).

One thing I've noticed that could trip me up is that it only tags files of one language (and if I had a project that had both Haskell and JS code, for example, I could tag one or the other). I would particularly appreciate advice on better ways to write find-parent-tags than just building each path from available sub-strings.

(defun create-tag-table ()
  "This will recursively tag all files of a given type starting with the current buffers' directory.
   It overwrites the old TAGS file, if one exists.
   Haskell files assume you've installed `hasktags`."
  (interactive)
  (let ((file-type (get-taggable-extension))
        (cur-dir default-directory)
        (tags-file (find-parent-tags default-directory)))
    (if (equalp file-type "hs")
        (shell-command "hasktags --ignore-close-implementation --etags `find . -type f -name \"*.*hs\"`")
          (shell-command (concat "find -name \"*." file-type "\" -print | etags -")))))

(defun find-parent-tags (dir)
  "Traverses the directory tree up to /home/[user]/ or / whichever comes first.
   Returns either nil or the directory containing the first TAGS file it finds."
  (interactive (list default-directory))
  (find-parent-tags-rec (build-tag-paths dir)))

(defun find-parent-tags-rec (list-of-filepath)
  (cond ((null list-of-filepath) nil)
        ((file-exists-p (car list-of-filepath)) (car list-of-filepath))
        (t (find-parent-tags-rec (cdr list-of-filepath)))))

(defun build-tag-paths (dir-string)
  (build-tag-paths-rec (remove-if #'empty-string? (split-string dir-string "/")) (list "/")))

(defun build-tag-paths-rec (steps acc)
  (if (null steps)
      (mapcar (lambda (p) (concat p "TAGS")) acc)
    (build-tag-paths-rec (cdr steps)
             (cons (concat (car acc) (car steps) "/") acc))))

(defun get-taggable-extension ()
  "Either returns the current file's extension (if it's appropriate) or asks the user to pick one with completion"
  (let ((b-name (buffer-file-name (current-buffer)))
        (valid-exts (list "lisp" "py" "c" "hs" "rb" "ss" "scm" "js" "erl" "el")))
    (string-match "\\.\\(.*?\\)$" b-name)
    (let ((current-filetype (match-string 1 b-name)))
      (if (member current-filetype valid-exts)
          current-filetype
        (completing-read "File type: " valid-exts nil 'confirm)))))

(defun empty-string? (s) (equalp s ""))

(provide 'tagariffic)


texts: Async distributed locking with StackExchange.Redis

texts:
I have been trying to write an analogy to this approach to distributed locking with two differences:

making it asynchronous
making it work with StackExchange.Redis rather than AppFabric Cache.

My biggest concern is going out of my way to use IDisposable to make it compatible with using() but thus calling an async method from within Dispose (in a sort of 'fire and forget' way). The basic tests I have run so far seem to pass ok but it doesn't seem right.

public static class RedisExtensions
{
    public static Task<IDisposable> AcquireLockAsync(this IDatabaseAsync db, string key, TimeSpan? expiry = null, TimeSpan? retryTimeout = null)
    {
        if (db == null)
        {
            throw new ArgumentNullException("db");
        }
        if (key == null)
        {
            throw new ArgumentNullException("key");
        }
        return DataCacheLock.AcquireAsync(db, key, expiry, retryTimeout);

    }

    private class DataCacheLock : IDisposable
    {
        private static StackExchange.Redis.IDatabaseAsync _db;
        public readonly RedisKey Key;
        public readonly RedisValue Value;
        public readonly TimeSpan? Expiry;
        private DataCacheLock(IDatabaseAsync db, string key, TimeSpan? expiry)
        {
            _db = db;
            Key = "ninlock:" + key;
            Value = Guid.NewGuid().ToString();
            Expiry = expiry;
        }
        public static async Task<IDisposable> AcquireAsync(IDatabaseAsync db, string key, TimeSpan? expiry, TimeSpan? retryTimeout)
        {
            DataCacheLock dataCacheLock = new DataCacheLock(db, key, expiry);
            Debug.WriteLine(dataCacheLock.Key.ToString() + ":" + dataCacheLock.Value.ToString());
            Func<Task<bool>> task = async () =>
            {
                try
                {
                    return await _db.LockTakeAsync(dataCacheLock.Key, dataCacheLock.Value, dataCacheLock.Expiry ?? TimeSpan.MaxValue);
                }
                catch
                {
                    return false;
                }
            };

            await RetryUntilTrueAsync(task, retryTimeout);
            return dataCacheLock;
        }
        public void Dispose()
        {
            Debug.WriteLine("release the lock:" + Value);
            _db.LockReleaseAsync(Key, Value);
        }
    }
    private static readonly Random _random = new Random();
    private static async Task<bool> RetryUntilTrueAsync(Func<Task<bool>> task, TimeSpan? retryTimeout)
    {
        int i = 0;
        DateTime utcNow = DateTime.UtcNow;
        while (!retryTimeout.HasValue || DateTime.UtcNow - utcNow < retryTimeout.Value)
        {
            i++;
            if (await task())
            {
                return true;
            }
            var waitFor = _random.Next((int)Math.Pow(i, 2), (int)Math.Pow(i + 1, 2) + 1);
            Debug.WriteLine(waitFor);
            await Task.Delay(waitFor);
        }
        throw new TimeoutException(string.Format("Exceeded timeout of {0}", retryTimeout.Value));
    }
}


texts:
So, my question is more of a 'best practices' question rather than a question with a particular aim. This is my current understanding of PHP factories and how to incorporate them into a project using PDOs and dependency injection. I'm pretty new at this and I still don't understand a lot about this subject. As such, I really don't know if I'm doing this quite right. Could someone point me in the right direction?

<?php
class PDOSettings_Factory {
    private function __construct() {}
    public static function build(Array $args = NULL) {
        $settings = array();
        // Set default values.
        $settings["dbType"] = 'mysql';
        $settings["dbName"] = 'test';
        $settings["host"] = 'localhost';
        $settings["user"] = 'guest';
        $settings["pass"] = '1234';
        // If keys are the same, they will be overwritten.
        if(isset($args)) {
            foreach($args as $key => $val) {
                $settings[$key] = $val;
            }
        }
        // Return setings.
        return $settings;
    }
}

$settings = PDOSettings_Factory::build();

class PDOConnection_Factory {
    private function __construct() {}
    public static function build($args) {
        // Set up PDO connection
        if(!isset($args)) {
            return NULL;
        } else {
            $statement =
                $args['dbType'].':'.
                'host='.$args['host'].';'.
                'dbname='.$args['dbName'];
            try {
                $dbh = new PDO(
                    $statement,
                    $args['user'],
                    $args['pass']);
                $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                // Return DBH
                return $dbh;
            } catch (PDOException $e) {
                echo 'Error: ',  $e->getMessage(), "\n";
            }
        }
        return NULL;
    }
}

And how to use the factories:

class demo {
    private $dbh = NULL;
    public function set($args) {
        if (!isset($args)) {return FALSE;}
        else {
            $this->dbh = $args;
            return TRUE;
        }
    }
    public function __construct($args = NULL) {
        $this->set($args);
    }

    public function doSomething() {
        // Set SQL command here.
        $sql = 'SELECT * FROM test';

        $results = $this->dbh->prepare($sql);
        // Perform param binds here.
        $results->execute();
        return $results;
    }
}

$db = PDOConnection_Factory::build($settings);

$test = new demo($db);
foreach ($test->doSomething() as $row) {print_r($row[0].PHP_EOL);}
?>


texts: Compose in Javascript - Go ahead with this example?

texts:
I'm trying to use the good parts of Javascript and dont follow the classical inheritance.
I studied and created this example of compose in Javascript, https://gist.github.com/fernandoperigolo/7789866.

My question is. You think this example have a good implementations of composition? Can i go ahead with it? If not, What you suggest?

(function(){
  // Adding compose to Function prototype
  Function.prototype.compose = function(argFn) {
    var fnToCall = this;
    return function() {
      // This line is really complex and i don't know exactly what this line do
      return fnToCall.call(this, argFn.apply(this,arguments));
    }
  }

  // Eletronic atributes and methods
  var asEletronic = function(){
    this.voltage = '220v';
    this.power = false;
    this.switchPower = function(){
      if (this.power === true) {
        this.power = false;
        console.info('Eletronic are off now.');
      }else{
        this.power = true;
        console.info('Eletronic are on now.');
      };
    }
    return this;
  };

  // Sound Reproducer atributes and methods
  var asSoundReproducer = function(){
    this.watts = 60;
    this.playSound = function(sound){
      console.info('Playing the sound: '+sound);
    };
    return this;
  };
  // All sound reproducer is a eletronic
  // Composing first level
  asSoundReproducer = asSoundReproducer.compose(asEletronic)

  // Micro System atributes and methods
  // Not used, just example
  var asMicroSystem = function(){
    this.cd = false;
    this.mp3 = true;
    return this;
  };

  // TV atributes and methods
  var TV = function(){
    this.pol = 42;
    this.hdmi = true;
    return this;
  };

  // Compose a TV with full resources
  // Compose second level, asSoundReproducer is a composed object
  // This line looks me strange...
  TV = TV.compose(asSoundReproducer);

  // Create a new TV
  var myTV = new TV();

  // Looking my TV
  console.log(myTV);

  // Call a Eletronic method
  myTV.switchPower();

  // Call a Sound Reproducer method
  myTV.playSound('guitar.mp3');
})();


texts:
I made a cool roll-over in CSS which displays an animated GIF when the parent is hovered.

Codepen

The problem is that I will have about 40 .day like that, all playing the animated GIF behind the circle at any time. I'm not sure that any browser/computer/connection can handle that much.

I tried to figure out a solution:

$( ".day" ).mouseenter(function() {
    $( ".play" ).append( "<img src="http://media.giphy.com/media/5Vb7xQB7Z3ScE/giphy.gif">" );
});

But I'm not sure if it will be better.

If someone as any idea to enhance that code, it would be really appreciated.

(The gif is just a sample.)


texts: Pivot pandas DataFrame while removing index duplicates

texts:
The goal of my code is to pivot a pandas DataFrame which is shown below. The idea is to use the Individual column as the column IDs and the VAF column as the values. I would like to combine the data such that the values from the columns Loc, Change, Chrom are used as the new index. To do this I made two new columns, newindex, and uniques in order to remove duplicates and then pivot.

Original DataFrame:

  Chrom        Loc WT Var Change ConvChange  AO     DP          VAF IntEx  \
0  chr1  115227855  T   A    T>A        T>A   5  19346  0.000258451  TIII
1  chr1  115227855  T   C    T>C        T>C   4  19346  0.000206761  TIII
2  chr1  115227856  C   T    C>T        C>T  14  19377  0.000722506  TIII
3  chr1  115227857  C   A    C>A        C>A   3  19377  0.000154823  TIII
4  chr1  115227857  C   T    C>T        C>T  15  19377  0.000774114  TIII

    Gene Upstream Downstream Individual          newindex             uniques
0  TIIIa        T          C          1  115227855T>Achr1  115227855T>Achr1_1
1  TIIIa        T          C          1  115227855T>Cchr1  115227855T>Cchr1_1
2  TIIIa        T          C          1  115227856C>Tchr1  115227856C>Tchr1_1
3  TIIIa        C          A          1  115227857C>Achr1  115227857C>Achr1_1
4  TIIIa        C          A          1  115227857C>Tchr1  115227857C>Tchr1_1

Code:

x = x.set_index(['uniques'])
x = x[~x.index.duplicated(keep='first')]
x = x.pivot(index='newindex', columns='Individual', values='VAF')

So in the above code I set the new index that uses the uniques column that is the same as the newindex column but with the values from Individual appended. Then remove the duplicate indices, and finally pivot into the final form shown below.

Individual                  1            2            3            4  \
newindex
106155152T>Achr4  0.000120685  0.000383835  0.000383224  0.000136617
106155152T>Cchr4  0.000603427  0.000575753  0.000694594  0.000461081
106155152T>Gchr4         None         None  0.000143709  6.83083e-05
106155153G>Achr4         None  0.000355969  0.000239257  0.000392398
106155153G>Tchr4         None  5.47645e-05         None  3.41215e-05

Individual                  5            6            7
newindex
106155152T>Achr4  0.000403506  0.000443759  0.000477926
106155152T>Cchr4  0.000560425  0.000570547   0.00155326
106155152T>Gchr4         None  8.45255e-05         None
106155153G>Achr4  0.000179127  0.000274534  0.000298436
106155153G>Tchr4  6.71727e-05         None         None

To clarify, I'm guessing there is probably a much more efficient way of making the new indexes that don't contain duplicates than making the newindex and uniques columns like I do.


texts: Dictionary lookup of non-nullable struct into nullable destination

texts:
I've got an IDictionary<SomeT, DateTime> that does not always contain the desired key-value pair. For that reason, a target method expects a DateTime? that the default TryGetValue method cannot provide a value for directly, because of the added ?.

I've written this generic extension with main emphasis on the parameter out TValue? value.

public static bool TryGetValue<TKey, TValue>(
    this IDictionary<TKey, TValue> that,
    TKey key,
    out TValue? value) where TValue : struct
{
    TValue output;
    if (that.TryGetValue(key, out output))
    {
        value = output;
        return true;
    }
    else
    {
        value = null;
        return false;
    }
}

Example use:

DateTime? nearestDateUtc; // The standard TryGetValue would not allow '?' here.
if (!nearestDatesUtc.TryGetValue(company, out nearestDateUtc)) { ... }

Based on this, my question is then; is there a more idiomatic way to extract (non-null) structs into nullable destinations than the solution I implemented? And if not, is the name TryGetValue confusing? C# developers might expect something very specific about exactly this name. In that case, what would a better name be?

An error could easily occur as the overload comes down to the presence of a single question-mark in a variable's type declaration and would mean the difference between null and default(DateTime).


texts:
I'm developing a desktop app that will scan a user's system for mp3 files and send their whole collection to a website. I'm assuming the best file format for sending this data to a server would be XML -- although correct me if I'm wrong.

Can someone kindly comment on whether the formatting of the sample XML file below looks okay? Thanks!

<?xml version="1.0" encoding="utf-8"?>
<collection>
    <artist name="Michael Jackson">
        <track>Beat It</track>
        <track>Thriller</track>
    </artist>
    <artist name="The Beatles">
        <track>Hey Jude</track>
        <track>Yellow Submarine</track>
    </artist>
    <artist name="Eminem">
        <track>Lose Yourself</track>
        <track>Without Me</track>
    </artist>
</collection>


texts:
I've written some code that is suppose to read socket all the time and when needed return the partial data from it. I just want the response to send a command. It works, but this is a bit messy implementation.

Is it possible to write it better?

public StringBuilder message = new StringBuilder();
private BufferedReader reader;
private Socket socket;
public boolean writing = true;
public boolean wantToRead = false;

public String getMessage() {
        synchronized (message) {
            while (writing) {
                try {
                    System.out.println("waiting");
                    wantToRead = true;
                    message.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("take the resource");
            writing = true;
            return message.toString().substring(0, message.toString().lastIndexOf("\n"));
        }
    }

@Override
    public void run() {
        int c;
        try {
            while((c = reader.read()) != -1) {
                synchronized(message) {
                    message.append(Character.toString((char) c));
                    if(!reader.ready()) {
                        System.out.println("end of response");
                        if(wantToRead) {
                            writing = false;
                            wantToRead = false;
                            message.notify();
                        }
                    }
                }
            }
            System.out.println("zamykam socket");
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


texts: Allowing users to subscribe to categories

texts:
I am working on a Rails 3 application, and am having some trouble with my user/edit view. In this application, Users can subscribe to Categories. Users and Categories have a has_and_belongs_to_many relationship through a join table (categories_users).

In my user/edit view, I need to display a list of checkboxes for the various categories so the user can edit his subscriptions. I am using the following code to achieve this:

  <% Category.roots.order('name ASC').each do |category| %>

      <li class="parent <%= category.name %>">
        <%= check_box_tag "user[category_ids][]", category.id, @user.categories.include?(category) %> <%= category.name %>

      <ul id="children-<%= category.id %>" class="children-list">
        <% category.children.order('name ASC').each do |child| %>
          <li class="child <%= child.name %>">
            <%= check_box_tag "user[category_ids][]", child.id, @user.categories.include?(child) %> <%= child.name %>

        <% end %>

  <% end %>

The Category model uses the ancestry gem for hierarchy, which is there the roots and children methods come from. Roots returns all the parent categories, and children returns all of the sub-categories for a given parent.

The really problematic part of this code seems to be @user.categories.include?(child) which is running 81 separate queries (one for each child category). This line is used to check if the category is currently subscribed to by the user -- if so, the checkbox is marked checked. Is there a better/faster way to accomplish this?

For reference, here is the join table's schema definition - I tried to put an index on the foreign keys thinking it would speed things up, but this is still very slow compared to the rest of my app.

create_table "categories_users", :id => false, :force => true do |t|
  t.integer "category_id"
  t.integer "user_id"
end

add_index "categories_users", ["category_id"], :name => "index_categories_users_on_category_id"
add_index "categories_users", ["user_id"], :name => "index_categories_users_on_user_id"


texts:
I have an object (ShoppingCart) that has a list of CartItems, which contains the related Product and the quantity bought.

public class ShoppingCart extends BaseEntity {

    @OneToMany(mappedBy = "shoppingCart", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<CartItem> cartItems = new ArrayList<>();

    @DateTimeFormat(pattern = "dd/MM/yyyy hh:MM:ss")
    private LocalDateTime dateTime;

    @Enumerated
    private PaymentMethod paymentMethod = PaymentMethod.CASH;

public class CartItem extends BaseEntity {

    @ManyToOne
    private Product product;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn
    private ShoppingCart shoppingCart;

public class Product extends BaseEntity {

    @NotEmpty
    private String name;

    private double price;

    private int quantity;

I have a view that sums all shopping carts, and I don't know if I should store that sum inside ShoppingCart entity, or iterate to find the sum.
Here's the code, right now I'm iterating.

@GetMapping("/")
    public String getProduct(@ModelAttribute("reportDto") ReportDto reportDto, Model model) {

        double total = 0, cash = 0, credit = 0, debit = 0;
        int quantity;
        List<ShoppingCart> results;
        if (reportDto.getBeginDate() == null || reportDto.getEndDate() == null) {
            results = shoppingCartService.findAll();
        } else {
            results = shoppingCartService.findByDateTimeBetween(reportDto.getBeginDate(), reportDto.getEndDate());
        }
        total = results.stream()
                .mapToDouble(shoppingCart -> shoppingCart.getCartItems().stream()
                        .mapToDouble(cartItem -> cartItem.getProduct().getPrice() * cartItem.getQuantity()).sum())
                .sum();
        quantity = results.stream().mapToInt(
                shoppingCart -> shoppingCart.getCartItems().stream().mapToInt(cartItem -> cartItem.getQuantity()).sum())
                .sum();

        cash = results.stream().filter(shoppingCart -> shoppingCart.getPaymentMethod().isCash())
                .mapToDouble(shoppingCart -> shoppingCart.getCartItems().stream()
                        .mapToDouble(cartItem -> cartItem.getProduct().getPrice() * cartItem.getQuantity()).sum())
                .sum();

        credit = results.stream().filter(shoppingCart -> shoppingCart.getPaymentMethod().isCredit())
                .mapToDouble(shoppingCart -> shoppingCart.getCartItems().stream()
                        .mapToDouble(cartItem -> cartItem.getProduct().getPrice() * cartItem.getQuantity()).sum())
                .sum();

        debit = results.stream().filter(shoppingCart -> shoppingCart.getPaymentMethod().isDebit())
                .mapToDouble(shoppingCart -> shoppingCart.getCartItems().stream()
                        .mapToDouble(cartItem -> cartItem.getProduct().getPrice() * cartItem.getQuantity()).sum())
                .sum();
        model.addAttribute("quantity", quantity);
        model.addAttribute("cash", cash);
        model.addAttribute("credit", credit);
        model.addAttribute("debit", debit);
        model.addAttribute("total", total);
        return "reports/reports";
    }

Also, any feedback regarding the code will be appreciated!


texts: Efficiency of a linq query on a nested structure

texts:
For a survey website I've written this query to show the survey results, with a percentage for each chosen answer:

SurveyResultViewModel srvm =
    (from s in _context.Surveys
        where s.Id == id

        select new SurveyResultViewModel
        {
            Title = s.Title,
            ResponseCount = s.Results.Count,
            Questions = from q in s.Questions
                select new QuestionResultViewModel
                {
                    Text = q.Text,
                    Answers = from a in q.Answers
                        select new AnswerResultViewModel
                        {
                            Text = a.Text,
                            SelectedCount = a.Results.Count,

                            SelectedPercentage =
                            (double)a.Results.Count / q.Answers.Select(an => an.Results.Count).Sum()
                        }
                }
        }).Single();

However, I do think it can be improved, just not sure how. It runs 4 queries for every question in the survey because of the line that calculates the percentage.


texts:
https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/601/

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Please review for performance.

using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace RecurssionQuestions
{
    /// <summary>
    /// https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/601/
    /// </summary>
    [TestClass]
    public class PascalTriangleTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            IList<IList<int>> result = PascalTriangle.Generate(5);
            IList<IList<int>> expected = new List<IList<int>>();
            expected.Add(new List<int> { 1 });
            expected.Add(new List<int> { 1, 1 });
            expected.Add(new List<int> { 1, 2, 1 });
            expected.Add(new List<int> { 1, 3, 3, 1 });
            expected.Add(new List<int> { 1, 4, 6, 4, 1 });
            for (int i = 0; i < expected.Count; i++)
            {
               CollectionAssert.AreEqual(expected[i].ToList(), result[i].ToList());
            }
        }
    }

    public class PascalTriangle
    {
        public static IList<IList<int>> Generate(int numRows)
        {
            IList<IList<int>> result = new List<IList<int>>();
            if (numRows == 0)
            {
                return result;
            }
            List<int> row = new List<int>();
            row.Add(1);
            result.Add(row);
            if (numRows == 1)
            {
                return result;
            }

            for (int i = 1; i < numRows; i++)
            {
                var prevRow = result[i - 1];
                row = new List<int>();
                row.Add(1);
                for (int j = 0; j < prevRow.Count - 1; j++)
                {
                    row.Add(prevRow[j] + prevRow[j + 1]);
                }
                row.Add(1);
                result.Add(row);
            }
            return result;
        }
    }
}


texts: I want to check neighborhoods of cell in two dimensional array in C++

texts:
I want to write a function which will return all possible/valid 'X' moves around my Target cell depending on it position inside the following two dimensional array.

X X X
X T X
X X X

But my 2 concerns are:

the performance because my "game field" will be 1000x1000 cells and each cell must be checked in the game turn. So creating 1,000,000 vectors (in one turn) is a bad idea? Maybe I should use a different data structure for it?
logic inside the function is not too complicated?

enum dir {topL, top, topR, l, r, botL, bot, botR};

std::vector<dir> neighborhood(int x, int y, int size)
{
    std::vector<dir> direction;
    direction.clear();

    if(x < size -1){direction.push_back(bot);}
    if(y < size -1){direction.push_back(r);}
    if(x < size -1 && y < size -1){direction.push_back(botR);}
    if(x > 0){direction.push_back(top);}
    if(y > 0){direction.push_back(l);}
    if(x < size -1 && y != 0){direction.push_back(botL);}
    if(x > 0 && y < size -1){direction.push_back(topR);}
    if(x > 0 && y > 0){direction.push_back(topL);}
    return direction;
}


texts: Discrete event simulation with variable intervals

texts:
I've built a discrete event simulation system, similar to the bank problem presented on the wikipedia page but with a key difference.

Let's say, that a TELLER can service two CUSTOMERS at the same time, and that the CUSTOMER-DEPARTURE time depends upon the number of CUSTOMERS a TELLER is servicing concurrently; I need to manage the dynamic CUSTOMER-DEPARTURE event scheduling when the number of concurrently served CUSTOMERS changes.

Consider the following example, where the servicing time for a single customer is of 4 time intervals and is doubled when the teller is servicing two customers at the same time:

t=0  CUSTOMER-ARRIVAL (1)
t=1  TELLER-BEGINS-SERVICE (1) --> schedules CUSTOMER-DEPARTURE (1) at t_a=5
...
t=3  CUSTOMER-ARRIVAL (2)
t=4  TELLER-BEGINS-SERVICE (1) --> teller is now servicing two customers:
                                   - reschedule CUSTOMER-DEPARTURE (1) to t_b=6
                                   - schedule CUSTOMER-DEPARTURE (2) at t_c=12
...
t=6  CUSTOMER-DEPARTURE (1)    --> teller is now servicing only one customer:
                                   - reschedule CUSTOMER-DEPARTURE (2) at t_d=9
...
t=9  CUSTOMER-DEPARTURE (2)

The times are calculated using this formula:

t = t_current + (4 - completed) * customer_count

Which gives these results for the values used above:

t_a = 1 + (4 - 0) * 1 = 5
t_b = 4 + (4 - 3) * 2 = 6
t_c = 4 + (4 - 0) * 2 = 12
t_d = 6 + (4 - 1) * 1 = 9

I came up with the following code in Python; is there something you would have done differently?

import heapq

class Simulator(object):

    def __init__(self):
        self.queue = []
        self.time = 0

    def schedule(self, time, callback, *args, **kwargs):
        """
        Schedules an event to be executed at a later point in time.
        ``callback`` is a callable which executed the event-specific behavior;
        the optional ``args`` and ``kwargs`` arguments will be passed to the
        event callback at invocation time.

        Returns an object which can be used to reschedule the event.
        """
        assert time > self.time
        event = [time, True, callback, args, kwargs]
        heapq.heappush(self.queue, event)
        return event

    def reschedule(self, event, time):
        """
        Reschedules ``event`` to take place at a different point in time
        """
        assert time > self.time
        rescheduled = list(event)
        event[1] = False
        rescheduled[0] = time
        heapq.heappush(self.queue, rescheduled)
        return rescheduled

    def run(self):
        """
        Simple simulation function to test the behavior
        """
        while self.queue:
            time, valid, callback, args, kwargs = heapq.heappop(self.queue)
            if not valid:
                continue
            self.time = time
            callback(*args, **kwargs)

def event(id, simulator, scheduled, rescheduled=None):
    if rescheduled is None:
        print "Event #{0}: scheduled at {1} and fired at {2}".format(id,
                scheduled, simulator.time)
    else:
        print "Event #{0}: scheduled at {1}, rescheduled at {2} and fired " \
                "at {3}".format(id, scheduled, rescheduled, simulator.time)

s = Simulator()
e1 = s.schedule(5, event, 1, s, 5)
e2 = s.schedule(7, event, 2, s, 7, 12)
e3 = s.schedule(9, event, 3, s, 9)
s.reschedule(e2, 12)
s.run()


texts:
I have the following code:

const arr = Array.from({length: 5}, (_, i) => i + 1);
const finalArray = [];
for (let i = 0; i < arr.length; i++) {
   for (let j = 0; j < arr.length; j++) {
       finalArray.push(arr[i] + '-' + arr[j])
   }
}

console.log(finalArray);

Which creates an array of range 1 => 5, and returns an array with a combination of all elements in the original array.
This code runs in O(n²), is it possible to make it more efficient?


texts: Get specific lines from a huge text file

texts:
I had a 50 Gb text file (ca. 45 mln lines) and needed to extract about 1500 lines from it. I knew their indices, that is, line numbers. Those 1500 lines were spread across the whole file up to the very end. To accomplish this, I wrote a simple Perl script. It worked and was quite fast: it finished in about 4-5 minutes on a low-end "business" laptop (but with an SSD).

Question 1: Is the code sensible and well-written?
Question 2: Could the performance be improved somehow?

#!/bin/perl
#
# Get lines from a file using line numbers from a second file
# Syntax
# getlinesfromfile.pl <source-file> <index-file> <output-file>
#
# Index file contains line numbers, one per line
# Example:
#
# 1
# 5
# 17
# 73
# 31337

use strict;
use warnings;

my $version = "1.0.4";
my $date_released = "4 December 2019";
print "\nGet lines from file. Version $version released on $date_released\n";

my ($source_file, $idx_file, $output_file) = @ARGV;
if (not defined $source_file or not defined $output_file or not defined $idx_file) {
    print "Parameters missing. Usage:\n\t$0 <source_file> <idx_file> <output_file>";
    exit;
}

open(my $i_fh, '<', $source_file)
    or die "FAILED to open '$source_file'!";
open(my $idx_fh, '<', $idx_file)
    or die "FAILED to open '$idx_file'!";
open(my $o_fh, '>', $output_file)
    or die "FAILED to open '$output_file'!";

# Read in indices
$/ = "\r\n";
my %indices;
while (my $line = <$idx_fh>) {
    chomp $line;
    $indices{$line} = 1;
}
close $idx_fh;
my $count_indices = scalar keys %indices;

my $msg_intro = <<"END";
Input filename: '$source_file'
Index filename: '$idx_file'
Output filename: '$output_file'

Indices: $count_indices

END

print $msg_intro;

my $lines_found = 0;
my $lines_parsed = 0;
$/ = "\n";
while (my $line = <$i_fh>) {
    chomp $line;
    $lines_parsed++;
    if (defined $indices{$lines_parsed}) {
        print $o_fh $line, "\r\n";
        $lines_found++;
    }
}
close $o_fh;
close $i_fh;
print ("Parsed $lines_parsed lines, found $lines_found matches.\n");


texts: More succinct / ideal solution to Project Euler #22

texts:
"Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?"

I'm relatively new to clojure, and this is what I came up with:

(def names (sort (map (fn[x] (replace x #"\"" "")) (split (slurp "/users/calvinfroedge/Downloads/names.txt") #","))))

(loop [i 0 total 0]
  (if (not= i (count names))
    (recur (inc i) (+ total (* (inc i) (reduce + (map (fn[x] (- (int x) 64)) (nth names i))))))
    total)

I read somewhere that doseq is preferred to loop/recur, but it wasn't apparent to me how to comprehensibly AND idiomatically approach this problem without using an explicit loop with an incrementing value.

Am I missing something?


texts: Alternative to setInterval and setTimeout

texts:
JavaScript's setTimeout() and setInterval() are evil and not precise:

Both functions have a delay of a varying quantity of milliseconds.
Both functions are very resource-intensive because they execute several times every second.

A new alternative is window.requestAnimationFrame(), which is less resource-intensive, disabled on page blur, and does not slow down other stuff. This makes it the perfect substitute for a modern setTimeout() and setInterval().

Description

These functions use requestAnimationframe() to check if the time has passed
based on the elapsed Time calculated from Date.now().  The time passed is more precise than the native functions and theoretically less resource-intensive.  Another advantage (or disadvantage) is that the functions are not executed on page blur.

Good for: animations, visual effects

Bad for: timers, clock

RafTimeout

window.rtimeOut=function(callback,delay){
 var dateNow=Date.now,
     requestAnimation=window.requestAnimationFrame,
     start=dateNow(),
     stop,
     timeoutFunc=function(){
      dateNow()-start<delay?stop||requestAnimation(timeoutFunc):callback()
     };
 requestAnimation(timeoutFunc);
 return{
  clear:function(){stop=1}
 }
}

RafInterval

window.rInterval=function(callback,delay){
 var dateNow=Date.now,
     requestAnimation=window.requestAnimationFrame,
     start=dateNow(),
     stop,
     intervalFunc=function(){
      dateNow()-start<delay||(start+=delay,callback());
      stop||requestAnimation(intervalFunc)
     }
 requestAnimation(intervalFunc);
 return{
  clear:function(){stop=1}
 }
}

Usage

var interval1,timeout1;
window.onload=function(){
 interval1=window.rInterval(function(){console.log('interval1')},2000);
 timeout1=window.rtimeOut(function(){console.log('timeout1')},5000);
}

/* to clear
interval1.clear();
timeout1.clear();
*/

Demo

jsFiddle

Questions

Normally I don't write functions inside functions, but in this case it's probably a good solution. What about memory leaks if I create hundreds of these time-based functions?
Is there a better solution to clear those functions?
For heavy animations and multiple intervals and timeouts, I was thinking to activate a single requestAnimationFrame() loop which would check for intervals and timeouts inside a previously stored array... (but I think there should be no difference if there is just one requestAnimationframe or multiple). So how do the browsers handle those multiple requestAnimationframes()?

Note:

If the code above does not work here is the original code:

window.rInterval=function(a,b){var c=Date.now,d=window.requestAnimationFrame,e=c(),f,g=function(){c()-e<b||(e+=b,a());f||d(g)};d(g);return{clear:function(){f=1}}}//callback,delay
window.rtimeOut=function(a,b){var c=Date.now,d=window.requestAnimationFrame,e=c(),f,g=function(){c()-e<b?f||d(g):a()};d(g);return{clear:function(){f=1}}}


texts: Programmatically using `exec` to load files

texts:
I'm making a command line interface (CLI) role playing tool that tracks the state of the world, storing characters, monsters, etc as text files so their data can be edited directly if needed (free Vim UI yay). This means that every game loop, I need to reload the files.
Note: Direct editing implies no pickling. Also, I may eventually add functions to these files so I can use duck typing.
Since filenames are pulled into Python as strings, I felt a straightforward approach would be to use exec.
I'm concerned though because learning materials rarely discuss using this function responsibly.
Instead they warn against its use for security reasons.
Below is the directory, two test character files with simple data, and the main program.
# Directory
dnd\
    main.py
    entities\
        char01.py
        char02.py

# File: char01.py
name = 'Gandalf Potter'

# File: char02.py
name = 'Obi-wan Picard'

My solution:

For this MWE, first check whether the files are loaded. For the first loop, they won't be loaded yet. By the second loop, the files
should load and the loop will exit to avoid infinity.
Read filenames from directory.
Check if filename is in globals().
Depending on the check, either import or reload the module with
exec.

# File: main.py

import importlib
import os

def main():
    while True:
        if test_load(): return  # Run until files load
        files = get_files('entities')
        load_files(files, 'entities')

def get_files(dir):
    return (file for file in os.listdir(dir)
        if not file.startswith('__'))  # Ignore __pycache__

def load_files(files, dir):
    for f in files:
        module = f.strip('.py')
        if module in globals():
            exec(f'importlib.reload({module})')
        else:
            exec(f'from {dir} import {module}')
    modules = {k: v for k, v in locals().items()
                    if isinstance(v, type(os))}
    globals().update(modules)

def test_load():
    try:
        char01.name
        char02.name
        print('loaded')
        return True
    except NameError:
        print('not loaded')
        return False

main()

Questions:

Is there a better approach?

Using exec is frowned upon for security reasons, however I want
to start using it more often because code can be treated as strings, which allows the code to be treated as data that can be manipulated, substituted, or changed.
However, I also want to be mindful of vulnerabilities.

Is there a better way of pulling out only the modules than using if isinstance(v, type(os))?

What is everyone's opinion of using the globals() function like
this to do imports programmatically from within functions?

I used DICT.update() to add imports to globals(), however I
wanted to be fancy and use Python39's new dictionary union operator
|=. Unfortunately, lines like

globals() |= {k: v for k, v in locals().items() if isinstance(v, type(os))}

don't work because a function call like globals() can't be assigned
to. It would work if I did the following:
globals_ = globals()
globals |= {k: v for k, v in locals().items() if isinstance(v, type(os))}

but at that point, it'd be simpler to just stick with DICT.update().

I welcome any other suggestions and criticisms.


texts: What a crooked way to compute the next straight string (advent of code 11)

texts:
This year I have been participating in the Advent of Code series of challenges, and it just so happened that I'd be doing them in Javascript. Not my usual weapon of choice, but I do have some experience in it.

Day 11 asks us to find the next valid password given a set of three requirements. The idea is that you'd be incrementing the given password until it matched all three criteria, but I wanted to do something more efficient. But the task "find the next string that has a straight of length three" turned out a bit more difficult than I anticipated, and the code happened to be a bit more convoluted than I'd like, whooping 38% of the whole challenge.

A straight is defined as

  like abc, bcd, cde, and so on, up to xyz. They cannot skip letters; abd doesn't count.

My main concern is that my code isn't "obviously bug-free" and that the logic is hard to follow. How can I clean my logic up without sacrificing performance? Of course, reviewers are welcome to comment on other aspects of the code as well.

So, here we go:

//jshint esversion: 6

function nextChar(x){return String.fromCharCode(x.charCodeAt(0)+1);}
var requirements = [
  {name: "straight3", nextMatch: function nextMatch(str){
    var prefix = str;
    while(prefix.length > 2){
      if(prefix === straighten(prefix)) return str;
      prefix = prefix.slice(0,-1);
    }
    prefix = str;
    while(true){
      if(prefix.length <= str.length - 3){
        return str.replace(/(.)([z]*)...$/, function(_, c, zs){
          return nextChar(c) + zs.replace(/z/g, 'a') + "abc";
        });
      } else if(prefix.match(/[yz]..$|xz.$/)) prefix = prefix.slice(0,-1);
      else if(str < straighten(prefix)) {
        var rv = straighten(prefix);
        while(straighten(rv).slice(0,-1) === straighten(rv.slice(0,-1))) rv = rv.slice(0,-1)
        while(rv.length < str.length) rv += 'a';
        return rv;
      } else {
        prefix = prefix.replace(/.(?=..$)/, nextChar).replace(/..$/, "aa");
        while(prefix.length < str.length) prefix += 'a';
        return nextMatch(prefix);
      }
    }
    function straighten(str){
      var ord = str.slice(-3).charCodeAt(0);
      return str.slice(0,-3) + String.fromCharCode(ord, ord+1, ord+2);
    }
  }},
  {name: "noIOL", nextMatch: function(x){
    return x.replace(/([iol])(.*)$/g, function(_, c, xs){
      return nextChar(c) + xs.replace(/./g, 'a');
    });
  }},
  {name: "twoPairs", nextMatch: function(str){
    if(str.match(/(.)\1.*(.)\2/)) return str;
    else if(str.match(/(.)\1../)){
      var rv = str.slice(0,-2) + nextPair(str.slice(-2));
      return rv.replace(/(.)\1\1$/, "$1$1a");
    } else {
      var rv = str.slice(0,-4) + nextPair(str.slice(-4,-2)) + "aa";
      return rv.replace(/(.)\1\1aa$/,"$1$1aaa");
    }
    function nextPair(x){
      if(x[0] > x[1]) return x[0] + x[0];
      else return nextChar(x[0]) + nextChar(x[0]);
    }
  }}
];

var pwd = "hxbxxzaa";
var toSat = requirements.length;
while(toSat){
  var oldPwd = pwd;
  pwd = requirements[0].nextMatch(pwd);
  if(pwd === oldPwd){
    toSat --;
  }else{
    toSat = requirements.length;
    console.log(oldPwd + " -> " + requirements[0].name + " -> " + pwd);
  }
  if(pwd.match(/[^a-z]/)) throw "oops";
  requirements.push(requirements.shift());
}
console.log(pwd);


texts:
It's an exercise from a Swift-course I'm currently taking.

  You are given an array of integers.  Make an additional array named
  computedNumbers. computedNumbers should multiply each element in the
  numbers array by the next following element. The last element shall be
  multiplied by the first element.

  Example: If numbers was equal to ... [3, 1, 4, 2] ... then the
  computedNumbers should computed [3 x 1, 1 x 4, 4 x 2, 2 x 3], so that
  they become: [3, 4, 8, 6]

Here my solution:

var numbers = [45, 73, 195, 53]

var computedNumbers = [Int]()
let count = numbers.count
var i = 0

while i < count - 1 {
    computedNumbers.append(numbers[i] * numbers[i + 1])
    i = i + 1
}

computedNumbers.append(numbers[count - 1] * numbers[0])

print(computedNumbers)

It has passed the automated tests, but it isn't very elegant.

It there a better way to accomplish the task?

What should I have done different and why?

Looking forward to reading your comments and answers.


texts:
The problem I am trying to solve:

Given a string, split the string into two substrings at every possible point. The rightmost substring is a suffix. The beginning of the string is the prefix. Determine the lengths of the common prefix between each suffix and the original string. Sum and return the lengths of the common prefixes. Return an array where each element 'i' is the sum for the string 'i'. Example:

My Solution:
def commonPrefix(l):

    size=len(l)  #Finding number of strings
    sumlist=[]  #Initializing list that'll store sums
    for i in range(size):
        total=0  #Initializing total common prefixes for every string
        string=l[i]  #Storing each string in string
        strsize=len(string)  #Finding length of each string
        for j in range(strsize):
            suff=string[j:]   #Calculating every suffix for a string
            suffsize=len(suff)  #Finding length of each suffix
            common=0   #Size of common prefix for each length
            for k in range(suffsize):
                if(string[k]==suff[k]):
                    common=common+1
                else:
                    break   #If characters at equal positions are not equal, break
            total=total+common   #Update total for every suffix
        sumlist.append(total)   #Add each total in list
    return sumlist   #Return list

My solution takes up a lot of time, I need help with optimizing it.


texts: Summing same index values in 2D arrays in javascript

texts:
After solving a problem, I came to this conclusion.

let n = 10;
let array = [
  [1, 5, 3],
  [4, 8, 7],
  [6, 9, 1]
];
let answer = array.map((val) => new Float32Array(n).fill(val[2], val[0] - 1, val[1]));
console.log(Math.max(...answer.reduce((r, a) => a.map((b, i) => (r[i] || 0) + b), [])))

Okay, so what this does is it creates an array of n elements with the value of the third element from the index from the range of the first value to the second value.

Indexes start from 1 here.

Like for [1, 5, 3], (n = 10), it creates an array of 10 elements with the value 3 from the index 1 to the index 5 and else everything is just blank or 0.

Then for [4, 8, 7], (n = 10), it creates an array of 10 elements with the value 7 from the index 4 to the index 8 and else, everything is just blank or 0.

Then for [6, 9, 1], (n = 10), it creates an array of 10 elements with the value 1 from the index 6 to the index 9 and else, everything is just blank or 0.

Now we have to sum all the matching columns and return the maximum value, which I do by

Math.max(...answer.reduce((r, a) => a.map((b, i) => (r[i] || 0) + b), []))

Everything works fine and the test cases work but the program is not at all efficent, with refrence to this problem, my code just timeouts.

I think the problem is when I sum the values. That is what is taking the most memory.

What can be an alternate method to sum the same index array values? Being it the most efficient


texts: Creating readline() function, reading from a file descriptor

texts:
I've got a task to create a readline() function that would have the exact same behavior as read():

ssize_t read(int fd, void *buf, size_t count); (man read)

So it should return -1 on error and number of bytes read on success.
Also, if the function receives a string with multiple \n chars, it should return only the first line and store the rest for a future use.

I was scrolling through this article:
Reading a line ending with a newline character from a file descriptor

But I do not think the author had the same purpose - that is to work just as read()

I came up with this function:

//global buffer
char gBUF[BUFSIZ];

int readline2(int fd, char* buf){

    static char* resultBuffer = gBUF;
    int ret, mv;
    char temp[256];
    char* t;

    bzero(temp, sizeof(temp));

    t = strchr(resultBuffer,'\n');
    if(t != NULL){
        mv = t-resultBuffer+1;
        strncpy(temp,resultBuffer, mv);
        resultBuffer = resultBuffer + mv;

        temp[strlen(temp)] = '\0';
        strcpy(buf,temp);
        bzero(temp, sizeof(temp));
        ret = read(fd,&temp,256);
        temp[ret]='\0';
        strcat(resultBuffer,temp);

        return mv;
    }
    ret = read(fd,&temp,256);
    temp[ret]='\0';
    t = strchr(temp,'\n');
    mv = t-temp+1;
    strncpy(buf,temp,mv);

    strcat(resultBuffer,temp+mv);
    return ret;

}

and I mean, it works well, although I had some real struggles with pointers and copying addresses instead of values.

My question is, how to improve this? I still have a feeling there's something missing or that something could significantly improve it.

I guess I should put a while inside and check whether the read string actually has a \n char and only return when it does, right?

I also do not like the idea of a global buffer, maybe I should just create a class/struct, something like this:

struct {
char BUF[BUFSIZ];
char *p = BUF;
}dataStruct;

to store the buffer and a pointer to it, but I do not really know how I could use that properly

Thanks for any suggestions!

Reading max 256bytes is a purpose, that should be the max;

I could've probably added that this function is to be used after in a multiprocess/multithread client server project.
The server reads these lines from clients and should know what input came first, in what order the lines came, etc. The buffer should essentially work as a queue.


texts: Find two numbers that equal to target value

texts:
Background
Given some random array of numbers like [3, 5, -4, 8, 11, 1, -1, 6] and a target value 10, find two numbers within the array that equal to the target value.
Code
def two_Number_Sum(array, target):
    unique_number_set = set()
    for num in array:
        required_value = target - num
        if required_value in unique_number_set:
            return [num, required_value]
        else:
            unique_number_set.add(num)
    return []

print(two_Number_Sum([3, 5, -4, 8, 11, 1, -1, 6], 10))

I am wondering if I can make this answer more pythonic. I don't have a Python background so a lot of times I write code like Java or another language, and I figure it will be good practice to critique myself and write code that is more pythonic so it becomes natural.