texts:
I am new to functional programming. Just now I solved my first "real world" task using Haskell and now I'm wondering whether I got it "right" and what can be improved.

The problem arises from tensor calculations (I am a theoretical physicist), where I have the tensor product of \$\frac{n}{2}\$ identical symmetric tensors and I am looking for all indistinguishable distributions of \$n\$ indices, i.e. terms like \$\eta^{a c} \eta^{b e} \eta^{d f}\$.

The combinatorics is easy, there are \$(n-1)\times(n-3)\times\dots\times1\$ different terms and prescriptions to enlist them all are easy to conceive.

I implemented the following algorithm:

input: string of even length ("indices")

output: rose tree representing all permutations as described above, a node is a pair (my implementation: two-element list) of indices, each branch from root node to leaf is one permutation

recursive construction:
From string of length \$n\$ (example: "abcdef"), construct \$n-1\$ nodes and "remainders", where the first index of each node is the first index of the input string (example: [("ab", "cdef"), ("ac", "bdef"), ("ad", "bcef"), ("ae", "bcdf"), ("af", "bcde")]). Repeat with all "remainders".

Now this is my implementation in Haskell:

import Control.Applicative
import Data.Tree

--- given string of n indices a:is,
--- construct all (n-1) two-character
--- strings a:i:[] and the reduced
--- string of (n-2) remaining indices
--- undefined if n == 1
innerEtas :: String -> [(String, String)]
innerEtas (x:[]) = undefined
innerEtas (x:xs) = map (\a -> ([x, a], filter (/=a) xs)) xs
innerEtas [] = []

--- build up tree by recursive application
--- of innerEtas
buildEtas :: String -> Forest String
buildEtas [] = []
buildEtas xs = let ys = innerEtas xs
               in map (\(node, list) -> Node node $ buildEtas list) ys

--- flatten Tree to list of strings
treeToStrings :: Tree String -> [String]
treeToStrings (Node n []) = [n]
treeToStrings (Node n ts) = liftA2 (++) [n] (forestToStrings ts)

forestToStrings :: Forest String -> [String]
forestToStrings ts = concat $ map treeToStrings ts

--- build ansatz tree from n indices
ansatzEtas :: Integer -> Forest String
ansatzEtas n
  | n < 0 = undefined
  | n `mod` 2 /= 0 = undefined
  | otherwise = buildEtas $ take (fromIntegral n) ['a'..'z']

main = do
        putStrLn $ drawForest $ ansatzEtas 8
        print $ forestToStrings $ ansatzEtas 8
        print $ (forestToStrings $ ansatzEtas 26) !! 10000

I am really impressed by Haskells lazy evaluation, which in the last line allows me to obtain certain combinations of ['a'..'z'] without first calculating them all! So I believe I got this aspect right.

So my question is, did I make any style errors? Did I miss idioms of functional programming and Haskell which would make the code better in some ways? Are there issues with space or time?


texts:
I'm building a Java method to sum arithmetically two time periods, using the JodaTime library. My code works fine, but I think that it's possible optimize to reduce the time execution.

import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

public class Test {

    public static void main(String[] args)
    {
        String time1 = "08:00";
        String time2 = "08:00";

        System.out.println(Operation_Sum(time1,time2));
    }

    private static String Operation_Sum(String time1, String time2)
    {
        String output;
        long start = System.currentTimeMillis();

        if (time1.equals("00:00") && time2.equals("00:00"))
        {
            output = "00:00";
        }
        else if (time1.equals("00:00"))
        {
            output = time2;
        }
        else if (time2.equals("00:00"))
        {
            output = time1;
        }
        else
        {
            boolean sign_time1 = false;
            boolean sign_time2 = false;
            String[] time1_out, time2_out;

            boolean negative = false;
            String output_split[];

            if (time1.contains("-"))
            {
                time1_out = time1.split(":");
                time1_out[0] = time1_out[0].replace("-", "");
                time1_out[1] = time1_out[1].replace("-", "");
                time1 = time1_out[0] + ':' + time1_out[1];
                sign_time1 = true;
            }

            if (time2.contains("-"))
            {
                time2_out = time2.split(":");
                time2_out[0] = time2_out[0].replace("-", "");
                time2_out[1] = time2_out[1].replace("-", "");
                time2 = time2_out[0] + ':' + time2_out[1];
                sign_time2 = true;
            }

            PeriodFormatterBuilder builder = new PeriodFormatterBuilder();
            builder.minimumPrintedDigits(2);
            builder.printZeroAlways();
            builder.appendHours();
            builder.appendLiteral(":");
            builder.appendMinutes();
            PeriodFormatter pf = builder.toFormatter();

            Period period1 = pf.parsePeriod(time1);
            Period period2 = pf.parsePeriod(time2);
            Period normalized;
            Period total = null;

            if (sign_time1 && sign_time2)
            {
                total = period1.plus(period2);
                negative = true;
            }

            if (sign_time1 && !sign_time2)
            {
                total = period2.minus(period1);
            }

            if (!sign_time1 && sign_time2)
            {
                total = period1.minus(period2);
            }

            if (!sign_time1 && !sign_time2)
            {
                total = period1.plus(period2);
                negative = false;
            }

            normalized = total.normalizedStandard(PeriodType.time());
            output_split = pf.print(normalized).split(":");

            if (output_split[1].contains("-"))
            {
                output = output_split[0] + ":" + output_split[1].replace("-", "");
            }
            else
            {
                output = (negative ? "-" : "") + output_split[0] + ":" + output_split[1];
            }
        }

        long end = System.currentTimeMillis();

        System.out.println("exec time sum1: " +(end - start) + " ms");
        return output;
    }
}


texts:
For this project I'm targeting .NET 4.6 with Prism 6 as a toolkit to implement correct MVVM patterns.

The code below allows me to raise a dialog box with Yes, No, Cancel buttons. If the user clicks 'Yes' the content is saved then the tab item closed. If 'No' the tab item is only closed, and if 'Cancelled' then return, do not close anything.

However the dialog is only displayed if the content is dirty. If not just close it.

I feel like in its current sate it's very messy and could be cleaned up. Take a look below and tell me what you think.

internal class CloseTabAction : TriggerAction<Button>
{
    protected override void Invoke(object parameter)
    {
        var args = parameter as RoutedEventArgs;
        if (args == null) return;

        var tabItem = FindParent<TabItem>(args.OriginalSource as DependencyObject);
        if (tabItem == null) return;

        var tabControl = FindParent<TabControl>(tabItem);
        if (tabControl == null) return;

        var region = RegionManager.GetObservableRegion(tabControl).Value;
        if (region == null) return;

        var context = new NavigationContext(region.NavigationService, null);

        if (Implements<IRequestTabItemClose>(tabItem.Content, r => r.IsContentDirty(isDirty =>
        {
            if (isDirty)
            {
                if (Implements<IRequestTabItemClose>(tabItem.Content,
                    i => i.ConfirmCloseRequest((canSave, cancel) =>
                    {
                        if (cancel) return;
                        if (!region.Views.Contains(tabItem.Content)) return;
                        if (canSave)
                        {
                            i.SaveContent();
                            region.Remove(tabItem.Content);
                            return;
                        }
                        region.Remove(tabItem.Content);
                    })))
                    return;
            }
            region.Remove(tabItem.Content);
        }))) return;
    }

    private static T FindParent<T>(DependencyObject child) where T : DependencyObject
    {
        while (true)
        {
            var parentObject = VisualTreeHelper.GetParent(child);

            if (parentObject == null) return null;

            var parent = parentObject as T;
            if (parent != null) return parent;

            child = parentObject;
        }
    }

    private static T Implementor<T>(object content) where T : class
    {
        T implementor = content as T;
        if (implementor != null) return implementor;

        var element = content as FrameworkElement;
        if (element != null) implementor = element.DataContext as T;
        return implementor;
    }

    private static bool Implements<T>(object content, Action<T> action) where T : class
    {
        T target = Implementor<T>(content);
        if (target == null) return false;
        action(target);
        return true;
    }
}

Here are my custom interfaces:

public interface IRequestTabItemClose
{
    void ConfirmCloseRequest(Action<bool, bool> callback);
    void SaveContent();
    void IsContentDirty(Action<bool> callBack);
}

public interface ICloseConfirmation : INotification
{
    bool Confirmed { get; set; }
    bool Cancel { get; set; }
}

ViewModel:

    public bool IsDirty { get; set; }

    public virtual void ConfirmCloseRequest(Action<bool, bool> callback)
    {
        ClosePopupRequest.Raise(
            new CloseConfirmation {Title = "Confirm", Content = "Do you want to save this view before closing?"},
            r => { callback(r.Confirmed, r.Cancel); });
    }

    public virtual void SaveContent()
    {
        // Save stuff
    }

    public void IsContentDirty(Action<bool> callBack)
    {
        callBack(IsDirty);
    }


texts:
I have this piece of code in my Node.js API and I feel like it could (should) be optimized.

var apiRouter = express.Router();

apiRouter.route('/user/:username')
.put(function(req, res) {
    User.findOne({
        username: req.params.username
    }).exec(function(err, user) {
    if (err) {
        res.send(err);
    }
    if (!user) {
        res.json({
            success: false,
            message: 'User not found'
        });
    } else {
        // This is the part to optimize
        if (req.body.firstname) {
            user.firstname = req.body.firstname;
        }
        if (req.body.lastname) {
            user.lastname = req.body.lastname;
        }
        if (req.body.email) {
            user.email = req.body.email;
        }
        if (req.body.username) {
            user.username = req.body.username;
        }
        if (req.body.password) {
            // no worries about this, I hash the password before it is saved
            user.password = req.body.password;
        }

        user.save(function(err) {
            if (err) {
                res.send(err);
            }
            res.json({
                success: true,
                message: 'User updated'
            });
        });
    }
});

I use this to update my user. In the future I could (will) have way more parameters than these.

Is there a scalable solution?

I'm thinking about something like this:

var form = req.body;
user.firstname = form.firstname ? form.firstname : user.firstname;
user.lastname = form.lastname ? form.lastname : user.lastname;
// ...

Problem is that I'm not sure it is more scalable. I feel like it is just another way to write if statements.


texts: Extending window.location give access to query string elements

texts:
I am attempting to add a property to access the query string elements on the window and am looking for feedback on this implementation.

if (!window.location.hasOwnProperty("query"))
  Object.defineProperty(window.location, "query", {
      get(){
        var query = document.location.search.substr(1);
        if (query === undefined || query === "")
          return {};

        var pairs = query.split("&");

        var mapped = pairs.map(function(v) {
          var temp = v.split("=");
          return { key: temp[0], val: temp[1] };
        });

        var obj = mapped.reduce(function(total, current){
            total[current.key] = decodeURIComponent(current.val)
                                         .replace(/\+/g, " ");
            return total;
        }, {});

        return obj;
      }
  });

Then I could us it like this

var myVal = window.location.query.customerId


texts:
I've seen other implementations around, but they seem pretty complicated. This seems to work for me, but is there anything I'm missing? Also, any tips on how I can improve the quality of the code is appreciated.

#include <iostream>
#include <vector>

template<typename Iter>
void quickSort(std::vector<typename Iter::value_type>& vec, Iter left,
    Iter right) {

    auto size = std::distance(left, right);
    if (size <= 1) {
        return;
    }
    auto pivot = std::next(right, -1);
    if (size == 2 && *pivot < *left) {
        std::iter_swap(left, pivot);
    }
    auto wall = left;
    auto curr = left;

    while (curr != right) {
        if (*curr < *pivot) {
            std::iter_swap(wall, curr);
            wall++;
        }
        curr++;
    }

    std::iter_swap(pivot, wall);
    quickSort(vec, left, wall);
    quickSort(vec, wall + 1, right);

}

int main() {
    std::vector<int> myVec = { 6, 5, 2, 3, 2, 4, 34, 2434, 251, 4, 12, 4, 5,
        634, 523, 5, 4, 353, 3, 5, 345, 7, 86786, 8, 7, 9, 1 };
    quickSort(myVec, myVec.begin(), myVec.end());
    return 0;
}


texts: Program to evaluate powers of complex numbers

texts:
I'm trying to develop a simple program to evaluate integral powers of a complex number \$z\$ , that is, \$z^n\$, where \$z\$ is in the algebrical form \$a+i b\$ and \$n \in \mathbb{Z} ^{*} _{+}\$.

How I was trying to proceed:

First, I defined a product function, and next I intended to define a exponentiation function inside of which I iterated the product function (the code can bee seen below). Is it correct? Is there a more efficient alternative for doing that?

    include <stdio.h>
    include <math.h>

    struct complex {
        float real,imag;
    };

    struct complex product (struct complex x, struct complex y){
    /* using the distributive property, (a+ib)(c+id) = (ac-bd)+i(ad+bc)*/
        struct complex z;
        z.real = (x.real * y.real)- (x.imag * y.imag);
        z.imag = (x.real * y.imag) + (x.imag * y.real);
    return z;
    }

    struct complex exponentiation (struct complex z, int n){
        int i;
        struct complex w;
        w = z;
        for (i=1, i<n, i++)
            w = product (w,z);
    return w;
    }


texts:
Given an ASCII string create a 'compressed' version of it. For example, aabccccddddddde would output a2bc4d7e whereas abc would output abc.

This is how I've implemented it. Is there a smarter way to do it without the need for two for loops?

import java.util.LinkedHashMap;
import java.util.Set;

public class CompressString {

  private static String compressString(String s) {
    LinkedHashMap<Character, Integer> charCountMap = createCharacterCountMap(s);

    StringBuilder result = new StringBuilder();
    Set<Character> keySet = charCountMap.keySet();
    for(Character c: keySet) {
      int val = charCountMap.get(c);
      if(val == 1) {
        result.append(c);
      } else {
        result.append(c.toString() + val);
      }
    }
    return result.toString();
  }

  private static LinkedHashMap<Character, Integer> createCharacterCountMap(String s) {
    char[] charArray =  s.toCharArray();
    int[] charCountArray = new int[128];
    LinkedHashMap<Character, Integer> charCountMap = new LinkedHashMap<Character, Integer>();
    for(int i=0; i<charArray.length; i++) {
      int intVal = charArray[i];
      charCountArray[intVal]++;
      charCountMap.put(charArray[i], charCountArray[intVal]);
    }
    return charCountMap;
  }

  public static void main(String[] args) {
    String s1 = "aabccccddddddde";
    String s2 = "abc";
    System.out.println(compressString(s1));
    System.out.println(compressString(s2));
  }

}


texts: Parsing a String to see if it contains another String, and then returning a monad if it does

texts:
I was writing a function (named listenString) in haskell to see if a string contains one of the strings in a list of strings, and to then return a value (of the type m ()) that corresponded with the string it found. The type of that function is (Eq a, Monad m) => [a] -> [([a], m ())] -> m ().

The reason why I used a list to store the strings and their corresponding values ([([a], m ())]) instead of a Map was because I wanted to make sure that the function evaluated strings in the order that they were in the list, e.g. listenString "hello there" [("lo",print True),("hello",print False)] would printed True. If I used a map, the order might have been lost, and the function might have printed False.

Here's the code. I'm specifically wondering if there are any bugs, and if I'm using ListT correctly (of if I should be using something other than ListT), but any other feedback would be helpful and appreciated.

import Data.Either
import Control.Monad.Trans.List

searchListMapMaybe f (Search a b c) = Search a (mapMaybe f b) c

data Search a b = Search a [a] b

type Searching a b = ListT (Either b) (Search a b)

listenString [] _ = return ()
listenString a l =
                    let list = filter (\(x,_) -> if (x == []) then False else True) l
                        noEmptyList [] = error "listenForString: You need to have at least one item in the list"
                        noEmptyList x = x
                     in listenStringSub a $ ListT $ Data.Either.Right $ fmap (\(x,y) -> Search x [] y) $ noEmptyList list
    where
    listenStringSub :: (Eq a) => [a] -> Searching [a] (m b) -> m b
    listenStringSub _ (ListT (Data.Either.Left a)) = a
    listenStringSub (c:cs) x = listenStringSub cs $ (listenStringMap c x) >>= searchFinal
        where
        listenStringMap char x = fmap ((searchReduce char) . (searchPop char)) x
    searchPop :: (Eq a) => a -> Search [a] b -> Search [a] b
    searchPop char (Search a@(x:_) l b)
      | char == x = Search a (a:l) b
      | otherwise = Search a l b
    searchReduce :: (Eq a) => a -> Search [a] b -> Search [a] b
    searchReduce char search = searchListMapMaybe (function char) search
        where
        function _ [] = Just []
        function c l@(x:xs)
          | c == x = Just xs
          | otherwise = Nothing
    searchFinal :: (Eq a) => Search [a] b -> Searching [a] b
    searchFinal s@(Search a b c)
      | [] `elem` b = ListT (Data.Either.Left c)
      | otherwise = return s

Edit: listenString should decide what values to return in the following order:

Which list comes first: listenString "hello there" [("lo",print True),("he",print False)] would output False.
If two or more strings end in the exact same place, e.g.  listenString "hello there" [("lo",print True),("hello",print False)], I want the tuple closest to the beginning of the list to be displayed (the above expression would output True.


texts: Periodically checking for internet connection

texts:
I have a SwingWorker which checks periodically for an internet connection and updates a jLabel accordingly.

public class InternetCheckWorker extends SwingWorker<Void, String> {

        @Override
        protected Void doInBackground() throws InterruptedException {
            while (true) {
                try (Socket socket = new Socket(HOSTNAME, 80);) {
                    process("on");
                } catch (IOException e) {
                    process("off");
                }
                Thread.sleep(500);
            }
        }

        protected void process(String status) {
            jInternetConnectionLabel.setText("Connection " + status);
        }
    }

    private static final String HOSTNAME = "www.google.com";

Is there maybe a more proper way of doing it or even a library with net tools (along with database management tools or general utility tools) that could do this and have less custom code littering my project?

All in all I am looking for the most minimalistic way.


texts: Do you see any flaws in these prepared statements to avoid SQL injection?

texts:
I have used this guide to implement prepared statements in order to avoid SQL Injection.

I made some tests and no error was shown. However, I would like to ask you if you see any flaw in the code, so that I can improve it.

This is the code for a simple login:

<form action="conexion_PDO.php" method="post">
User:
<input type="text" name="user">
Pass:
<input type="password" name="pass">
<input type="submit" value="Ingresar">
</form>

This is Conexion_PDO.php:

<?php

try {
$gbd = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$statement = $gbd->prepare("SELECT * FROM user where email = ? AND
password = ?");
if ($statement->execute(array($_GET['user'],md5($_POST['pass'])))) {
while ($rs = $statement->fetch()) {
print_r($rs);
}

$gbd = null;
} catch (PDOException $e) {
print "¡Error!: " . $e->getMessage() . "
";
die();
}

?>


texts:
Problem statement

  Two players - Alice and Bob. Alice needs to guess a number \$n\$, from
  range \$[1, N]\$, \$N \le 200\$

  In \$i\$th turn, Alice guesses a number \$i\$
  Bob chooses to tell the relation between \$i\$ and \$n\$ (\$n \lt i\$, \$n = i\$ or \$n \gt i\$). Bob could tell what he wants, unless
  it conflicts with what he says before
  Each turn costs \$i\$
  Alice wants to minimize the total costs
  Bob wants to maximum the total costs

  What is the minimal cost if both players take the best strategy?

Any performance improvement ideas in terms of algorithm time complexity, code bugs or code style advice is appreciated.

More specific question: I do not know how Bob could make sure there is no conflict to what he said in the past -- if he tells number wrong at one time. For example, if \$n\$ is 20, Alice guess \$i\$ = 50, if Bob tells alice \$i\$ is smaller (Bob lies), then Alice will always guess a number > 50, how could Alice achieve the final goal? I think Bob could lie, but finally he should help Alice achieve the final goal, even if in the middle Alice may take more steps (more costs) -- because of some conclusion Bob tells in the middle is not correct.

If anyone have any ideas about how Bob could lie (which will maximum cost for Bob as one goal), while at the same time he still make sure no conflict in the future (and finally guide Alice to the right number), it will be great.

The major ideas of my code is, I try to use Dynamic programming approach to build dp structure from bottom up, dp[(i,j)] means for numbers start from i and ends with j, what are minimal cost for Alice. Both i and j are inclusive.

import sys
from collections import defaultdict
class Solution(object):
    def getMoneyAmount(self, n):
        """
        :type n: int
        :rtype: int
        """
        dp = defaultdict(lambda : sys.maxint) # key: tuple (start, end), value: min cost
        for end in range(1, n+1):
            for start in range(end, 0, -1):
                if start == end:
                    dp[(start, end)] = 0
                elif start + 1 == end:
                    dp[(start, end)] = start
                else:
                    for d in range(end-1, start, -1):
                        dp[(start, end)] = min(dp[(start, end)], d + max(dp[(d+1, end)], dp[(start, d-1)]))

        return dp[(1, n)]
if __name__ == "__main__":
    s = Solution()
    print s.getMoneyAmount(10)


texts: Adding data to database using asp.net and sql-server

texts:
I just want to know your suggestions on improving my code on adding data to the database using asp.net and sql-server. Basically, I've created a form that the admin will fill-up and then when he clicked the submit button, the input values will be added to the database.

As of now, this is how i add data. Here is the code of my submit button.

public int ItemType { get; set; }

protected void Button1_Click(object sender, EventArgs e)
{

    try
    {
        int item_brandId = ConnectionClassBrands.GetIdByBrand(itemBrand.Text);
        string item_model = itemModel.Text;
        double item_price = Convert.ToDouble(itemPrice.Text);
        string item_image1 = Session["PicturePath1"].ToString();
        string item_image2 = Session["PicturePath2"].ToString();
        string item_description = itemDescription.Text;
        string item_necktype = itemNeckType.Text;
        string item_body = itemBody.Text;
        string item_fretboard = itemFretboard.Text;
        string item_fret = itemFret.Text;
        string item_bridge = itemBridge.Text;
        string item_neckpickup = itemNeckPickup.Text;
        string item_bridgepickup = itemBridgePickup.Text;
        string item_hardwarecolor = itemHardwareColor.Text;

        if (itemType1.Checked)
        {
            int item_type = ConnectionClassBrands.GetIdByType(itemType1.Text);
            ItemType = item_type;
        }
        else if (itemType2.Checked)
        {
            int item_type = ConnectionClassBrands.GetIdByType(itemType2.Text);
            ItemType = item_type;
        }
            ConnectionClassGuitarItems.AddStringInstrumentItems(ItemType, item_brandId, item_model, item_price, item_image1, item_image2,
            item_description, item_necktype, item_body, item_fretboard, item_fret, item_bridge, item_neckpickup,
            item_bridgepickup, item_hardwarecolor);

            lblResult2.Text = "Upload successful!" + item_image1 + " and " + item_image2;

            ClearTextFields2();
    }
    catch (Exception ex)
    {
        lblResult2.Text = ex.Message;
    }
}

So the data that i want to add is item typeId,brandId,model,price,image1,image2,
description,necktype,body,fretboard,fret,bridge,neckpickup,bridgepickup and hardwarecolor. That is basically the columns in my database. Now, with the input values that the admin made, it will populate to the given variables above. And then all those values will be passed on to ConnectionClassGuitarItems.AddStringInstrumentItems(ItemType,item_brandId etc..).

Inside the ConnectionClassGuitarItems.AddStringInstrumentItems is this code:

public static void AddStringInstrumentItems(int typeId, int brandId, string model, double price, String itemimage1, String itemimage2, string description, string necktype, string body,
    string fretboard, string fret, string bridge, string neckpickup, string bridgepickup, string hardwarecolor)
{
    MusicStoreDBEntities obj = new MusicStoreDBEntities();

    instrumentItem s = new instrumentItem();

    s.typeId = typeId;
    s.brandId = brandId;
    s.model = model;
    s.price = price;
    s.itemimage1 = itemimage1;
    s.itemimage2 = itemimage2;
    s.description = description;
    s.necktype = necktype;
    s.body = body;
    s.fretboard = fretboard;
    s.fret = fret;
    s.bridge = bridge;
    s.neckpickup = neckpickup;
    s.bridgepickup = bridgepickup;
    s.hardwarecolor = hardwarecolor;

    obj.instrumentItems.Add(s);
    obj.SaveChanges();
}

I am using entity framework to add values to the database. That's pretty much my approach on adding data.


texts: Filtering a list of names based on certain conditions

texts:
I wrote this code to filter a list of names based on certain conditions, and  wanted to see if I can reduce this further and eliminate redundancy in code.

names1 = ["Jane", "Jake", "Bradley", "Bill", "Betty", "Kara", "Kris", "Jil"]
names2 = ["George", "Kate", "Karen", "Kurt", "Greg", "Gary"]
selection_criteria = ["full_list", "four_characters", "three_characters", "start_with_k", "start_with_z"]

def sublist (name_list, condition):
    return_list = []
    if condition == "full_list":
        return name_list
    if condition == "four_characters":
        for name in name_list:
            if len(name) == 4:
                return_list.append(name)
    if condition == "three_characters":
        for name in name_list:
            if len(name) == 3:
                return_list.append(name)
    if condition == "start_with_k":
        for name in name_list:
            if name[0] == 'K':
                return_list.append(name)
    if condition == "start_with_z":
        for name in name_list:
            if name[0] == 'Z':
                return_list.append(name)
    return return_list

for criteria in selection_criteria:
    print(sublist(names1, criteria))

for criteria in selection_criteria:
    print(sublist(names2, criteria))


texts: Implementation of an UniqueIdentifier class

texts:
I have a requirement to implement a generic UniqueIdentifier which can cover identifiers like OrderId, TrackingID, scannableId and other Ids. The ids, as they are now, are either Long or String.
Below is my implementation of the UniqueIdentifier class --

public class UniqueIdentifier {
    String stringValue;
    Long longValue;
    boolean isLong;
    boolean isString;

    public UniqueIdentifier(String value) {
        setStringValue(value);
        try
        {
            setLongValue(Long.parseLong(value));
        }
        catch(NumberFormatException nex)
        {
            setLong(false);
        }
    }
    public UniqueIdentifier(Long value) {
        setLongValue(value);
        setStringValue(Long.toString(value));
    }
    public String getStringValue() {
        return stringValue;
    }
    private void setStringValue(String stringValue) {
        this.stringValue = stringValue;
    }
    public Long getLongValue() {
        return longValue;
    }
    private void setLongValue(Long longValue) {
        this.longValue = longValue;
    }
    public boolean isLong() {
        return isLong;
    }
    private void setLong(boolean isLong) {
        this.isLong = isLong;
    }
    public boolean isString() {
        return isString;
    }
    private void setString(boolean isString) {
        this.isString = isString;
    }
}

Is there anything that i can do better here


texts:
I am working on an application that reads lots of data from the network and puts it in a grid.  I noticed that I could save some memory by reusing existing strings instead of always using the new strings that came off the wire.  So here is the class that I wrote to accomplish that.  It is simple and it works.  But I was wondering if this had a name and, of course, if the code could be improved. One thing that I don't like is that I'm storing two references to each string.

public class StringCollection
{
  private Dictionary<string, string> lookup_ = new Dictionary<string, string>();

  public string Reuse(string s)
  {
    if (s == null)
    {
      return null;
    }
    string existing;
    if (lookup_.TryGetValue(s, out existing))
    {
      return existing;
    }
    else
    {
      lookup_.Add(s, s);
      return s;
    }
  }

  public void Clear()
  {
    lookup_.Clear();
  }

  public int Count { get { return lookup_.Count; } }

}


texts:
I'm trying to solve the problem of a whiteboard receiving registrations before, during and after its own initialization. As each registration needs a bit of handling which can happen only after the whiteboard is fully initialized, I need to delay that handling, until initialization has completed. All of this needs to be managed in a thread safe manner, as registrations may happen by multiple threads.

So I've devised the component below to help the whiteboard achieve this.

I've made this interface :

@FunctionalInterface
public interface RegistrationHandler {

    void handle(Runnable registration);

    default void ready() {
    }
}

And this is the implementation that helps me delay

public final class DelayedRegistrationHandler implements RegistrationHandler {
    private volatile RegistrationHandler state = new QueuedHandler();

    @Override
    public void handle(Runnable registration) {
        state.handle(registration);
    }

    @Override
    public void ready() {
        RegistrationHandler queued = state;
        state = Runnable::run;
        queued.ready();
    }

    private static class QueuedHandler implements RegistrationHandler {

        private final Queue<Runnable> registrations = new ConcurrentLinkedQueue<>();

        @Override
        public void handle(Runnable registration) {
            registrations.add(registration);
        }

        public void ready() {
            while (!registrations.isEmpty()) {
                registrations.remove().run();
            }
        }
    }

}

Intended usage (added for clarification, not actual code, not for review)

RegistrationHandler registrationHandler = new DelayedRegistrationHandler();

public void register(Object registered) {
    registrationHandler.handle(() -> this.doActualRegistration(registered));
}

public void init() {
    doHeavyInitPossiblyWaitingForOtherServices();
    registrationHandler.ready();
}

My primary goal for this review is asserting the thread safety of the implementation. But obviously all remarks are welcome.


texts: Looping through Radgrid in JS is slow, can this be faster?

texts:
I do a single select in one radgrid, and based upon that selection I want to select multiple rows in a different radgrid:

<telerik:RadGrid ID="rgPaymentLines"> <ClientEvents OnRowSelected="RowPaymentSelected"/> ... </telerik:RadGrid>

<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
    <script type="text/javascript">

        function RowPaymentSelected(sender, eventArgs) {
            var grid = $find("<%=rgPaymentLines.ClientID %>");
            var MasterTablePayment = grid.get_masterTableView();
            var paymentRow = MasterTablePayment.get_selectedItems()[0];
            var paymentCell = MasterTablePayment.getCellByColumnUniqueName(paymentRow, "DossierID")
            selectDossierRow(paymentCell.innerHTML);
        }
        function selectDossierRow(dossierID) {
            var gridDossier = $find("<%=rgDossiersAdmin.ClientID %>");
            var MasterTableDossier = gridDossier.get_masterTableView();
            var rows = MasterTableDossier.get_dataItems();

            MasterTableDossier.clearSelectedItems();
            for (var i = 0; i < rows.length; i++) {
                if (MasterTableDossier.getCellByColumnUniqueName(rows[i], "columnDossierID").innerHTML == dossierID) {
                    MasterTableDossier.selectItem(i);
                }
            }
        }


texts:
I ran into this question on Stack Overflow. It looked like a really cool thing to try myself, being that I haven't done any recursion for ages (read at least 2 years).

var keypadPossibilities = (function()
{
    var keypad_mapping = [
        [],
        ['a','b','c'],
        ['d','e','f'],
        ['g','h','i'],
        ['j','k','l'],
        ['m','n','o'],
        ['p','q','r','s'],
        ['t','u','v'],
        ['w','x','y','z']
    ];

    function getPosibilities(keypad_mapping_indexes)
    {
        //if only 1 keypad mapping index: simply return the characters
        if ( keypad_mapping_indexes.length === 1)
        {
            return keypad_mapping[keypad_mapping_indexes.shift()];
        }

        //still multiple keypad mapping index left. lets do some magic
        var currentIndex = keypad_mapping_indexes.shift(), posibilities = [],
            characters = keypad_mapping[currentIndex];

        var charactersToGlueAtEnd = getPosibilities(keypad_mapping_indexes);

        for ( var i in characters )
        {
            for ( var j in charactersToGlueAtEnd )
            {
                posibilities.push(characters[i]+charactersToGlueAtEnd[j]);
            }
        }

        return posibilities;
    }

    return function(pressed_keys)
    {
        return getPosibilities(pressed_keys);
    }

})();

Usage would be:

keypadPossibilities([1,2,3]);

It works, so thats nice (no debugging required, that was a first). So, shoot, code remarks, performance remakrs, ... You can go full package. Everything to learn new cool stuff about JS.


texts:
I have a Ruby programming task. My code passes all the rspec requirements, but I am not sure if I've done it in the right way. And I'm not quite sure why I need :entries there...

Here is the rspec test:

# # Topics
#
# * Hash
# * Array
# * instance variables
# * regular expressions

require '11_dictionary'

describe Dictionary do
  before do
    @d = Dictionary.new
  end

  it "is empty when created" do
    expect(@d.entries).to eq({})
  end

  it "can add whole entries with keyword and definition" do
    @d.add("fish" => "aquatic animal")
    expect(@d.entries).to eq({"fish" => "aquatic animal"})
    expect(@d.keywords).to eq(["fish"])
  end

  it "add keywords (without definition)" do
    @d.add("fish")
    expect(@d.entries).to eq({"fish" => nil})
    expect(@d.keywords).to eq(["fish"])
  end

  it "can check whether a given keyword exists" do
    expect(@d.include?("fish")).to be_falsey
  end

  it "doesn't cheat when checking whether a given keyword exists" do
    expect(@d.include?("fish")).to be_falsey # if the method is empty, this test passes with nil returned
    @d.add("fish")
    expect(@d.include?("fish")).to be_truthy # confirms that it actually checks
    expect(@d.include?("bird")).to be_falsey # confirms not always returning true after add
  end

  it "doesn't include a prefix that wasn't added as a word in and of itself" do
    @d.add("fish")
    expect(@d.include?("fi")).to be_falsey
  end

  it "doesn't find a word in empty dictionary" do
    expect(@d.find("fi")).to be_empty # {}
  end

  it "finds nothing if the prefix matches nothing" do
    @d.add("fiend")
    @d.add("great")
    expect(@d.find("nothing")).to be_empty
  end

  it "finds an entry" do
    @d.add("fish" => "aquatic animal")
    expect(@d.find("fish")).to eq({"fish" => "aquatic animal"})
  end

  it "finds multiple matches from a prefix and returns the entire entry (keyword + definition)" do
    @d.add("fish" => "aquatic animal")
    @d.add("fiend" => "wicked person")
    @d.add("great" => "remarkable")
    expect(@d.find("fi")).to eq({"fish" => "aquatic animal", "fiend" => "wicked person"})
  end

  it "lists keywords alphabetically" do
    @d.add("zebra" => "African land animal with stripes")
    @d.add("fish" => "aquatic animal")
    @d.add("apple" => "fruit")
    expect(@d.keywords).to eq(%w(apple fish zebra))
  end

  it "can produce printable output like so: [keyword] 'definition'" do
    @d.add("zebra" => "African land animal with stripes")
    @d.add("fish" => "aquatic animal")
    @d.add("apple" => "fruit")
    expect(@d.printable).to eq(%Q{[apple] "fruit"\n[fish] "aquatic animal"\n[zebra] "African land animal with stripes"})
  end
end

Here is my code:

class Dictionary
    attr_accessor :entries

    def initialize
        @hash={}
    end

    def add(a)
        if a.class == Hash
            a.each_pair { |k, v|
                @hash[k]=v
            }
        else
           @hash[a]=nil
       end
    end
    def entries
        @hash
    end

    def keywords
        @hash.keys.sort
    end
    def include?(k)
        @hash.key?(k)
    end

    def printable
        str=[]
        key=@hash.keys.sort
        key.each do |el|
            @hash.each_pair do |k,v|
                if k==el
                    str << "[#{k}] \"#{v}\""
                end
            end
        end
        return str.join("\n")
    end

    def find(str)
        if str.class == Hash
            str.each_pair { |k, v|
               return (@hash.select { |k,v| k.include?(k)})
            }
        elsif str.class == String
            return (@hash.select {|k,v| k.include?(str)})
        end
    end
end


texts: How can I check if a sequence is alternating?

texts:
I need to write a program that reads a sequence of integers and determines if the sequence is alternating. An alternating sequence is a sequence of numbers in which every number should be greater or smaller than the one before it according to the base alternation. For example, 1 5 4 8 2 10 is alternating.

I wrote this program but I am not sure it is 100% correct.

import java.util.Scanner;

  public class alternating {

 public static void main(String[] args) {
    // TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int cases = scan.nextInt();
for (int testcase = 0; testcase < cases; testcase++) {
    int n = scan.nextInt();
    int[] sequence = new int[n];
    for (int i = 0; i < sequence.length; i++)
        sequence[i] = scan.nextInt();
    if (alternating(sequence))
        System.out.println("alternating");
    else
        System.out.println("not alternating");
}

  }

  public static boolean alternating(int[] sequence) {
   for (int i = 0; i < sequence.length - 2; i++) {
    if (sequence[i] <= sequence[i + 1]) {
        if (sequence[i + 1] <= sequence[i + 2])
            return false;
    } else {
        if (sequence[i] >= sequence[i + 1])
            if (sequence[i + 1] >= sequence[i + 2])
                return false;

    }

}
return true;
     }

      }


texts:
Short and Spicy question is that If input is how are you and output should beyou are how.

public class ReverseWord {
    public static void main(String[] args) throws IOException{
        String input;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the input string");
        input = br.readLine();
        System.out.println("Enterd String:"+input);
        System.out.println("Reversed:"+reverse(input));
    }

    public static String reverse(String input){
        String delimiter = " ";
        String[] splits = input.split(delimiter);
        String reverse = new String("");
        for(int i=splits.length-1; i>=0; i--){
            //System.out.println(splits[i]);
            reverse += splits[i];
            reverse = reverse.concat(delimiter);
        }
        System.out.println(reverse);
        return reverse;
    }
}

How can I improve my code? And Is there any other way to do it with less time and space complexity?


texts: DRY multiple if statements used to show/hide elements based on slider value

texts:
I'm showing and hiding 4 svg paths based on the value of a slider, all is working as expected, but it still feels a little cumbersome. Does anyone know a way to "DRY" it out a little more?

jsFiddle

$('.volumeSlider').slider({
    value: 1,
    orientation: "vertical",
    range: "min",
    max: 1,
    step: 0.05,
    animate: true,
    slide: function (e, ui) {
        $('p').text(ui.value);
        var v = $('.volume1');
        if (ui.value == 1) {
            v.show();
        }
        if (ui.value < 1) {
            v.slice(0).hide();
            v.slice(1, 4).show();

        }
        if (ui.value <= 0.65) {
            v.slice(0, 2).hide();
            v.slice(2, 4).show();
        }
        if (ui.value <= 0.35) {
            v.slice(0, 3).hide();
            v.slice(4).show();
        }
        if (ui.value === 0) {
            v.hide();
        }
    }
});


texts:
What can be more elegant ways to solve the given problem.

    #
   ##
  ###
 ####

Code:

function StairCase(n) {
    for (var i = 1; i <= n; i++) {
        var col = i;
        for(var j = 1; j <= n - col; j++) {
            process.stdout.write(' ');
        }
        for(var j = 1; j <= col; j++) {
            process.stdout.write('#');
        }
        process.stdout.write('\n');
    }

}


texts: Python class to implement a list with a size limit

texts:
I am currently working through a python course about objected oriented programming. I was given this first assignment to work on:

  Create a simple class, MaxSizeList, that acts a little bit like a
  list, with a pre-configured limit on its size.

  Here some test calling code that imports the completed MaxSizeList and
  then uses it to create two new MaxSizeList objects.

from assignments import MaxSizeList  # assumes "class MaxSizeList"
                                     # is in a script called "assignments.py"

  Below are the test cases:

a = MaxSizeList(3)
b = MaxSizeList(1)

a.push("hey")
a.push("hi")
a.push("let's")
a.push("go")

b.push("hey")
b.push("hi")
b.push("let's")
b.push("go")

print(a.get_list())
print(b.get_list())

Output

 # ['hi', "let's", 'go']
 # ['go']

I came up with this code which outputs the correct result:

class MaxSizeList(object):

    ls = []

    def __init__(self,mx):
        self.val = mx

    def push(self,st):
        self.ls.append(st)

    def get_list(self):
        while len(self.ls) != self.val:
            self.ls.pop(0)
        return self.ls

Do you have any input on how this can be done more efficiently? Did I do it correctly or is there anything to note from the code I came up with?


texts: Bounded spigot algorithms for e and pi in Python

texts:
I've written bounded spigot algorithms(Spigot Algorithm) for e and pi. I would like to understand if there is anything I can do to make this more efficient. I've done things already like move the carry over check to the very end, precompute values etc.
You run the functions and pass it the number of digits you want i.e. print(pispig(1000))`
The spigot algorithm for computing functions you can apply a Horner schema to is one of the coolest things I have ever learned.
def espig(n):
    estr = '2.'
    (multq, asum, carover) = (0, 0, 0)
    prec = 10 ** n
    (remainders, tsum) = ([], [])
    b = [x for x in range(2, n + 1)]
    init = [1 for x in range(2, n + 1)]
    x10 = [prec * x for x in init]
    while True:
        for (x, y) in zip(reversed(b), x10):
            asum = carover + y
            remainders.insert(0, asum % x)
            tsum.insert(0, asum)
            multq = asum // x
            carover = multq
        estr += str(int(tsum[0] // 2))
        x10 = [prec * x for x in list(reversed(remainders))]
        (carover, asum) = (0, 0)
        (remainders, tsum) = ([], [])
        if len(estr) > n:
            break
    return estr

def pispig(n):
    e = n
    xfact = 10 ** e
    n = int(round(3.4 * n))
    prec = n // 3.4
    (pilist, remainders, tsum) = ([], [], [])
    (multq, asum, carover, counter) = (0, 0, 0, 0)
    a = [x for x in range(n)]
    b = [2 * x + 1 for x in range(n)]
    init = [2 for x in range(1, n + 1)]
    x10 = [xfact * x for x in init]
    while True:
        for (A, B, R) in zip(reversed(a), reversed(b), reversed(x10)):
            asum = carover + R
            remainders.insert(0, asum % B)
            tsum.insert(0, asum)
            multq = asum // B
            carover = multq * A
        pilist.append(tsum[0] // 10)
        remainders[0] = tsum[0] % xfact
        x10 = [10 * x for x in list(remainders)]
        (carover, asum) = (0, 0)
        (remainders, tsum) = ([], [])
        if len(''.join([str(x) for x in pilist])) > prec:
            break
    for D in reversed(pilist):
        counter = 0
        if D >= xfact:
            pilist[pilist.index(D) - 1] += 1
            pilist[pilist.index(D)] = pilist[pilist.index(D)] % xfact
            counter += 1
    return str('3.' + ''.join(str(x) for x in pilist[1:]))


texts: BFS for creating a queue without repetitions and with loops in the graph

texts:
I have a pipeline with loops of filters and one input filter.  The rest are splitters, transform and output.

I would like my code to go over the filters and push them into a queue (order is important).  However, if I have a loop, I only want to count the end of the loop once.

Here is my working code.  Please review it.

queue<string> CEngineInternal::GetFiltersListToRun()
{
    queue<string> filtersBFS;
    queue<string> filtersToRun;
    set<string> alreadyFoundFilters;

    // add input filters to the list
    for(BaseFilterMap::const_iterator it = m_Filters.begin(); it != m_Filters.end(); it++)
    {
        string FilterName = (*it).first;
        const CBaseFilter *filter = (*it).second;
        if(filter->IsInputFilter())
        {
            //push the input filter
            filtersBFS.push(FilterName);
            filtersToRun.push(FilterName);
            alreadyFoundFilters.insert(FilterName);
        }
    }

    while (!filtersBFS.empty())
    {
        string filterName = filtersBFS.front();
        filtersBFS.pop();

        //get the OutputPin connections for the next filter
        FilterConnection* filterConnection = m_Connections[filterName];
        ASSERT(filterConnection != NULL);
        PinConnectionVector& outPinConnections = filterConnection->GetOutputPinConnections();

        if (outPinConnections.size() != 0)
        {
            // find all the output pin connections
            for (size_t i = 0; i < outPinConnections.size(); ++i)
            {
                //add connected filters id's to the list
                const std::string& oFilterName = outPinConnections[i].ConnectedFilterName();

                if (oFilterName.empty())
                {
                    continue;
                }

                if (alreadyFoundFilters.find(oFilterName) != alreadyFoundFilters.end())
                {
                    continue;
                }
                else
                {
                    filtersBFS.push(oFilterName);
                    filtersToRun.push(oFilterName);
                    alreadyFoundFilters.insert(oFilterName);
                }
            }
        }
    }

    return filtersToRun;
}


texts:
In this program there is a single remote server which performs miscellaneous work. Because there is only one server, it seems like a singleton pattern could fit well.

The problem that a distributed program introduces is that every client will have its own version of a static variable. Therefore I have defined a basic ComputeInterface which is implemented by two classes. ComputeServer is the object which performs the work asked for by clients. ComputeService is a class which performs an RMI lookup to the ComputeServer and acts like singleton server in the client program.

The location information for the Server is maintained in a Configuration class:

public class Configuration {
    public static final int COMPUTE_REMOTE_PORT = 8900;
    public static final String COMPUTE_REMOTE_ID = "COMPUTE_REMOTE_ID";
    public static final String COMPUTE_REMOTE_HOST = "localhost";
}

A ComputeTask implements Serializable and is performed by the ComputeInterface which implements Remote. The ComputeInterface contains an isConnected method which is used for determining if there is connectivity to the server from the service:

public interface ComputeTask extends Serializable{
    void doWork();
}

public interface ComputeInterface extends Remote {
    ComputeTask compute(ComputeTask task) throws RemoteException;
    boolean isConnected() throws RemoteException;
}

This is the implementation for the server:

final class ComputeServer extends UnicastRemoteObject implements ComputeInterface {
    public static void main(String[] args) throws RemoteException, AlreadyBoundException {
        ComputeServer computeServer = new ComputeServer();
        Registry registry = LocateRegistry.createRegistry(Configuration.COMPUTE_REMOTE_PORT);
        registry.bind(Configuration.COMPUTE_REMOTE_ID, computeServer);
        System.out.println("Compute Server Running");
    }

    private ComputeServer() throws RemoteException {
        super();
    }

    @Override
    public synchronized ComputeTask compute(ComputeTask task) throws RemoteException{
        task.doWork();
        return task;
    }

    @Override
    public synchronized boolean isConnected() throws RemoteException{
        return true;
    }
}

And here is the Service. If the server has not yet been connected, the service will attempt to do a registry lookup on the server. If the registry lookup up was successful (or has already been performed), it will check the server connectivity before performing any tasks.

final public class ComputeService implements ComputeInterface{

    public static final ComputeInterface service = new ComputeService();
    private static ComputeInterface computeServer;

    private ComputeService(){}

    @Override
    public synchronized boolean isConnected() throws RemoteException{
        return ComputeService.connected();
    }

    private static boolean connected(){
        if (computeServer == null) {
            try{
                Registry reg = LocateRegistry.getRegistry(Configuration.COMPUTE_REMOTE_HOST, Configuration.COMPUTE_REMOTE_PORT);
                computeServer = (ComputeInterface) reg.lookup(Configuration.COMPUTE_REMOTE_ID);
                System.out.println("New Connection to Compute Server");
            }
            catch (RemoteException | NotBoundException e){
                System.err.print(e);
                computeServer = null;
                return false;
            }
        }
        try{
            return computeServer.isConnected();
        }
        catch (RemoteException e){
            System.err.print(e);
            computeServer = null;
        }
        return false;
    }

    @Override
    public synchronized ComputeTask compute(ComputeTask task) throws RemoteException{
        if(!ComputeService.connected()) return task;
        return computeServer.compute(task);
    }
}

Here is an example of how a client can use the service to perform work on the server:

CustomComputeTask task = new CustomComputeTask();
task = ComputeService.service.compute(task);


texts:
About

This is a SEDE query which will calculate your activity and participation on a site. It's geared for Programming Puzzles & Code Golf where questions are values more, but the values can be modified to fit general Q&A SE sites too.

Try it online!

So I did what all programmers do and I looked up how to most of this stuff on Stack Overflow and mashed the snippets from SO into my program until it worked!

Essentially this program takes input for the user's User ID and their score is calculated by::

1  * <# of Upvotes>
2  * <# of Downvotes>
10 * <# of Questions>
5  * <# of answers>
1  * <# of Comments>

The actual values of what <# of ...> is multiplied is stored in variables which you can see I've declared.

Then within the FROM the Upvotes, Downvotes, etc. are all counted. The outmost SELECT is used so I can manipulate these also

Code

DECLARE @UID int = ##UserId##

DECLARE @Up      int = 1
DECLARE @Down    int = 2
DECLARE @Q       int = 10
DECLARE @A       int = 5
DECLARE @Comment int = 1

SELECT Score = Upvotes   * @Up +
          Downvotes * @Down +
          Questions * @Q +
          Answers   * @A +
          Comments  * @Comment,
       Upvotes, Downvotes, Questions, Answers, Comments
FROM (
  SELECT TOP 1
    (
      SELECT UpVotes
      From Users
      WHERE Id = @UID
    ) as Upvotes,
    (
      SELECT DownVotes
      From Users
      WHERE Id = @UID
    ) as Downvotes,
    (
      SELECT COUNT(*)
      FROM Posts
      WHERE OwnerUserId = @UID and PostTypeId = 1
    ) as Questions,
    (
      SELECT COUNT(*)
      FROM Posts
      WHERE OwnerUserId = @UID and PostTypeId = 2
    ) as Answers,
    (
      SELECT COUNT(*)
      FROM Comments
      WHERE UserId = @UID
    ) as Comments
  FROM Users, Comments, Posts
) data

I'd appreciate any comments on better ways to write this program, if I can restructure this better, my formatting, and really anything because I suck at SQL.


texts:
I am trying to generate JSON from a query. All this seems to be too much grinding it out.

string function getJSON() output="false"    {

  var result = "[";
  var myrow = 0;

  for(var row in this.qryLocation)  {
    myrow++;
    result &= "["
             & row.LocationID                     & ','
             & '"' & row.Address & " " & row.City & '",'
             & '"' & row.formatted_CreateDate     & '"'
             & ']'
             & myRow < this.qryLocation.recordcount ? ',' : '';
    } // end for-in query

  return result & "]";
  }

All this seems very hard to read, especially making sure that the last row does not get an extra comma.


texts: Find alignable blocks of digits between different bases

texts:
In cases where two radices are powers of a common sub-case (e.g., base 8 and base 16 are both powers of base 2), it is possible to align blocks of digits between representations to make converting between those bases more efficient. That's what makes, e.g., streaming base64 encoding and decoding possible--you can do it in chunks of 3 (for encoding) or 4 (for decoding) bytes, rather than needing to accumulate the entire number first. This function takes in two radices and returns a pair of numbers indicating how many digits must be consumed in one base in order to produce a block of output digits in the other base (with "Infinity" indicating that you must consume the entire source number--there is no smaller alignment). It does this by calculating a minimal solution to the equation \$a^x = b^y\$, where \$a\$ and \$b\$ are the radices and \$x\$ and \$y\$ are the sizes of their minimal aligning digit strings.
Can this be made more efficient? Or if not, can it be made clearer without impacting efficiency?
export function digit_ratio(n: number, m: number) {
  if (n === m) return [1, 1];
  const [a, b] = n < m ? [n, m] : [m, n];

  // Find x such that a ^ x = b ^ y
  // Find c such that a = c ^ w and b = c ^ z
  // c only exists if b = 0 mod a (c ^ z = 0 mod c ^ w)
  if (b % a > 0) return [Infinity, Infinity];

  // Use repeated division to find
  // c and a lower bound for w.
  // c ^ (z - w) = c ^ z / c ^ w
  let [c, d] = [b, a];
  for (;;) {
    c = c / d | 0;
    if (c === d) break;
    if (c < d) [c, d] = [d, c];
    if (c % d > 0) return [Infinity, Infinity];
  }

  const logc = Math.log(c);
  const w = Math.log(a)/logc|0;
  const z = Math.log(b)/logc|0;

  // put GCD(w, z) in g
  let [g, f] = [w, z];
  while (f) [f, g] = [g % f, f];

  // return x == the factor by which
  // to multiply w so as to reach its
  // least common multiple with z.
  return n < m ? [z/g, w/g] : [w/g, z/g];
}


texts: Find the best way to get the max sum in a list where sum of three consecutive elements is not allowed

texts:
I am trying to find a maximum sum of elements in a list where the sum of three consecutive elements is not allowed. So, to find the max sum, you'll have to go through each element sequentially from the first element of the list(Must have first element value in max sum output). You can not select more than two elements in a row.

So, the simple example will be like this:

  Input: list = [1, 2, 3, 4, 5]

  Possible combination of elements might be like this:

  1 = [1, 2, 4, 5] & Sum of elements : 12

  2 = [1, 3, 5] & Sum of elements: 9

  Output: 12 (Elements used to calculate maximum sum: [1, 2, 4, 5])

  Rules followed:

  1. A must selection of first element of the list.

  2. Traverse through list sequentially.

  3. Can not select more than two elements in a row.(Here in this scenario, selected first two element which is 1 & 2, then skip 3 and choose 4 & 5)

And I have got the solution, but I would like suggestions on how to make it more efficient.

These are the details of the problem:

  Input format

  Line 1: A single integer N, the number of elements.

  Line 2: List of elements.

  Output format

  The output consists of a maximum sum of elements

  Sample Input: 1

  5

  [10, 3, 5, 7, 3]

  Sample Output: 1

  23

  (Explanation: 10+3+7+3)

  Sample Input: 2

  8

  [3, 2, 3, 2, 3, 5, 1, 3]

  Sample Output: 2

  17

  (Explanation: 3+3+3+5+3)

  Sample Input: 3

  5

  [10, 1, 5, 7, 3]

  Sample Output: 3

  22

  (Explanation: 10+5+7)

Now, for this problem, I have managed to provide a solution, which is this one

def get_max_sum(num, input):
    output_1 = {'skip': True, 'sum': input[0]+input[1], 0: input[0], 1:input[1]}
    output_2 = {'skip': False, 'sum': input[0]+input[2], 0: input[0], 2:input[2]}

    main_output = [output_1, output_2]

    for i in range(2, num):
        for output in main_output:
            if output.get(i) is None:
                if output['skip']:
                    output['skip'] = False
                    continue
                if len(input) > i+1:
                    if input[i] > input[i+1] or output.get(i-1) is None:
                        output[i] = input[i]
                        output['sum'] += input[i]
                        if output.get(i-1) is not None:
                            output['skip'] = True
                    else:
                        output[i+1] = input[i+1]
                        output['sum'] += input[i+1]
                        if output.get(i) is not None:
                            output['skip'] = True
                else:
                    output[i] = input[i]
                    output['sum'] += input[i]

    if main_output[0]['sum'] >= main_output[1]['sum']:
        return main_output[0]['sum']
    else:
        return main_output[1]['sum']

print(get_max_sum(8, [3, 2, 3, 2, 3, 5, 1, 3]))
print(get_max_sum(5, [10, 3, 5, 7, 3]))
print(get_max_sum(5, [10, 1, 5, 7, 3]))
print(get_max_sum(5, [1, 2, 3, 4, 5]))

And I got the output correct which is this:

17
23
22

Now the thing is, I am looking for a better version of this. I know this is not the most efficient code and I will appreciate any suggestions to improve this code.

This is Code Visualization Link.

EDIT: I have made some minor changes/improvements in my code.


texts: Custom ViewModel to check property existance prior to update

texts:
I have written an abstract View Model which all my other View Models inherit when I write any apps in Silverlight, WinRT, WPF etc. The class was written to attempt to address an issue I have run into frequently. That is, after refactoring code, all my property names are wrong and I often forget to rename them. Debugging by identifying views which don't reflect their view models is hard, thus this.

The idea is relatively simple. It provides an implementation of the INotifyPropertyChanged interface with the addition of some additional safety checking when debugging the project. This is done via reflection by checking if the property you are attempting to notify actually exists.

Thus:

class Foo : AbstractViewModel {
    public object Bar { get; set; }
}

Will throw an exception if I try to call NotifyPropertyChanged("Ponies") since Ponies is not a property in Foo.

The AbstractViewModel looks like this:

using System;
using System.ComponentModel;

#if DEBUG
// We need reflection in order to debug our Property Changed Notifications
using System.Reflection;
#endif

namespace WorldOfZero.Common.ViewModels
{
    public class AbstractViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(string name)
        {
#if DEBUG
            // This will detect and throw an error if we attempt to Notify a change on a none existant property.
            // This helps eliminate stupid mistakes like spelling errors.
            // This code is only included in the debug builds of the app, this prevents us from slowing down production code.
            Type type = this.GetType();
            PropertyInfo property = type.GetRuntimeProperty(name);
            if (property == null)
            {
                throw new InvalidOperationException(String.Format("Attempting to Notify a change on a property ({0}) that does not exist.", name));
            }
#endif

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}

I'm looking for ways to improve this. I'm also curious if there might be better ways to solve this than with Reflection.


texts: JavaScript and jQuery check for image file and assign CSS

texts:
This is my first attempt at JavaScript, so I am looking to learn.

I have a website that has jQuery built in and I wanted to leverage that in the following way:

I want to get a number variable that precedes a certain text string (*n*/portal.css)
Get the name of the current webpage
Use this number and pageName to help build a URL to a specifically named image file  The image will have the same name as the webpage with an "_hd.jpg" appended to it
Check if the image file exists and if it does add this image to a CSS div background otherwise do nothing

<script>

    $(function () {
        $(document).foundation();
        //get webpage name
        var loc = window.location.href
        var fileNameIndex = loc.lastIndexOf("/") + 1;
        var dotIndex = loc.lastIndexOf('.');
        var pageName = loc.substring(fileNameIndex, dotIndex < fileNameIndex ? loc.length : dotIndex);

        //get number variable
        var head = document.head
        var portalCss = head.innerHTML.match(/\/[0-9]+\/portal.css/);

        var portalNum = portalCss[0].replace("/", "")
        portalNum = portalNum.replace("portal.css", "")

        //build url for image
        var HeaderImgUrl = '/Portals/' + portalNum + '/Images/' + pageName + '_hd.jpg'

        //check if image exists and assign css values to css class RowPageHeader
        $.ajax({
            url: HeaderImgUrl, //or your url
            success: function (data) {
                $(".RowPageHeader").css("background-image", "url(" + HeaderImgUrl + ")");
                $(".RowPageHeader").css("background-position", "center top");
                $(".RowPageHeader").css("background-size", "100% auto");
                $(".RowPageHeader").css("background-repeat", "no-repeat");
                $(".RowPageHeader").css("overflow", "hidden");
            },
        })

        var FooterImgUrl = '/Portals/' + portalNum + '/Images/footer_bg.jpg'

        $.ajax({
            url: FooterImgUrl, //or your url
            success: function (data) {
                $(".RowFooter").css("background-image", "url(" + FooterImgUrl + ")");
                $(".RowFooter").css("background-position", "center top");
                $(".RowFooter").css("background-size", "2000px auto");
                $(".RowFooter").css("background-repeat", "no-repeat");
                $(".RowFooter").css("overflow", "hidden");
            },
        })

    })

</script>

Two questions:

How can I improve this code?
I want to move the CSS rules into a CSS class in the pages skin.css file.  How can I add a CSS class to the existing one that I am adding the CSS rules to?


texts: Module for sending messages through PubNub

texts:
I have created a Drupal 6 module that sends messages through PubNub when the user updates information about a Node. I have a separate app that, when launched, calls my Drupal site and receives a JSON array containing a lot of information about some nodes. I then update the info in my other app by PubNub->publish from Drupal every time the page is reloaded after the Node is updated. I have the following in my foo.module file:

hook_admin: //not really a hook

function moduleName_admin(){
  //Here we are pulling in the Pubnub.php file from the module directory
  // NOTE: This file requires PubnubAES.php even when you aren't using encryption so include it too
  module_load_include('php', 'moduleName', 'Pubnub');
  $pubnub = new Pubnub(
    "PUBKEY",
    "SUBKEY",
    "",
    false
  );
  $form = array();
  $query = "SELECT info FROM tables;"

  $results = db_query($query);

  while($r=db_fetch_object($results)){
    $form['moduleName_fieldDescription_'.$r->nid] = array(
    '#type' => 'radios',
    '#title' => "Select one for ".$r->info.":",
    '#options' => array(
      t('Foo'),
      t('Bar'),
      t('Baz')
    ),
    '#default_value' => variable_get('moduleName_fieldDescription_'.$r->nid, '0'),
  );

    $pubnub->publish(array(
      'channel' => 'channelName',
      'message' => array("id"=>$r->nid, "selected"=>variable_get('moduleName_fieldDescription_'.$r->nid, '0'))
    ));
  }
  return system_settings_form($form);
}

JSON page:

function moduleName_JSON(){
  $query = "SELECT info FROM table;"
  $results = db_query($query);

  $infoObject = array();
  for($i=0;$r = db_fetch_object($results); $i++){
    $infoObject[$i] = array(
      'info' => $r->info,
      'id' => $r->nid,
      'selected' => variable_get('moduleName_fieldDescription_'.$r->nid, '0'),
    );
  }
  //This next part will wrap the JSON in a function so jQuery can be called like
  //$.ajax( {
    //url:"example.com/moduleName/json",
    //dataType: 'jsonp',
    //callback: 'foo',
    //success:function(data){
      //checkListInfo = data;
      //styleSheetLoaded();
    //}
  //} );
  $callback = check_plain($_REQUEST['callback']);
  if (isset($callback) && $callback != '') {
    header("Content-type: text/javascript");
    echo $callback ."(";
    drupal_json($infoObject);
    echo ");";
  } else {
    drupal_json($infoObject);
  }
}

hook_menu:

function moduleName_menu(){
  $items = array();
  $items['moduleName/editPage'] = array(
    'title' => 'Module edit page',
    'description' => 'Edit this page to make changes to pubnub',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('moduleName_admin'),
    'access arguments' => array('Edit moduleName Permissions'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['moduleName/json'] = array(
    'title' => 'JSON Array containing module info',
    'page callback' => 'moduleName_JSON',
    'access arguments' => array('Change moduleName values'),
    'tpye' => MENU_CALLBACK,
  );
  return $items;
}

This is slightly changed up code from my working Drupal 6 module that uses a live PubNub account. It works great for my purpose. I just want to know how to do it a little more to Drupal standards.

I know I probably have the publish time wrong. Right now it publishes when the page is reloaded instead of right before the page sends the info. I don't think this is right but I am very new to Drupal.

There is a Drupal Module that is in the process of being built that will allow PubNubs integration in Drupal 7/8 but I am on D6 and I am just including the files myself.


texts:
I've implemented a PID controller, but seeing as I'm not an expert in control theory, have I missed any edge cases?

public class PIDController
{
    public enum PIDMode
    {
        Manual,
        Auto,
    }

    public enum PIDAction
    {
        Indirect,
        Direct,
    }

    public PIDMode Mode { get; set; }
    public PIDAction Action { get; set; }

    public double Proportional { get; set; }
    public double Integral { get; set; }
    public double Derivative { get; set; }

    public double Minimum { get; set; }
    public double Maximum { get; set; }

    public double DeltaMinimum { get; set; }
    public double DeltaMaximum { get; set; }

    private double _ProportionalTerm;
    private double _Integrator;
    private double _Derivator;

    public double Setpoint { get; set; }

    private double _Feedback;
    public double Feedback
    {
        get
        {
            return _Feedback;
        }
    }

    public void Calculate(double Input, long Time)
    {
        double output;

        // Compute the error value
        double Error = Setpoint - Input;

        if (Mode == PIDMode.Auto)
        {
            if (Action == PIDAction.Direct)
                Error = 0 - Error;

            // Compute the proportional component
            _ProportionalTerm = 1000.0f * (Error - _Derivator) / (double)Time;

            // Compute the integrator component, clamped to min/max delta movement
            _Integrator += (float)Error * (float)Time / 1000.0f;
            if (_Integrator < DeltaMinimum)
                _Integrator = DeltaMinimum;
            if (_Integrator > DeltaMaximum)
                _Integrator = DeltaMaximum;

            // Add the proportional component
            output = (Proportional * Error);

            // Add the integral component
            output += Integral * _Integrator;

            // Add the derivative component
            output += Derivative * _ProportionalTerm;

            // Clamp output to min/max
            if (output < Minimum)
                output = Minimum;
            if (output > Maximum)
                output = Maximum;
        }
        else
        {
            output = Input;
        }

        // Store values
        _Derivator = Error;

        // Returns the result
        _Feedback = output;
    }
}


texts:
floor[1*e] + floor[2*e] + floor[3*e] + ... + floor[n*e],

  where floor[x] is the largest integer that is not greater than x,
  and e is Euler's number: 2.7182818284..

  Input

  A single line which contains a single integer: n.

  Output

  A single line which contains a single integer which should be
  the answer.

  Constraints

  1 ≤ n ≤ 10 ^ 4000

  Subtasks

  Subtask #1 (50 points): 1 ≤ n ≤ 10 ^ 100

  Subtask #2 (50 points): Original constraints.

  Example

  Input:

  3

  Output:

  15

  Explanation

floor[1*e] = floor[2.71828..] = 2.

floor[2*e] = floor[5.43656..] = 5.

floor[3*e] = floor[8.15484..] = 8.

  So the answer is 2+5+8=15.

My Code

Scanner in=new Scanner(System.in);
int T = in.nextInt();
double e=2.7182818284;
long sum=0;

for (int t_i = 1; t_i <= T; t_i++)
{

   sum=Math.floor(sum+t_i*e);
   // System.out.println(Math.floor(sum));

}
System.out.printf("%.0f",(sum));

This runs into a time-limit exceeded.


texts: Most idiomatic way of declaring a deck in Rust

texts:
I'm new at Rust and I'm trying to implement a cards' deck on Rust, I'm trying to use most idiomatic code I can, but since I'm new at this language, I'd like to hear advice from more experienced programmers. There's my code.
(P.D: Thanks in advance! :>)

use std::fmt;

use rand::seq::SliceRandom;
use rand::thread_rng;

#[derive(PartialEq)]
pub struct Card<'a> {
    name: &'a str,
    value: i8,
    suit: char,
}

impl<'a> fmt::Debug for Card<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} of {}", self.name, self.suit)
    }
}

pub struct Deck<'a> {
    pub cards: Vec<Card<'a>>,
}

impl<'a> Deck<'a> {
    const SUITS: [char; 4] = ['♥', '♦', '♣', '♠'];
    const CARDS: [(&'a str, i8); 13] = [
        ("ACE", 11),
        ("TWO", 2),
        ("THREE", 3),
        ("FOUR", 4),
        ("FIVE", 5),
        ("SIX", 6),
        ("SEVEN", 7),
        ("EIGHT", 8),
        ("NINE", 9),
        ("TEN", 10),
        ("JACK", 10),
        ("QUEEN", 10),
        ("KING", 10),
    ];

    pub fn new() -> Deck<'a> {
        let mut deck: Vec<Card> = Vec::new();

        for suit in Deck::SUITS.iter() {
            for (card_name, card_value) in Deck::CARDS.iter() {
                deck.push(Card {
                    name: card_name,
                    value: *card_value,
                    suit: *suit,
                });
            }
        }
        let mut rng = thread_rng();
        deck.shuffle(&mut rng);

        Deck { cards: deck }
    }

    pub fn deal_card(&mut self) -> Card<'a> {
        if self.cards.is_empty() {
            self.initialize_deck()
        }
        self.cards.pop().unwrap()
    }

    pub fn get_initial_cards(&mut self) -> Vec<Card> {
        vec![self.deal_card(), self.deal_card()]
    }
    /// When the cards vector is empty, shuffle a new deck
    fn initialize_deck(&mut self) {
        *self = Deck::new();
    }
}

EDIT: This module is meaned to be used with a BlackJack game, that is the reason because the cards have those particular values


texts: Blocking queue implementation with std::unique_ptr

texts:
I implemented, somewhat closely based on this implementation, a blocking queue with emphasis on filling up first. So if one producer and one consumer thread are using the queue, the producing queue gets prioritized.

// BQueue.hpp
//#pragma once
#ifndef _BQUEUE_HPP
#define _BQUEUE_HPP

#include <condition_variable>
#include <mutex>
#include <queue>

template <class T> class BQueue {
public:
  BQueue(size_t size);
  void push(T item);
  bool pop(T &item);
  /* ALTERNATIVE 1
  void push(std::unique_ptr<T> item);
  bool pop(std::unique_ptr<T> &item);
  */

private:
  std::mutex _mutex;
  //std::queue<std::unique_ptr<T>> _queue; // ALTERNATIVE 1
  std::queue<T> _queue;
  size_t _size;
  std::condition_variable _condition_full;
  std::condition_variable _condition_empty;
};
#include "BQueue.hxx"
#endif // _BQUEUE_HPP

implementation

// BQueue.hxx
#include "BQueue.hpp"
#include <condition_variable>
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <queue>

template <class T> BQueue<T>::BQueue(size_t size) : _size(size) {}

// ALTERNATIVE 1
// template <class T> void BQueue<T>::push(std::unique_ptr<T> item) {
template <class T> void BQueue<T>::push(T item) {
  std::unique_lock<std::mutex> lock(_mutex);
  while (_queue.size() >= _size) {
    _condition_full.wait(lock, [&]() { return (_queue.size() < _size); });
  }
  _queue.push(std::move(item));
  // _queue.push(item); // ALTERNATIVE 1

  // if queue is full, notify consumation part first
  if (_queue.size() >= _size) {
    _condition_empty.notify_one();
  }
  _condition_full.notify_one();
}

// template <class T> bool BQueue<T>::pop(T &item) {
template <class T> bool BQueue<T>::pop(T &item) {
  std::unique_lock<std::mutex> lock(_mutex);
  while (_queue.empty()) {
    if (!_condition_empty.wait_for(lock, std::chrono::seconds(1),
                                   [&]() { return !_queue.empty(); })) {
      // waited too long for input.
      return false;
    }
  }
  item = std::move(_queue.front());
  // item = _queue.fron(); // ALTERNATIVE
  _queue.pop();
  /* THIS FOLLOWING CODE MAY BE NEEDED;
   * KEEP IT IN CASE
   * _condition_empty.notify_one();
   * // if queue is empty, notify production
   * if (_queue.empty()) { //*/
  _condition_full.notify_one();
  // assert(_queue.size() < _size); //*/
  return true;
}

main

// alternatively: class Resource
struct Resource {
  int x;
};

int main() {
  BQueue<std::unique_ptr<struct Resource>> q{40};
  //BQueue<struct Resource> q_alternative1[40};

  std::unique_ptr<struct Resource> res1{new struct Resource};
  res1->x = 42;
  q.push(std::move(res1));

  q.push(std::move(std::unique_ptr<struct Resource>{new struct Resource}));

  for (size_t i = 0; i < 30; i++) {
    std::unique_ptr<struct Resource> res{new struct Resource};
    res->x = i;
    q.push(std::move(res));
  }
  for (size_t i = 0; i < 15; i++)
    q.pop(res1);
  return 0;
}

Now, I came across the question of resource handling. What does make more sense? Using the shown code or implement the whole thing using std::unique_ptr where necessary (see ALTERNATIVE 1)? std::move even works with non-resource wrapped types, apparently.

And, is the main function leak-free or did I miss anything? Does it work for shared_ptr types as well, or do I have to specialize because of pop(T item &) being a reference?


texts:
Version 2 of Music note class

#!/usr/bin/env python3

from string import ascii_uppercase
from string import ascii_lowercase

class Notes:
    octave_number = 7
    low_notes = ascii_uppercase[:octave_number]
    high_notes = ascii_lowercase[:octave_number]
    notes = low_notes + high_notes
    notes_number = range(octave_number * 2)
    notes_dict = dict(zip(notes, notes_number))
    numbers_dict = dict(zip(notes_number, notes))

    def __init__(self, _note):
        if not _note in Notes.notes:
            raise Exception("Not a valid note")
        self.note = _note
        self.note_number = Notes.notes_dict[self.note]

    def add(self, n):
        if (self.note in Notes.high_notes) and (n > 0):
            raise Exception("You can only add to low notes (ABCDEFG)")
        if (self.note in Notes.low_notes) and (n < 0):
            raise Exception("You can only subtract from notes (abcdefg)")
        if(abs(n) > Notes.octave_number):
            raise Exception("Maximum amount of increase or decrease is %d" % Notes.octave_number)

        new_number = self.note_number + n
        return Notes(Notes.numbers_dict[new_number])

Test:

x = Notes("A")
x.add(7).note
x = Notes("b")
x.add(-6).note

Changes:

Removed minus method
Expanded notes to two octaves
add now returns a Notes object


texts: Image gallery with pagination using CSS, $_GET, and Bootstrap

texts:
I am relatively new to web development and I created an image gallery with pagination using the Twitter Bootstrap framework. Basically, I want to know if I approached creating an image gallery correctly and what I could do to improve. The basic idea was that each pagination
 element linked with a different get variable and I then used an array of images to update the view.

PHP

<?php

$dir = "./images/NYC/Gallery/";
$perPage = 18;
if($_GET['currentPage']) {
    $currentPage = $_GET['currentPage'];
} else {
    $currentPage = 1;
}

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $images = array();

        while (($file = readdir($dh)) !== false) {
            if (!is_dir($dir.$file)) {
                $images[] = $file;
            }
        }

        closedir($dh);
    }
}

$numImages = count($images);
$numPages = round($numImages / $perPage + 1);
if($currentPage == 8) {
    $images = array_slice($images, ($currentPage-1) * $perPage);
} else {
    $images = array_slice($images, ($currentPage-1) * $perPage, $perPage);
}
?>

HTML/CSS

<?php
    foreach($images as $image) {
        echo "

";
    }
?>

1

2

3

4

5

6

7

8


texts:
I wanted to make a dynamic select statement from this year to 10 years. This gets the job done, but I feel like it's a little much.

 form_dropdown('year', array_combine(range(date('Y'), date('Y')+10), range(date('Y'), date('Y')+10)), set_value('year'));

Specifically, is there a better way to create this array, other than this?

array_combine(range(date('Y'), date('Y')+10), range(date('Y'), date('Y')+10))

Desired output (at least for this year):

Array
(
    [2014] => 2014
    [2015] => 2015
    [2016] => 2016
    [2017] => 2017
    [2018] => 2018
    [2019] => 2019
    [2020] => 2020
    [2021] => 2021
    [2022] => 2022
    [2023] => 2023
    [2024] => 2024
)


texts: Thread-safe stack in Java with fixed capacity

texts:
Implement a multi-threaded stack, with freedom to use existing
  implementations of stack. On top of being thread-safe, it must block
  (not busy-wait) a pushing thread when stack is full and a popping
  thread when stack is empty. It must signal the threads out of sleep
  when stack has space again or elements to pop. Fairness is optional in this question.

How can I implement such a stack in Java? I came up with below implementation. Is this the correct way to solve above problem?

public class MyStack<E> {
  private final Stack<E> stack;
  private int max = 16;
  private final ReentrantLock lock = new ReentrantLock(true);
  private final Condition notEmpty = lock.newCondition();
  private final Condition notFull = lock.newCondition();

  public MyStack(int size) {
    this.stack = new Stack<>();
    this.max = size;
  }

  public void push(E e) {
    lock.lock();
    try {
      while (stack.size() == max) {
        notFull.await();
      }
      stack.push(e);
      notEmpty.signalAll();
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public E pop() {
    lock.lock();
    try {
      while (stack.size() == 0) {
        notEmpty.await();
      }
      E item = stack.pop();
      notFull.signalAll();
      return item;
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }
}


texts: Bash Script for file auditing, push information to server and be able to view in a web page

texts:
Edit: The goal of this Question was only seeking code review and guidance in learning or tips for improvement. I apologize if that was not clear or aligned properly with the goals of this forum.
Script Goal: audit file existence and differences between two red hat Enterprise Linux Servers

Place information in sql server tables to use for analysis
Maintain ability to view the diff in a web page

Process Steps
Set array with Directorys to check

Set array of file types to look for
Build a list of existing files for each Environment

Script will solve the following
If the files exist in both servers are they the identical? (md5)*

If no what is different (Diff)?
Does the file contain hard coded values (grep)

View Diff in web page (currently reading text file using into site php)

Code

DIR=(/Dir/Durp/DurpaDurp/Scriptdir1 /Dir/Durp/DurpaDurp/Scriptdir2 /Dir/Durp/DurpaDurp/Scriptdir3 )

f_Type=("*.sh" "*.txt" "*.log")
f_Type2=("*.img" "*.rpt" )

for((i=0; i<${#DIR[@]}; i++))
do
  echo "CHECKING: ${DIR[$i]}"
  cd "${DIR[$i]}"
      for((x=0; x<${#f_Type[@]}; x++))
       do
         echo "FOR FILE TYPE: ${f_Type[$x]}"
        find $PWD -type f -name "${f_Type[$x]}" | sed 's/^/ENV1|/'| column -t >> "$filelistENV1"
      done
if [[ ${DIR[$i]} == "/Dir/Durp/DurpaDurp/Script3" ]];
  then
     for((y=0; y<${#f_Type[@]}; y++))
    do
       echo "FOR FILE TYPE: ${f_Type2[$y]}"
      find $PWD -type f -name "${f_Type2[$y]}" | sed 's/^/ENV1|/'| column -t >> "$filelistENV1"
    done
fi
done

After these files are output to the text files the script will delete the existing data from a staging table in SQL Server 2008 R2 and insert the new data.

for((i=0; i<${#ENV[@]}; i++))
do
  sqlcmd -S $_DB_CONN -d $_DB  -Q "DELETE FROM ['$_DB']..['$_TABLE'] WHERE ENV = '${ENV[$i]}'";
done

bcp $_DB_CONN.."$_TABLE" in "$filelistENV1" -f "$_SCRIPTDIR/STG.fmt" -e $_ERRDIR/ERROR_STG$(date -d "today" +"%Y%m%d%H%M").txt -S $_DB_CONN -d "$_DB"

the format file creates 2 columns

AbsoluteFilePath | ENV
gets a list of files from the database to compare

`

sqlcmd -S $_DB_CONN -d $_DB -s "|" -h-1 -m -1 -W -i $_SCRIPTDIR/SQL/EXPORT_COMPARE.sql -o $_INPUT/comp_list.txt  set NOCOUNT ON;

compare the md5sum of the files.

for i in $(cat "$_INPUT/comp_list.txt")
do
export filename=$(basename "$i")
export path=$(dirname "$i")
env1_md5sum=$(md5sum "$i")
env1="${env1_md5sum%% *}"
export tmpdir=("$_TMPDIR$path")

if ssh "$_CONN" stat $path'$filename' \> /dev/null 2\>\&1
then
    env2_md5sum=$(ssh $_CONN "cd $path; find -name '$filename' -exec md5sum {} \;")
    env2_md5="${env2_md5sum%% *}"

    if [[ $env1_md5 == $env2_md5 ]]; then
        echo $filename $path >> "$matchingMD5"
    else
        echo "md5 does not match, getting copy of file"
        echo "$i" >> "$no_matchMD5"
        mkdir -p $tmpdir
        scp $_CONN:$i $tmpdir
    fi
fi done

run a diff on files that do not match

for x in $(cat "$no_matchMD5")
do
comp_filename=$(basename "$x")
env2file=(/"$ScriptsDir"/tmp"$x")
DIFF=$(diff --ignore-all-space --ignore-blank-lines --brief  "$x" "$env2file" &>/dev/null


texts: Encryption/Decryption between Python and Node JS

texts:
I have created a Python & Node JS encryption/decryption AES 256-CFB. The point of this little project is that I will encrypt a special URL with Python covered with base64 & URL encoding and then the Node JS will decrypt it.
For now the Node JS is working perfectly fine that can starts by decoding the URL, decoding the Base64 and then decrypt the AES with special password key. Meaning that I will have the same key for Node JS and Python to be able to decrypt. Something to add, this will not be added to any other clients/users meaning that covering the password is not needed since no one will reach the code ever but me :)
import base64
import hashlib
import urllib.parse

from Crypto import Random
from Crypto.Cipher import AES

key = "testing"  # Will of course be another password

def encrypt(url):
    """
    Encrypting the given url
    :param url:
    :return:
    """
    private_key = hashlib.sha256(key.encode()).digest()
    rem = len(url) % 16
    padded = str.encode(url) + (b'\0' * (16 - rem)) if rem > 0 else str.encode(url)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(private_key, AES.MODE_CFB, iv, segment_size=128)
    enc = cipher.encrypt(padded)[:len(url)]
    return base64.b64encode(iv + enc).decode()

def main():
    encrypted = urllib.parse.quote(encrypt("https://stackoverflow.com/"))
    url_decode = urllib.parse.unquote(encrypted)

    print(f'Encrypted and URL encoded: {encrypted}\n')
    print(f'URL decoded: {urllib.parse.unquote(url_decode)}\n')

if __name__ == '__main__':
    main()

Now I wonder if there is anyhow where I can improve the code in any how? In my eyes I don't see any ways to improve anyhow but I always end up be wrong :D


texts: Implementation of a property and a corresponding animated setter

texts:
There a various examples in UIKit where a class has a property and a corresponding method to set the property along with an animated property.

Examples include the progress and setProgress(_:animated:) of UIProgressView or the isEditing and setEditing(_:animated:) of UITableView.

In Objective-C you implement this by overriding the plain property setter to call the additional setter with the additional parameter:

- (void)setEditing:(BOOL)editing {
    [self setEditing:editing animated:NO];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    _editing = editing // set the instance variable

    // The rest of the code
}

The question is about doing this in Swift. The best I can come up requires using a private backing variable for the public computed property in addition to the corresponding animated setter.

private var _editing: Bool

public var isEditing: Bool {
    get { return _editing }
    set { setEditing(newValue, animated: false) }
}

public func setEditing(_ editing: Bool, animated: Bool) {
    _editing = editing

    // The rest of the code
}

Is there a better way to implement this pattern in Swift without the need to wrap a private property with a computed property à la Objective-C?


texts:
I am creating a shopping cart application to learn Spring MVC. I want to display a list of all categories and subcategories in more than one page. i.e; Home Page, Products page, and Category page.

In the Home Page controller I am retrieving the list of categories, subcategories and featured products and passing them to the home page:

@Controller
public class CatalogController {

    @Autowired
    private CategoryConfigService categoryConfigurationService;
    @Autowired
    private ProductConfigService productConfigurationService;
    private static final Logger logger = LoggerFactory
            .getLogger(CatalogController.class);

    /**
     * Catalog Controller method which retrieves the information required in the
     * application home page(Categories,SubCategories)
     *
     * @return Home Page View
     */
    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String returnHomePage(Model model) {
        logger.info("Processing information for home page");
        List<Category> categoriesList = categoryConfigurationService
                .getAllCategories();
        Map<Category, List<SubCategory>> categoryMap = new HashMap<Category, List<SubCategory>>();
        for (Category category : categoriesList) {
            List<SubCategory> subCategoryList = categoryConfigurationService
                    .getAllSubCategoriesByCategoryId(category.getId());
            categoryMap.put(category, subCategoryList);
        }
        model.addAttribute("categoryMap", categoryMap);
        model.addAttribute("featProd",
                productConfigurationService.getFeaturedProducts());

        return "home";
    }

}

What is the best way to store the object categoryMap in Spring to access it in the header page?

The header page is common for all the JSPs in my web application. So I have used the application context scope to store and retrieve the categoryMap.

What are the drawbacks of this approach? And are there any better ways of doing it?

I want to display the header page as shown in this image:


texts: Theme/skin swap... version 2! (CSS-driven)

texts:
I basically have an AJAX-fetched skin (html/css) that's loaded into a dummy element (id=SkinContainer) when the page is loaded, and then the content of one of its divs (contentdiv) is fetched with another AJAXHTTPRequest.

At any rate, when the page is loaded, the user can click a button to swap the theme/skin. Below is the (working) code for my theme swap, but I'm wondering whether or not it's the best way to do this:

function themeSwap() {
    var oldTheme = themeSelect;
    themeSelect++;
    if (themeSelect>2 || themeSelect<1) {themeSelect=1;}
    $('html').addClass('js');

    var tempContentDiv = document.getElementById("contentdiv");
    var tempContent = tempContentDiv.innerHTML;

    ReplaceJSCSSFile("css/skin" + oldTheme  + ".css", "css/skin" + themeSelect + ".css", "css");
    AJAX_LoadResponseIntoElement("skinContainer", "skin" + themeSelect + ".txt", function() {themeSwapCallback(tempContent)} );
}

function themeSwapCallback (tempContent) {
    initPage();
    document.getElementById("contentdiv").innerHTML = tempContent;
    setCookie("themeSelection",themeSelect,365);
}

What this basically does is stores the innerHTML of contentdiv into the "tempContent" variable, loads the new skin into skinContainer with an AJAX fetch, and then restores the original content by setting contentdiv's innerHTML to "tempContent."

The reason why it has to use an AJAX fetch on top of the CSS swap is because the structure of the elements changes.

Have I finally have this done correctly?  or is this still not perfect? :(


texts:
I wrote a rather inapt lotto simulator in Python, showing how long it would take to win the jackpot. I ran a similar application implemented in C and it is so much faster. I know you can't compare the two, but I wonder anyway if there is room for performance improvement in my code. By the way, I converted my code using Cython into C, with no speed gain.

import random, locale

locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
r_list = []
super_number = 0
my_super_number = 5
my_list = [[3, 4, 45, 7, 23, 33], [1, 2, 3, 4, 5, 6], [13, 43, 33, 15, 17, 18], [11, 14, 2, 17, 33, 13],
           [1, 2, 14, 15, 25, 26], [23, 26, 37, 40, 43, 44]]  # each list within corresponds to 1 games per drawing
match_list = []
iteration = 0
number_matches = 0

def fill_random_list():
    for i in range(6):
        # print (random.randint(1,49))
        r_list.append(random.randint(1, 49))

def return_matches(lista, listb):
    # print set(lista).intersection(listb)
    return set(lista).intersection(listb)

def return_number_matches(l_matches):
    if l_matches:
        return len(l_matches)

def print_communicate(v_iteration, v_number_matches, v_guess, v_r_list, v_match_list, v_super_number,
                      v_my_super_number):
    print (
    'Drawing No.: ' + locale.format("%d", v_iteration, grouping=True))
    print ('My guess: ' + str(sorted(v_guess)) + ', Super Number: ' + str(v_my_super_number))
    print ('Result :' + str(sorted(v_r_list)) + ', Super Number: ' + str(v_super_number))
    print ('My hits: ' + str(sorted(v_match_list)) + ', Amount of hits: ' + str(v_number_matches))
    print ('Time to win: ' + str(calculate_time_to_win(v_iteration)) + ' Years')
    print ('---------')

def calculate_time_to_win(v_drawings):
    return (v_drawings/2)/365  # calculate years assuming participation in 2 lotteries a week

def draw_lottery(v_hits, v_with_super_number):  #v_hits: number of hits until termination, v_with_super_number: include super number 'yes' or 'no'
    global iteration, number_matches, r_list, match_list, my_list, super_number, my_super_number
    jackpot = False
    while not jackpot:
        fill_random_list()  # draw lottery results
        super_number = random.randint(1, 9)  # draw super number
        for guess in my_list:
            match_list = return_matches(r_list, guess)
            number_matches = return_number_matches(match_list)
            if number_matches == v_hits:
                if v_with_super_number == 'yes':
                    if my_super_number == super_number:
                        print_communicate(iteration, number_matches, guess, r_list, match_list, super_number,
                                          my_super_number)
                        jackpot = True
                if v_with_super_number == 'no':
                    if my_super_number != super_number:
                        print_communicate(iteration, number_matches, guess, r_list, match_list, super_number,
                                          my_super_number)
                        jackpot = True
            match_list = []
            number_matches = 0

        if jackpot:
            break
        else:
            iteration += 1
            print 'Drawing No.: {0}'.format(iteration) + ' Years: {0}\r'.format(calculate_time_to_win(iteration)),
            r_list = []
            match_list = []
            number_matches = 0

def iterate(number):
    for i in enumerate(range(number), 1):
        print('Round: ' + str(i[0]))
        draw_lottery(6, 'no')

def main():
    iterate(1)
    print 'END!'

if __name__ == "__main__":
    main()


texts:
I have written a method for removing a link from a linked list for a phonebook project I'm currently working on and it works perfectly. However, I want to know whether or not my code is acceptable from a programmer's perspective. I tried to systematically structure it in a way such that it's understandable, but by doing so, this results in multiple if statements being nested inside one another.

Is this considered bad coding? Also, should I have used a recursive implementation instead? What do you think? Are there any ways to improve this code? Any constructive criticism is certainly welcome.

public Link removeLink(String surname, String firstName)
{
    Link currentLink = firstLink;
    Link previousLink = firstLink;
    if(isEmpty())
    {
        return null;    // Name was not found
    }
    // customer to delete is first element in the list
    else if((currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName))
    {
        firstLink = firstLink.next;
    }
    // customer is not the first element in the list
    else
    {
        // search until either the end of list is reached or a match is found
        while(currentLink.next!=null && !((currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName)))
        {
            previousLink = currentLink;
            currentLink = currentLink.next;
        }
        // if end of list is reached
        if(currentLink.next == null)
        {
            // check if there is a match with last element in list
            if((currentLink.surname).equals(surname) && (currentLink.firstName).equals(firstName))
            {
                previousLink.next = currentLink.next;
            }
            else
            {
                return null;
            }
        }
        // match is found somewhere in the middle of list
        else
        {
            previousLink.next = currentLink.next;
        }
    }
    numEntries--; // number of entries decrements each time a customer is deleted
    return currentLink; // return the entry that was deleted
}