texts:
This is based on a very similar question I asked, found here.

The intent of this program is to start with a set number of random strings of zeros and ones, and eventually evolve them to find one specific string ('111111').

It fulfils its purpose, but what do you think, and how can I improve it?

import random as r
import operator
import time
import os
target = '111111'

class String(object):
    def __init__(self, chromo):
        self.chromo = chromo
        self.fitness = 5
        self.age = 0
def Fitness(string):
    for char in string.chromo:
        if char == '1':
            string.fitness += 1
        else:
            pass

def SelectParents(strings):
    parents = []
    parents.append(max(strings, key=operator.attrgetter('fitness')))
    strings.remove(parents[0])
    parents.append(max(strings, key=operator.attrgetter('fitness')))
    strings.append(parents[0])
    return parents

def PartStringRand():
    string_complete = ''
    for _ in range(4):
        rand = r.randint(0, 1)
        string_element = str(rand)
        string_complete = ''.join([string_complete, string_element])
    return string_complete

def CreateChild(strings, parents):
    for children in range(2):
        string_complete = PartStringRand()
        string_complete += (parents[0].chromo[r.randint(0, 5)] + parents[1].chromo[r.randint(0, 5)])
        child = String(string_complete)
        strings.append(child)

def KillOld(strings):
    for _ in strings:
        if _.age > 2:
            strings.remove(_)

#First strings
strings = []

for _ in range(5):
    string_complete = ''
    for _ in range(6):
        rand = r.randint(0, 1)
        string_element = str(rand)
        string_complete = ''.join([string_complete, string_element])
    string = String(string_complete)
    strings.append(string)
    if string.chromo == "111111":
        strings.remove(string)
for string in strings:
    print string.chromo
raw_input()

#Start incremental mutation
c = 0
for _ in range(5000000):
    #os.system("cls")
    for string in strings:
        Fitness(string)
    parents = SelectParents(strings)
    CreateChild(strings, parents)
    for organism in strings:
        organism.age += 1
        print organism.chromo
        if organism.chromo == '111111':
            print "::...Successfully evolved specifc string '111111' from random strings...::"
            time.sleep(4)
            sys.exit()
    KillOld(strings)
    c += 1
    print "Generation: %s" %c
    #time.sleep(0.3)


texts:
I'm using three instances of ace editor in a form. I initialize them like so:

var before = ace.edit("beforeSQL", {
  showPrintMargin: false,
  fontSize: '14px',
  theme: "ace/theme/sqlserver",
  mode: "ace/mode/sql"
}),
execute = ace.edit("executeSQL", {
  showPrintMargin: false,
  fontSize: '14px',
  theme: "ace/theme/sqlserver",
  mode: "ace/mode/sql"
}),
after = ace.edit("afterSQL", {
  showPrintMargin: false,
  fontSize: '14px',
  theme: "ace/theme/sqlserver",
  mode: "ace/mode/sql"
});

I then put a listener on each one to make sure there's content in each field before the user can click the submit button:

  before.session.on('change', () => {
    toggleSubmit();
  });
  execute.session.on('change', () => {
    toggleSubmit();
  });
  after.session.on('change', () => {
    toggleSubmit();
  });

The toggleSubmit() function enables the submit button when each editor stores a value.

Both sections of code feel redundant, but the second section is what really concerns me. Anyone know a clever way to whittle this down? For example is there a way I could do the following:

[before.session, execute.session, after.session].on('change', () => {
  toggleSubmit();
});


texts:
I am producing a PHP code and I want to implement it in my server to do its function. My question is, are there any vulnerabilities that I should correct?

I tried to establish the session first then I will initiate a SQL connection and I will ask the user to enter his email. Also I added the reset function of his email.

<?php
if ($_SESSION['admin'] !== true) {
    header('Location: /login.php?');
}

$conn = new mysqli("localhost","admin","password","db");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$msg = '';
if (isset($_POST['submit'])) {
    $email = $_POST['email'];
    $sql = "SELECT * FROM users WHERE email = $email;";
    $result = @$conn->query($sql);
    if ($result->num_rows == 0) {
        die("This email: $email is incorrect");
    }
    $row = $result->fetch_assoc();
    $id = $row["id"];
    $surename = $row["surename"];

    $sql = "SELECT * from users JOIN password_resets ON (password_resets.user_id=users.id)  WHERE id=$id;";
    $result = @$conn->query($query);
    if ($result->num_rows == 0) {
        $insert_sql = "INSERT INTO password_resets (user_id, reset_timestamp) VALUES ($id, unix_timestamp());";
        if ($conn->query($insert_sql) !== TRUE) {
            die("Error: " . $insert_sql . "
" . $conn->error);
        }
    }
    $result = $conn->query($query);
    $row = $result->fetch_assoc();

    $link = "https://".$_SERVER['SERVER_NAME']."/reset.php?id=".$row['id'] ."&timestamp=".$row['reset_timestamp'];
    $message = "Hi, $surename,

    Here's your password reset link: $link";
    $headers = "From: ".$_SESSION['first_name']." ".$_SESSION['last_name']." <".$_SESSION['email'].">";
    mail($email,"Your password reset link",$message,$headers);
    $msg = "Password reset for $email sent!";
?>

<title>Reset password for a user</title>

  <form>

<?=$msg ?>

    <input type="text" width=80 name="email">
    <input type="submit" name="submit" value="Send">
  </form>

<?php
}


texts: Fetch text values from JSON and Display pop onclick text

texts:
I have below code which will fetch the text from json & onclick text , display pop up box in page.... Now i need to give options to change font-family, font color....

But Adding the code in the place of Content is going to be extremely difficult....

Is there any way so that i can improve code structure or write same code in another way ?

JSON :

{
          "font" : "Arian",
          "x" : 201,
          "y" : 461,
          "src" : "180ef82d1.otf",
          "width" : 679,
          "type" : "text",
          "text" : "Good Food",
          "name" : "edit_good_1"
}

script

const lightId = 'light' + layer.name
        const lightIdString = '#' + lightId
        $('.container').append(
            '<a id ="' + layer.name + '" onclick="openPopUp(' + lightId + ')"' +
            '
' + layer.text + '
' +
            '
 content Close

'
        );
        document.getElementById(lightId).style.left = layer.x + document.getElementById(layer.name).offsetWidth + 'px'

codepen : https://codepen.io/kidsdial/pen/OGbGwN

fiddle : https://jsfiddle.net/kidsdial1/z6eyq4j3/


texts:
I wrote this looping Caesar cipher with a default key. I'd love for some input on how I could make this operate better/more effectively.

#Et Tu, Brute? [Caesar's Cipher]
#loops?
#Determine type of cipher...
doLoop=("y")
while doLoop==("y"):
#yep. loops.
    det=input("Enter N for number or C for character; 'exit' to quit program ").lower() #lower case for simplicity! it don't care!
#Now the fun part!
#Numbers...
    if (det)==("n"):
        print("The default cipher key is 5")
        numRaw=input("Enter number to be decoded: ")
        if ord(numRaw)<ord("5"):
            numDec=ord(numRaw)+5
        else:
            numDec=ord(numRaw)-5
        print("The decoded number is: ",(chr(numDec)))

#Letters...
    if (det)==("c"):
        print("The default cipher key is 13")
        charRaw=input("Enter character to be decoded: ").lower() #lower case for simplicity!
        if ord(charRaw)<ord("m"):
            charDec=ord(charRaw)+13
        else:
            charDec=ord(charRaw)-13
        print("The decoded character is: " , (chr(charDec)))
    if det==("exit"):
        break


texts: Manhattan Distance + Linear Conflicts scoring function for sliding tile puzzle solver

texts:
I have written yet another n-puzzle solver.  I used the A* algorithm to search with the Manhattan Distance heuristic.  It worked very well for the 9-puzzle (3x3) but was unusable for most instances of the 15-puzzle (4x4.)  In fact I would exhaust all RAM before I got anywhere near the result.

So I switched to IDA* and the Manhattan Distance + Linear Conflicts heuristic.  Now I can solve most puzzles reasonably fast.  (e.g. one with a 50-move solution takes about 8s.)  However more difficult puzzles (the worst case for the 15-puzzle is 80 moves.) are still much too slow.  Profiling my code with Callgrind I saw that by far the most expensive part of the algorithm is calculating the heuristic which has to be done once for every node.  Any win here would be a tremendous improvement to the solvers overall speed.  So I present to you the current state of my code.  Can it be improved?

One thing you need to know to understand this function is that Board is a struct
with three members.  _height and _width which are the dimensions of the board.  and _tiles which is one-dimensional C-style array of uint8_t which represents the state of the board with each cell containing a number from 1 to (_height * _width - 1) or 0 to represent the blank square.

int ManhattanLinearConflict(Board& b) {
    int md = 0;

    // Pre-compute goals.
    uint8_t goalRow[b._height * b._width];
    uint8_t goalCol[b._height * b._width];

    for (uint8_t i = 0, length = b._height * b._width; i < length; i++) {
        if (b._tiles[i] == 0) {
            continue;
        }
        goalRow[i] = (b._tiles[i] - 1) / b._height;
        goalCol[i] = (b._tiles[i] - 1) % b._width;
    }

    for (auto row = 0; row < b._height; row++) {
        for (auto col = 0; col < b._width; col++) {
            // This part is just Manhattan distance.
            auto i = row * b._width + col;
            if (b._tiles[i] == 0) {
                continue;
            }
            md += abs(long(row - goalRow[i]));
            md += abs(long(col - goalCol[i]));

            // Two tiles I and J are in a linear conflict if I and J are
            // in the same line, the goal positions of I and J are both in
            // that line, I is to the right of J and goal position of I is
            // to the left of the goal position of J.
            if (goalRow[i] != row) {
                continue;
            }
            for (uint8_t j = row * b._width, l = j + b._width; j < l; j++) {
                if (j == i || b._tiles[j] == 0) {
                    continue;
                }
                if (goalRow[j] == row && b._tiles[i] > b._tiles[j] &&
                goalRow[i] < goalRow[j]) {
                    md += 2;
                }
            }
        }
    }

    return md;
}


texts:
I recently started my first project with Erlang. I've been skimming documentation and various books to get the information I need, and it's going well, but now that I have something that works I want to go "back to the basics" to fill in some holes in my knowledge, and more importantly, my style. So I took a look at some exercises in the book "Programming Erlang", and this one struck me as one I could implement and post here to get feedback on one topic I feel I'm implementing "sub-optimally" to say the least.:

-module(scratch).
-author("Oak").

%% API
-export([new/0,destroy/1,write/3,read/2,match/2]).

new()-> {db,[]}.

destroy({db,_Data})->{db,[]}.

write(Key,Element,{db,Data}) -> {db,[{Key,Element}|Data]}.

read(_Key,{db,[]})-> error(no_instance);
read(Key,{db,[{CurKey,CurValue}|_Data]}) when Key =:= CurKey-> CurValue;
read(Key,{db,[{_CurKey,_CurValue}|Data]}) -> read(Key,{db,Data}).

match(_Element,{db,[]})->[];
match(Element,{db,[{CurKey,CurValue}|Data]}) when Element =:= CurValue -> [CurKey | match(Element,{db,Data})];
match(Element,{db,[{_CurKey,_CurValue}|Data]}) -> match(Element,{db,Data}).

I'd like to know if the pattern matching I'm using is in line with the style that's expected when coding in Erlang. I could think of multiple ways of doing this, but this is what comes "naturally" to me right now, I'm not sure how elegant it is. I'm looking for tips about style more than the actual "algorithm", but if there are any glaring mistakes feel free to point them out.


texts: Utilizing Moviepy's fl_image function efficiently to modify an incoming video

texts:
This is a followup question from this question of mine. I used the suggested function provided by an answer in my current code. 'model' is a dictionary loaded from the pickle file. 'loadpickle' and findScale are helper functions. So, I load the model, and other variables and read the moviepy frame by frame. The moviepy's fl_image function is used to convert every frame through a rolling buffer. The buffer has to be updated in the 'filtered_output' function itself. Now, I have an impression that the function supplied to fl_image can take only one input (i.e. the frame) and can return only one output (i.e. the output frame). Hence I had to make 'buffer' global. Also, I have been assuming that constants like scale and clip_size do not need to be included in the function definition of the 'filtered_output' function, and also it is necessary for fl_image function.

path=os.getcwd()
model=loadpickle('file.pkl')
scale=findScale(model)
clip_size=(240L,320L,3L)
Scaling=1.5
Offset=0
clip=moviepy.editor.VideoFileClip('input.mp4',audio=False) #Greyscale Video - all 3 channels are the same in the frames
bufshape=15,clip_size[0],clip_size[1]
buffer=np.zeros(BufShape, dtype=float)
modified_clip = clip.fl_image(filtered_output)
print type(modified_clip)
modified_clip.write_videofile(os.path.join(path,'output.mp4'))

def filtered_output(image):
    global buffer
    finalOut=np.zeros(image.shape, dtype=float)
    scaled_frame=Scaling*(image[:,:,0]/ 255.)+Offset
    # padding is required
    top, left = model['item']
    width, height = model['item1'].shape
    bottom = height - top - 1
    right = width - left - 1
    # Create a copy of our current frame, with appropriate padding
    frame = cv2.copyMakeBorder(scaled_frame, top, bottom, left, right, cv2.BORDER_CONSTANT, value=0.5)
    convolved_frame = scipy.signal.convolve2d(frame, model['item1'], boundary='symm', mode='valid')
    buffer = np.vstack((buffer[1:], convolved_frame))
    # Apply kernel
    temp = np.sum(model['TempKern'] * buffer, axis=0)
    temp = np.nan_to_num(temp)
    output_frame = ApplyCubicSpline(model['CubicSplineCoeffs'], temp) * scale
    for i in range(len(finalOut.shape)):
       finalOut[:,:,i]=output_frame # copying frames to make it 3 channels again
    return finalOut

So, from this code review I wish to know, whether my assumptions are right. If not, then how do I make this moviepy fl_image work?


texts: Return a rank for string of letters based on alphabetical permutations

texts:
So, first off, a little bit of unrelated information: I am preparing for a technical interview. I was reading this article, How to Prepare for (and Ace) the Technical Interview, by Rich Hein and I decided to try to tackle the problem he uses as an example.

From the article:

  We are looking for a solution that is compact and runs quickly. What quickly means to us depends on the language you use, but it should take no longer than 500 milliseconds to run. Please use what language you are most comfortable with. However, please know that we do not have Visual Studio so C++ solutions should have the ability to compile with the standard G++.

  Problem:
  Consider a word as any sequence of capital letters A-Z, not limited to just dictionary words. For any word with at least two different letters there are other words composed of the same letters but in a different order. For instance, stationarily and antiroyalist, which happen to both be dictionary words. For our purpose alianrostily is also a word composed of the same letters as these two. We can then assign a number to every word based on where it falls within an alphabetically sorted list of all words made up of the same set of letters.

  One way to do this would be to generate the entire list of words and then find the desired ones, but this would be slow if the word is long. Write a program that takes a word as a command line argument and prints to standard output its number. Do not use the method above of generating the entire list. Your program should be able to accept any word 25 letters or less in length possibly with some letters repeated. It should use no more than 1 gig of memory and take no more than 500 milliseconds to run.

emphasis mine

So, this is my summarized understanding of the problem:

  Create a function that accepts a capitalized string of letters. You are tasked with finding its alphabetical ranking among the possible permutations for that given input. Your method should return the integer ranking. Do not store a list of the permutations.

What I first did was open up Excel and using the following example dacb come up with an equation of how to do this:

Then, I wrote the program as a C# Console Application:

using System;
using System.Collections.Generic;

namespace WordAlphabeticalRank
{
    class Program
    {
        static void Main(string[] args)
        {
            var testArray = new []{ "DACB", "CA", "FLCR", "RTZX" };

            foreach (var test in testArray)
            {
                Console.WriteLine("Alphabetical rank of \"{0}\": {1}", test, AlphabeticalRank(test));
            }

            Console.Read();
        }

        public static int AlphabeticalRank(string s)
        {
            var rankingArray = new List<char>(s.ToCharArray());
            rankingArray.Sort();
            var score = 1; //this is the lowest possible rank

            for(int i = 0; i < s.Length -1; i++){

                var rank = rankingArray.IndexOf(s[i]);
                score += Factorial(rank) * rank;

                rankingArray.RemoveAt(rank);
            }

            return score;
        }

        public static int Factorial(int n)
        {
            var product = 1;
            for (int i = n; i > 0; i--)
            {
                product *= i;
            }

            return product;
        }
    }
}

The above program, when run outputs:

  Alphabetical rank of "DACB": 20
  Alphabetical rank of "CA": 2
  Alphabetical rank of "FLCR": 3
  Alphabetical rank of "RTZX": 2

So, what points can I improve on? Did I understand the problem correctly? (I wasn't able to ask questions, but I definitely would have because I have some questions about the wording and examples). Was Excel a good idea? Is my solution easy to understand? And, last but not least, does it meet the requirements?


texts: Xamarin Forms with Ninject navigation service

texts:
I am new to Xamarin Forms and I have been searching online finding ways to set up navigation in a MVVM fashion. In particular I am designing around a concept I found here. However, I am using Ninject to have a ViewModelLocator type object in my application.

Here is the code to my Locator object:

public class Locator
{
    private readonly IKernel _kernel;

    public const string MainPage = "MainPage";
    public const string AlertPage = "AlertPage";

    public Locator(INavigationService navigationService)
    {
        //Setup services
        _kernel = new StandardKernel();
        _kernel.Bind<INavigationService>().ToConstant(navigationService);
        _kernel.Bind<IDialogService>().To<DialogService>();
    }

    public MainViewModel MainViewModel
    {
        get { return _kernel.Get<MainViewModel>(); }
    }

    public AlertViewModel AlertViewModel
    {
        get { return _kernel.Get<AlertViewModel>(); }
    }
}

Now instinctively something is telling me that it may be a smell to have my locator require a INavigationService, because my locator should not be concerned with this, right?

The reason I am doing this is because my NavigationService requires some configuration to map the views. I did attempt to bind the NavigationService as I did the dialog service, and then resolved it in my application start up and set the configurations, but it didn't seem to keep these configurations when it resolved my view model dependencies, e.g., the views could not be found in the dictionary. (No longer an issue, just a side note)

Here is the code in my application startup:

public App()
{
    InitializeComponent();

    //setup navigation service
    var navigation = new NavigationService();
    navigation.Configure(Locator.MainPage, typeof(MainPage));
    navigation.Configure(Locator.AlertPage, typeof(AlertPage));

    //Instantiate locator and add to resources for XAML reference
    Locator locator = new Locator(navigation);
    Current.Resources.Add("ServiceLocator", locator);

    //Create root navigation page
    var nav = new NavigationPage(new MainPage());

    //Assign main page and initialize navigation
    MainPage = nav;
    navigation.Initialize(nav);
}

Just in case you are wondering about the addition of the locator as an application resource, here is an example of how I am using that -- if you find it relevant:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             BindingContext="{Binding Path=AlertViewModel, Source={StaticResource ServiceLocator}}"
             x:Class="MvvmApp.Views.AlertPage">
    <ContentPage.Content>
        <StackLayout>
            <Entry x:Name="messageEntry" />
            <Button Text="Show Alert"
                    Command="{Binding ShowAlertCommand}"
                    CommandParameter="{Binding Source={x:Reference messageEntry}, Path=Text}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

So ultimately my question is: Is what I am doing considered fundamentally wrong or a smell?


texts: Retrieve value from a formula in cells into different merged cells and retrieved value can be edited

texts:
I have created this macro and having a small issue. I am very new to this VBA and did this with experts’ guides by googling it. I am creating an excel form for a work purpose at work. The Excel form has 7 sheets and each have named tables with different data.

1st sheet is the editable form, which retrieves data from the tables in the different sheets. This is the only visible sheet, and other sheets are protected and hidden,
1st sheet has hidden rows and columns those have logical formulas that assist me to retrieve my data from the other tables, so cells with formulas (mostly-vlookup, index, match, if, or) are in those rows and columns.
I want the user to edit on the retrieved data, which is kind of suggestion to the user for to use it as-is or edit on it if required.
I cannot write vlookup or loop kind of events, so I created below macro that allows me to retrieve the value of the formula as a text (not editable) in different cell, then retrieve that text to another merged and named cell as editable text.
This macro works fine, but when I add more and more data into the Excel and add other macros, then it is quit slow.

Is it possible to this and make it function faster?

This macro applies to Sheet 1.

Private Sub Worksheet_Change(ByVal Target As Range)
    'Value as text - kind of copy+pastespecial
    If Range("F17").Value <> Range("E17").Text Then
        Range("F17").FormulaR1C1 = Range("E17")
        Range("func_R").FormulaR1C1 = Range("F17")
             'func_R and other cells below with "_R" are my merged and main cells that users will see. E17 has a vlookup formula that retrieve data from a table in Sheet 2, with this macro I copy and pastpecial the formula in E17 in F17 as a text. Then to make it editable text I copy and paste it into the merged cell with "_R".Texts in cells with "_R" come from same table in sheet 2.
        ElseIf Range("F18").Value <> Range("E18").Text Then
            Range("F18").FormulaR1C1 = Range("E18")
            Range("job_R").FormulaR1C1 = Range("F18")
        ElseIf Range("F20").Value <> Range("E20").Value Then
            Range("F20").FormulaR1C1 = Range("E20")
            Range("purp_R").FormulaR1C1 = Range("F20")
        ElseIf Range("F22").Value <> Range("E22").Value Then
            Range("F22").FormulaR1C1 = Range("E22")
            Range("duty_R").FormulaR1C1 = Range("F22")
        ElseIf Range("F25").Value <> Range("E25").Value Then
            Range("F25").FormulaR1C1 = Range("E25")
            Range("ikey_R").FormulaR1C1 = Range("F25")
        ElseIf Range("F26").Value <> Range("E26").Value Then
            Range("F26").FormulaR1C1 = Range("E26")
            Range("ekey_R").FormulaR1C1 = Range("F26")
        ElseIf Range("F28").Value <> Range("E28").Value Then
            Range("F28").FormulaR1C1 = Range("E28")
            Range("iimp_R").FormulaR1C1 = Range("F28")
        ElseIf Range("F29").Value <> Range("E29").Value Then
            Range("F29").FormulaR1C1 = Range("E29")
            Range("eimp_R").FormulaR1C1 = Range("F29")
        'Generel requirement - it is basicly same as above, but data comes from different table in Sheet 3.
        ElseIf Range("F31").Value <> Range("E31").Value Then
            Range("F31").FormulaR1C1 = Range("E31")
            Range("req_1").FormulaR1C1 = Range("F31")
        ElseIf Range("F32").Value <> Range("E32").Value Then
            Range("F32").FormulaR1C1 = Range("E32")
            Range("req_2").FormulaR1C1 = Range("F32")
        ElseIf Range("F33").Value <> Range("E33").Value Then
            Range("F33").FormulaR1C1 = Range("E33")
            Range("req_3").FormulaR1C1 = Range("F33")
        ElseIf Range("F34").Value <> Range("E34").Value Then
            Range("F34").FormulaR1C1 = Range("E34")
            Range("req_4").FormulaR1C1 = Range("F34")
        ElseIf Range("F35").Value <> Range("E35").Value Then
            Range("F35").FormulaR1C1 = Range("E35")
            Range("req_5").FormulaR1C1 = Range("F35")
        End If
    End Sub


texts: Filtering on an array of object literal properties and their nested array values

texts:
This is a function which filters on multiple object properties and their corresponding arrays.

I need to match all properties to a pattern and have an array as their property value.
Properties that match that pattern and contain an array get filtered on whether they contain string values.
The values can be in any one of the arrays related to that object.
All objects which have met the criteria and contain the appropriate strings irrespective of the property array they are contained in. With the exception being that all values are in the same object.
The object containing all string values do not get filtered out.

If I match all object properties containing 'ev_' and those properties contain arrays whose values include 'value75' and '12+'

This should be the resulting output

{
  "data": {
    "id": 3,
    "date": "2019-02-03",
    "ev_filter_1": [
      "art",
      "foodie"
    ],
    "ev_filter_2": [
      "value1",
      "value75"
    ],
    "ev_filter_3": [
      "value1",
      "value2"
    ],
    "ev_filter_4": [
      "all",
      "12+"
    ]
  }
}

From this array of objects

const posts = [{
    data: {
      id: 1,
      date: "2019-02-03",
      ev_filter_1: ["art", "foodie"],
      ev_filter_2: ["value1", "value2"],
      ev_filter_3: ["value1", "value2"],
      ev_filter_4: ["all", "12+"]
    }
  },
  {
    data: {
      id: 2,
      date: "",
      ev_filter_1: ["arti", "foodie"],
      ev_filter_2: ["value1", "value2"],
      ev_filter_3: ["value1", "value2"],
      ev_filter_4: ["all", "19+"]
    }
  },
  {
    data: {
      id: 3,
      date: "2019-02-03",
      ev_filter_1: ["art", "foodie"],
      ev_filter_2: ["value1", "value75"],
      ev_filter_3: ["value1", "value2"],
      ev_filter_4: ["all", "12+"]
    }
  }
];

This example is currently working but it is ugly and rigid. The "some" is just used for iteration, which I painfully coerced to return true. There is also a nested if statement (horrid).

const posts = [{
    data: {
      id: 1,
      date: "2019-02-03",
      ev_filter_1: ["art", "foodie"],
      ev_filter_2: ["value1", "value2"],
      ev_filter_3: ["value1", "value2"],
      ev_filter_4: ["all", "12+"]
    }
  },
  {
    data: {
      id: 2,
      date: "",
      ev_filter_1: ["arti", "foodie"],
      ev_filter_2: ["value1", "value2"],
      ev_filter_3: ["value1", "value2"],
      ev_filter_4: ["all", "19+"]
    }
  },
  {
    data: {
      id: 3,
      date: "2019-02-03",
      ev_filter_1: ["art", "foodie"],
      ev_filter_2: ["value1", "value75"],
      ev_filter_3: ["value1", "value2"],
      ev_filter_4: ["all", "12+"]
    }
  }
];

function sift(arrObjLit, pattern, argOne, argTwo) {
  return arrObjLit.filter(function(x, y) {
    return (result = Object.entries(x).some((q, i) => {
      for (let [key, v] of Object.entries(q[1])) {
        if (key.startsWith(pattern) && Array.isArray(v) && v.includes(argOne)) {
          for (let an of Object.values([x.data][0])) {
            if (Array.isArray(an) && an.includes(argTwo)) {
              return true;
            }
          }
        }
      }
    }))
  })
}

console.log(...sift(posts, "ev_", "value75", "12+"));


texts: Project Euler #14: Longest Collatz sequence

texts:
Problem :  source
Which starting number, under one million, produces the longest chain?
n → n/2 (n is even)
n → 3n + 1 (n is odd)

I want to receive advice on my code.
It is too slow... It takes 514 seconds

import math
from functools import reduce
import time
start_time = time.time()

target = int(math.pow(10,6))
first_list = list(map(lambda x : x , range(1,target+1)))
def chain_operate(given_list):
    given_list = [0 if x == 1 else x for x in given_list]
    new_list = list(map(lambda x : x/2 if x%2==0  else 3*x+1 , given_list))
    new_list = [0 if x == 1 else x for x in new_list]
    # replace 1 to 0 because of below condition : while max(new_list) != reduce(lambda x,y : x+y, new_list)

    while max(new_list) != reduce(lambda x,y : x+y, new_list): # when the list comes to (0,0,0,4,0,0), break
        new_list = chain_operate(new_list)[0] #recursive method

    return (new_list,new_list.index(max(new_list)))

print(chain_operate(first_list)[1]+1)
print("--- %s seconds ---" % (time.time() - start_time))


texts: Make C# Unity Script database methods more re-usable and concise

texts:
I have a C# file, that makes some modifications on screen (changes the text on the user interface) but I have some doubts:

How I can re-use the below methods to be more concise and reusable?
How I can separate the database methods in another file class?

private void GetDoencaNome(){
    using(IDbConnection dbConnection = new SqliteConnection(connectionString)){
        dbConnection.Open();

        using(IDbCommand dbCommand = dbConnection.CreateCommand()){
            string sqlQuery = "SELECT nome FROM doenca WHERE id=@id";
            dbCommand.Parameters.Add(new SqliteParameter("@id", doencaId));
            dbCommand.CommandText = sqlQuery;

            using(IDataReader reader = dbCommand.ExecuteReader()){
                while(reader.Read()){
                    doenca.nome = reader.GetString(0);
                }
            }
        }
    }
}

private void GetDoencaDescricao(){
    using(IDbConnection dbConnection = new SqliteConnection(connectionString)){
        dbConnection.Open();

        using(IDbCommand dbCommand = dbConnection.CreateCommand()){
            string sqlQuery = "SELECT descricao FROM descricao_doenca WHERE id=@id";
            dbCommand.Parameters.Add(new SqliteParameter("@id", doencaId));
            dbCommand.CommandText = sqlQuery;

            using(IDataReader reader = dbCommand.ExecuteReader()){
                while(reader.Read()){
                    doenca.descricao = reader.GetString(0);
                }
            }
        }
    }
}

private void GetDoencaSintomasIds(){
    using(IDbConnection dbConnection = new SqliteConnection(connectionString)){
        dbConnection.Open();

        using(IDbCommand dbCommand = dbConnection.CreateCommand()){
            string sqlQuery = "SELECT sintoma_id FROM doenca_sintoma WHERE doenca_id=@id";
            dbCommand.Parameters.Add(new SqliteParameter("@id", doencaId));
            dbCommand.CommandText = sqlQuery;

            using(IDataReader reader = dbCommand.ExecuteReader()){
                while(reader.Read()){
                    listaIds.Add(reader.GetInt32(0));
                }
            }
        }
    }
}

private void GetDoencaSintomas(){
    using(IDbConnection dbConnection = new SqliteConnection(connectionString)){
        dbConnection.Open();

        using(IDbCommand dbCommand = dbConnection.CreateCommand()){
            string sqlQuery = "SELECT descricao FROM sintoma WHERE";
            sqlQuery += " id=" + listaIds[0].ToString();
            for(int i = 1; i < listaIds.Count; i++){
                sqlQuery += " OR id=" + listaIds[i].ToString();
            }
            dbCommand.CommandText = sqlQuery;

            using(IDataReader reader = dbCommand.ExecuteReader()){
                while(reader.Read()){
                    doenca.sintomas.Add(reader.GetString(0));
                }
            }
        }
    }
}


texts:
I am embedding my size in a Stream in the first 4 byte.  When I think about it, it should be possible to do it better, but that depends.

Here is how I currently do it:

bsize = ms.Length;
tcp.GetStream().Write(BitConverter.GetBytes(bsize), 0, intsize);
tcp.GetStream().Write(ms.GetBuffer(), 0, (int)bsize);

As you can see, it works and it's nothing weird.  I just send 2 streams, the first being the length and the other being the data.

So, there aren't many things that can be done to improve or even change this.

But my idea is: why use 2 streams when you can probably embed the size immediately on the second, so you only need to write it once?

Sadly, I am not sure how to do that, or if it's even an improvement.  Here is my testing code to achieve it:

bsize = ms.Length;
ms.Write(BitConverter.GetBytes(bsize), 0, intsize);
ms.Position = 0;
tcp.GetStream().Write(ms.GetBuffer(), 0, (int)bsize+4);

So, I thought: why can't you just write the length to the MemoryStream and add it before the actual data?

But, it doesn't work, and I am not sure if it's adding or overwriting data.  I suppose it's overwriting, which means it won't work.

From my testing, I think Write adds data to the end, which complicates things.


texts:
I created a simple text to morse code converter in python, and was wondering if there was an easier/shorter way to do this. Is there a way to generate the dictionary without having to hard-code every single option?
def main():

    print("This program translates words to morse code\n")

    words = input("Enter a word or phrase to be encoded: ")
    words = words.upper()

    codeDict = createDict()

    i = 0

    try:
        while (i < len(words)):
            if (words[i] != " "):
                print(codeDict[words[i]], end = " ")
            else:
                print("/", end = " ")
            i += 1
    except:
        print("\nInvalid characters found - refer to morse code alphabet")

def createDict():
    code = {'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': '--..',
            '1': '.----',
            '2': '..---',
            '3': '...--',
            '4': '....-',
            '5': '.....',
            '6': '-....',
            '7': '--...',
            '8': '---..',
            '9': '----.',
            '0': '-----'}

    return code

main()


texts: Javascript filter class to hide and show content on data-attributes

texts:
I'm a hacker, not a trained engineer.  I ask/answer specific questions on StackOverflow and am pretty confident in my ability to get the browser to do what I want, I thought I could benefit a great deal from a code review- hopefully I'm in the right place.

Please tear down my bright-eyed naivetie with cutting comments on code style, design, etc if I am and let me know if this isn't what this site is for.

This is a filter class that hides and shows long lists of content in container divs based on the content meta data.  A sample content div:

<div class="todd.packer StreamContent"
  data-username="todd.packer"
  data-topic_id="13"
  data-post_id="1394">
  ...
</div>

The class itself (relies on JQuery):

function StreamFilter(_containerId, _testAttribute, _targetStyleClass, _applyStyleClass, _testFor){
    return{
        active : false,
        filterHash : {},
        testFor : _testFor,
        CONTAINER_ID : _containerId,
        TEST_ATTRIBUTE : _testAttribute,
        TARGET_STYLE_CLASS : _targetStyleClass,
        APPLY_STYLE_CLASS : _applyStyleClass,

        on : function(){
            this.active = true;
            this.enforce();
        },

        off : function(){
            this.clear();
            this.active = false;
            this.unenforce();
        },

        clear : function(){
            this.filterHash = {};
        },

        add_key : function(_key){
        // messages with matching metadata will be displayed
            this.filterHash[_key] = true;
        },

        filter_only : function(_key){
            this.clear();
            this.add_key(_key);
            this.on();
        },

        test : function(_key){
            return(this.filterHash[_key]);
        },
        render : function(_$object){
            if(this.active && ((this.test(_$object.attr(this.TEST_ATTRIBUTE)) === true) === this.testFor)){
                _$object.addClass(this.APPLY_STYLE_CLASS);
            }
            return _$object;
        },

        enforce : function(){
            var i;
        // possible performance problems
            $("#" + this.CONTAINER_ID + " ." + this.TARGET_STYLE_CLASS).addClass(this.APPLY_STYLE_CLASS);
            //first hide everything...
            for(i in this.filterHash){
                    // For each attribute and value in add_key, remove the hidden class
                    $("[" + this.TEST_ATTRIBUTE + "='" + i + "']").removeClass(this.APPLY_STYLE_CLASS);
            }
        },

        unenforce : function(){
            $("#" + this.CONTAINER_ID + " ." + this.TARGET_STYLE_CLASS).removeClass(this.APPLY_STYLE_CLASS);
        }
    };
}


texts: Hierarchical data structure using classes

texts:
My code implements the following structure :Module contains Submodule contains Ability contains Template. There is so much repetition that I'm sure there is a better way.

class Module:
    def __init__(self, name, lang):
        assert lang in ['fr', 'en']
        self.name = name
        self.lang = lang
        self.submodules = {}

    def add_submodule(self, submodule):
        assert isinstance(submodule, Submodule)
        assert submodule.name not in self.submodule
        self.submodules[submodule.name] = submodule

class Submodule:
    def __init__(self, name, module):
        self.name = name
        self.link_with(module)
        self.abilities = {}

    def add_ability(self, ability):
        assert isinstance(ability, Ability)
        assert ability.name not in self.abilities
        self.abilities[ability.name] = ability

    def link_with(self, module):
        assert isinstance(module, Module)
        self.module = module
        module.add_submodule(self)

class Ability:
    def __init__(self, name, submodule):
        self.name = name
        self.link_with(submodule)
        self.templates = {}

    def add_template(self, template):
        assert isinstance(template, Template)
        assert template.name not in self.templates
        self.templates[template.name] = template

    def link_with(self, submodule):
        assert isinstance(submodule, Submodule)
        self.submodule = submodule
        submodule.add_ability(self)

class Template:
    def __init__(self, name, ability):
        self.name = name
        self.link_with(ability)
        self.lang = ability.submodule.module.lang

    def link_with(self, ability):
        assert isinstance(ability, Ability)
        self.ability = ability
        ability.add_template(self)

I could have coded a global function "link_to_parent" and set 'childs' sets and 'parent' set but I prefer to be able to do : ability.submodule.module instead of doing ability.parent.parent which is not explicit enough.


texts:
I have adapted a VBA code to import all the XML files I have on a folder into Excel. I have tried to run the code with only two files and it takes about 30 seconds. Several minutes to import less than 20 files.

I need to import more than 200,000 files. Can you please help me on how to improve my code?

Sub ListFiles()
'DECLARE AND SET VARIABLEs
Dim ShellApplication As Object
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set ShellApplication = CreateObject("Shell.Application").BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
Path = ShellApplication.self.Path
Set ShellApplication = Nothing
[a3] = "XML"
[b3] = "Files"
'DEFAULT PATH FROM HIDDEN SHEET
Call ListMyFiles(Path, True)
End Sub

Sub ListMyFiles(mySourcePath, IncludeSubfolders)
    Set MyObject = New Scripting.FileSystemObject
    Set mySource = MyObject.GetFolder(mySourcePath)
    'With SearchXML
    Application.ScreenUpdating = False

'--------------------------------------------------------------------
    'FIND XML FILES ONLY, APPLY SEARCH CRIERIA, DISPLAY MATCHES ONLY
    For Each myfile In mySource.Files
        If Right(myfile.Name, 3) = "XML" Or Right(myfile.Name, 3) = "xml" Then 'IS XML?
            LastRow = ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row

 '-------------------------------------------------------------
            'IMPORT XML FILE
            Application.DisplayAlerts = False
            ActiveWorkbook.XmlImport URL:=mySource & "\" & myfile.Name, _
                ImportMap:=Nothing, Overwrite:=True, Destination:=Range("$B$" & LastRow + 1)
            Cells(LastRow + 1, 1) = myfile.Name

'------------------------------------------------------------
            'DELETE MAPS
            maps = ActiveWorkbook.XmlMaps.Count
            For i = 1 To maps
                ActiveWorkbook.XmlMaps(1).Delete
            Next i
        End If
    Next
    If IncludeSubfolders Then 'SEARCH SUBFOLDERS FOR SAME CRITERIA
        For Each MySubFolder In mySource.SubFolders
            Call ListMyFiles(MySubFolder.Path, True)
        Next
    End If
    'End With
    Application.ScreenUpdating = True
Application.DisplayAlerts = True
Sheets("XMLData").UsedRange.WrapText = False
End Sub


texts: Sensor logger for Raspberry Pi in a stratospheric probe

texts:
I'm writing a Python Script for a Raspberry Pi to measure different sensors. We are planning to send the Pi with that Script running to the stratosphere, so the power usage for the Pi is limited.

I excuse myself in advance for the code, I had no prior experience with Python.
Are there any ways I can make this code more battery friendly? Would it be beneficial to write 10 rows at once instead of writing one row at a time?

#!/usr/bin/env python3

from sense_hat import SenseHat
import time
import csv
import datetime

sense = SenseHat()
sense.clear()
sense.set_imu_config(True, True, True)
sense.low_light = True

with open('data.csv', mode='w') as file:
    writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['Zeit','Temperatur1', 'Temperatur2', 'Temperatur3',     'Luftdruck', 'Luftfeuchtigkeit', 'Yaw', 'Pitch', 'Roll', 'Compass X', 'Compass     Y', 'Compass Z', 'Gyro X', 'Gyro Y', 'Gyro Z'])

with open('acc.csv', mode='w') as file:
    writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['Zeit','Acc_X','Acc_Y','Acc_Z'])

with open('log.csv', mode='w') as file:
    writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['Zeit','Fehler'])

# Farben definieren
red = (255, 0, 0)
green = (0, 255, 0)
black = (0,0,0)

def writeDataToCsv(temperature, temperature2, temperature3, pressure, humidty,     yaw, pitch, roll, mag_x, mag_y, mag_z, gyro_x, gyro_y, gyro_z):
    with open('data.csv', mode='a') as file:
        writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
        writer.writerow([datetime.datetime.now(),temperature, temperature2,     temperature3, pressure, humidty, yaw, pitch, roll, mag_x, mag_y, mag_z,     gyro_x, gyro_y, gyro_z])

def writeAccelerationToCsv(x,y,z):
    with open('acc.csv', mode='a') as file:
        writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
        writer.writerow([datetime.datetime.now(),x,y,z])
        sense.set_pixel(0, 0, green)
        time.sleep(.05)
        sense.set_pixel(0, 0, black)

def main():
    sense.set_pixel(0, 0, black)
    counter = 0
    try:
        while True:
            #Region Acceleration
            acceleration = sense.get_accelerometer_raw()
            acc_x = acceleration['x']
            acc_y = acceleration['y']
            acc_z = acceleration['z']
            writeAccelerationToCsv(acc_x,acc_y,acc_z)
            time.sleep(.250)
            counter+=1

            #Region Data
            if(counter == 4):
                temperature = sense.get_temperature()
                temperature2 = sense.get_temperature_from_humidity()
                temperature3 = sense.get_temperature_from_pressure()

                pressure = sense.get_pressure()
                humidty = sense.get_humidity()

                orientation = sense.get_orientation()
                yaw = orientation["yaw"]
                pitch = orientation["pitch"]
                roll = orientation["roll"]

                mag = sense.get_compass_raw()
                mag_x = mag["x"]
                mag_y = mag["y"]
                mag_z = mag["z"]

                gyro = sense.get_gyroscope_raw()
                gyro_x = gyro["x"]
                gyro_y = gyro["y"]
                gyro_z = gyro["z"]

                writeDataToCsv(temperature, temperature2, temperature3,     pressure, humidty, yaw, pitch, roll, mag_x, mag_y, mag_z, gyro_x, gyro_y,     gyro_z)

                counter = 0;
    except Exception as e:
        with open('log.csv', mode='a') as file:
            writer = csv.writer(file, delimiter=';', quotechar='"',     quoting=csv.QUOTE_MINIMAL)
            writer.writerow([datetime.datetime.now(),str(e)])
            sense.set_pixel(1, 0, red)
    finally:
        pass
        main()

if __name__ == '__main__':
    main()


texts: Kadane's Algorithm for 2D array with known boundaries

texts:
I asked this question first on StackOverflow but I didn't get an answer and was advised to try here too. So here we go.

I have implemented Kadane's algorithm for a 2D array in Python 2 with known boundaries, but I'm using the implementation for an online contest and the time it takes is more than the time given.

So that made me think if there is maybe another algorithm similar to Kadane's that has a smaller complexity, or if my code can be optimized in a way. My implementation works for any array with dimensions N x M and a subarray with dimensions maxRows x maxCols.

maxSumSubarray.py

import numpy as np

# returns the maximum sum for the given vector using kadane's algorithm, with
# maxRows maximum members in the sum
def kadane1DwithBounds(maxRows):
    global temp
    m = s = sum(temp[i] for i in xrange(maxRows))
    k = 0

    for i in xrange(1, N - maxRows + 1):
        s -= temp[k]
        s += temp[maxRows + i - 1]
        k += 1
        m = max(m, s)

    return m

# prints the maximum "area" given by the values of an NxM array inside a
# subarray with dimensions maxRows x maxCols. temp holds the latest vector to be
# given to kadane1DwithBounds()
def kadane2DwithBounds(maxRows, maxCols):
    global temp
    for i in xrange(N):
        temp[i] = sum(table[i][j] for j in xrange(maxCols))

    m = kadane1DwithBounds(maxRows)

    k = 0
    for j in xrange(1, M - maxCols + 1):
        for i in xrange(N):
            temp[i] -= table[i][k]
            temp[i] += table[i][maxCols + j - 1]
        k += 1
        m = max(m, kadane1DwithBounds(maxRows))

    print m

line = map(int, raw_input().split())
N = line[0]
M = line[1]
maxRows = line[2]
maxCols = line[3]

table = []
temp = np.empty(N, dtype = int)

for _ in xrange(N):
    table.append(map(int, raw_input().split()))

kadane2DwithBounds(maxRows, maxCols)

test.txt

4 8 2 3
1 1 2 3 3 1 1 1
2 2 2 2 2 2 2 2
3 3 3 1 1 3 3 4
0 0 1 1 3 2 2 1

Run with

python maxSumSubarray.py < test.txt

it gives

16

which is correct and is the following rectangle:

2 2 2
3 3 4

I've tried with other dimensions too and I'm pretty sure it works fine. Only problem is time/complexity.


texts: TextField Validation for Teleport Feature in Game

texts:
I've implemented a teleport feature for my game and I would like some feedback on the way that I validate the user input. I am using the libGDX library.

When the player clicks the Teleport Menu button, a menu will pop up that has two TextFields pre-populated with zeros.  The user can click the TextField to begin input, and then can input any string that they want to.  Once the player clicks Teleport, the current Strings of the TextFields are retrieved and handed off to a method that turns them into valid integers.

Here is a screenshot of the Teleport Menu:

Here is the TeleportMenu class, it is not too large:

public class TeleportMenu extends BZMenuTable {

    private final NinePatch menuBackground;
    private final MainGame game;
    private final float stageWidth;
    private final float stageHeight;

    private TextField longitudeTextField;
    private TextField latitudeTextField;

    public TeleportMenu(Skin skin, Stage hudStage, NinePatch menuBackground, MainGame game, float stageWidth, float stageHeight) {
        super(skin, hudStage);
        this.menuBackground = menuBackground;
        this.game = game;
        this.stageWidth = stageWidth;
        this.stageHeight = stageHeight;
    }

    @Override
    public void build() {

        TextButton teleportButton = new TextButton("Teleport", skin);
        teleportButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                TeleportMenu.this.activateTeleport();
                TeleportMenu.this.close();
            }
        });

        this.menuTable.setBackground(new NinePatchDrawable(this.menuBackground));
        this.menuTable.setPosition(this.stageWidth/10, this.stageHeight/8);
        this.menuTable.setWidth((float)(this.stageWidth * 0.8));
        this.menuTable.setHeight((float)(this.stageHeight * 0.6));

        this.menuTable.add("Teleport");
        this.menuTable.row();

        this.menuTable.add("Latitude 0 - 50");
        this.menuTable.row();
        this.latitudeTextField = new TextField("0", skin);
        this.menuTable.add(latitudeTextField);
        this.menuTable.row();

        this.menuTable.add("Longitude 0 - 50");
        this.menuTable.row();
        this.longitudeTextField = new TextField("0", skin);
        this.menuTable.add(longitudeTextField);
        this.menuTable.row();

        this.menuTable.add(teleportButton).pad(10).width(this.stageWidth/5).height(this.stageHeight/12).fill();
    }

    private void activateTeleport() {
        int xPos = this.processTextField(this.latitudeTextField.getText());
        int yPos = this.processTextField(this.longitudeTextField.getText());
        this.game.playerActivatedTeleport(xPos, yPos);
    }

    private int processTextField(String string) {
        Integer position;
        try {
            position = Integer.parseInt(string);
        } catch (Exception e) {
            System.out.println("Invalid input");
            position = 0;
        }
        if (position < 0) {
            position = 0;
        }
        if (position >= World.WORLD_WIDTH) {
            position = World.WORLD_WIDTH - 1; //because it is the index of an array
        }
        return position;
    }
}

Specifically I am curious about the processTextField method, but I am always interested in any kind of feedback.


texts:
public sealed class LinkXPathRepository : ILinkXPathRepository
{
    private static readonly ILog _log = LogManager.GetLogger(typeof(LinkXPathRepository));

    internal ILink Parse(Uri endpoint)
    {
        if (endpoint == null)
        {
            throw new ArgumentNullException("endpoint");
        }
        string leftPart = endpoint.GetLeftPart(UriPartial.Authority);

        EntityDataModelContext dc = DataContext.GetDataContext();

        IList<LinkXPath> sources = null;
        HtmlDocument document = null;

        Task t1 = Task.Factory.StartNew(() => sources = dc.LinkXPaths.Where(p => leftPart.Contains(p.Host)).OrderByDescending(p => p.Priority).ToList());
        Task t2 = Task.Factory.StartNew(() => document = Utility.DownloadHtml(endpoint));
        Task.WaitAll(new[] { t1, t2 });

        if (document == null)
        {
            return null;
        }

        Link result = new Link();
        foreach (LinkXPath source in sources)
        {
            if (result.Title.NullOrEmpty())
            {
                string title = GetFragment(document, source.Title);
                result.Title = title;
            }
            if (result.Description.NullOrEmpty())
            {
                string description = GetFragment(document, source.Description);
                result.Description = description;
            }
            if (result.Article.NullOrEmpty())
            {
                string article = GetFragment(document, source.Article);
                result.Article = article;
            }
        }

        return result;
    }

    internal string GetFragment(HtmlDocument document, string xpath)
    {
        return document.DocumentNode.GetChildNodeHtml(xpath);
    }
}

I'm particularly interested in refactoring this fragment:

            if (result.Title.NullOrEmpty())
            {
                string title = GetFragment(document, source.Title);
                result.Title = title;
            }
            if (result.Description.NullOrEmpty())
            {
                string description = GetFragment(document, source.Description);
                result.Description = description;
            }
            if (result.Article.NullOrEmpty())
            {
                string article = GetFragment(document, source.Article);
                result.Article = article;
            }

EDIT: please note that result.X and source.X come from different classes, even though their names are the same.


texts:
With some background and experience in PHP & Python, I'm trying to learn Swift by myself (web, videos, Ray Wenderlich books). I've read that a good first project for beginners is to try and write a basic calculator, so I've tried that. I'm wondering if there's a way to make my code leaner and more elegant (I've spent quite some time just getting the operator & equals keys to behave as expected). There's still no support for handling division by zero or display overflowing, the "C" and "AC" methods should be merged, but for now it does what it's supposed to do.

All digit keys are connected to buttonDigit, all operators to operation and the rest is obvious (I hope). Pardon the indentation right after the class declaration.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var display: UILabel!
var isTyping : Bool = false
var currentResult : Double = 0
var currentOperation : String? = nil
var nextOperation : String? = nil
var operand : Double = 0

// Handle digits

@IBAction func buttonDigit(sender: UIButton) {

    let digit = sender.currentTitle!
    if isTyping {
        display.text = display.text! + digit
    } else {
        display.text = digit
        isTyping = true
    }

}

// Handle operations keys

@IBAction func operation(sender: UIButton) {

    operand = displayValue
    nextOperation = sender.currentTitle

    if isTyping {
        equals()
    }

    currentOperation = nextOperation
    currentResult = displayValue
    isTyping = false
}

// Handle "equals" key

@IBAction func equals() {

    if (isTyping) {
        operand = displayValue
    }

    if (currentOperation != nil) {
        switch currentOperation! {
        case "+": display.text = "\(currentResult + operand)"
        case "-": display.text = "\(currentResult - operand)"
        case "×": display.text = "\(currentResult * operand)"
        case "÷": display.text = "\(currentResult / operand)"
        default: break
        }
    }

    currentResult = displayValue
    isTyping = false
}

// Handle AC key

@IBAction func allClear() {
    currentResult = 0
    display.text = "0"
    nextOperation = nil
    currentOperation = nil
    isTyping = false
}

// Handle C key

@IBAction func clear() {
    display.text = "0"
    isTyping = false
}

// Computed double from display label string

var displayValue : Double {
    get {
        return (display.text as NSString!).doubleValue
    }
    set {
    }
}
}


texts: JSLint says "unexpected function" doCalc

texts:
See the full calculator with HTML -> https://gist.github.com/1861120
You should be able to drag that html file from github into a browser and start using it. I'm only putting the js below. The calculator works fine but JS Lint is telling me I have an unexpected 'function' doCalc line 9 character 1.

Also just looking for some general tips on best practices and how this might be refactored. Any help is appreciated. Thank you.

var type, n, r, formula;
Math.factorial = function (n) {
    if (n < 2) {
        return 1;
    }
    return (n * Math.factorial(n - 1));
}

function doCalc(type) {
    switch (type) {
        case 'permutation':
            n = document.permutation.T1.value;
            r = document.permutation.T2.value;
            formula = function() {
                document.permutation.T3.value = Math.factorial(n) / Math.factorial(n - r);
            }
            break;
        case 'combination':
            n = document.combination.T1.value;
            r = document.combination.T2.value;
            formula = function() {
                document.combination.T3.value = Math.factorial(n) / (Math.factorial(r) * Math.factorial(n - r));
            }
            break;
    }
    n = Number(n);
    r = Number(r);
    if (isNaN(n) || isNaN(r)) {
        alert("Factorial requires a numberic argument.");
        return null;
    }
    formula();
}

window.onload = function() {
    document.getElementById('calculate-p').onclick = function() {
        doCalc('permutation');
    }
    document.getElementById('calculate-c').onclick = function() {
        doCalc('combination');
    }
}


texts: Singly linked list abstraction in ES5 JavaScript

texts:
Below is the code for, Singly linked list implementation,

function List(){
    this.start=null;
    this.end=null;
}

List.makeNode=function(){
    return {data:null,next:null};
};

List.prototype.add=function (data){
    if(this.start===null){
        this.start=List.makeNode();
        this.end=this.start;
    }else{
        this.end.next=List.makeNode();
        this.end=this.end.next;
    }
    this.end.data=data;
};

List.prototype.traverse = function(){
    var current = this.start;
    while (current !== null) {
        current = current.next;
    }
};

List.prototype.insertAsFirst = function(d) {
    var temp = List.makeNode();
    temp.next = this.start;
    this.start = temp;
    temp.data = d;
};
List.prototype.delete = function(data) {
    var current = this.start;
    var previous = this.start;
    while (current !== null) {
        if (data === current.data) {
            if (current === this.start) {
                this.start = current.next;
                return;
            }
            if (current == this.end) this.end = previous;
            previous.next = current. next;
            return;
        }
        previous = current;
        current = current.next;
    }
};
List.prototype.insertAfter = function(t, d) {
    var current = this.start;
    while (current !== null) {
        if (current.data === t) {
            var temp = List.makeNode();
            temp.data = d;
            temp.next = current.next;
            if (current == this.end) this.end = temp;
                current.next = temp;
                return;
            }
            current = current.next;
        }
};
List.prototype.item=function(i){
    var current = this.start;
    while (current !== null) {
        i--;
        if(i===0) return current;
        current = current.next;
    }
    return null;
};
List.prototype.each = function(f) {
    var current = this.start;
    while (current !== null) {
        f(current);
        current = current.next;
    }
};

From the above code,

1) Is List a proper abstraction?

2) Does List ensure encapsulation?

3) Is the usage of List.prototype justified?

4) Does makeNode justified as static function?


texts:
I have an asp.net/MVC5 app that for reasons that are outside of my control needs to hang onto (some) user credentials (username and password) to facilitate certain operations they may perform. I don't like it - but with that as a given, I would like some QC on the approach I'm thinking of taking to keep their credentials relatively secure.

When the application initializes - create a AES 256 key using RNGCryptoServiceProvider and partial IV - this is retained in a static class.

private const int AesBlockSize = 128;                  // block size in bits
private const int AesKeySize = 256;                    // key size in bits

// ...

var rngCrypto = new RNGCryptoServiceProvider();
_encryptionKey = new byte[AesKeySize/8];
rngCrypto.GetBytes(_encryptionKey);                    // generate key
_encryptionIV = new byte[AesBlockSize/8];
rngCrypto.GetBytes(_encryptionIV);                     // generate partial IV

When a user authenticates, if their username and password passes validation, serialize them into a JSON string and encrypt it with the AES 256 key using as the IV the partial IV combined with their username (lowercase).

Create a custom FormsAuthenticationTicket and store the encrypted value as user data inside the ticket.

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
            (
                ticketVersion,
                username,
                ticketIssueDateTime,
                ticketExpireDateTime,
                ticketPersist,
                encryptedCredentials
            );

            // Encrypt the ticket
            string encTicket = FormsAuthentication.Encrypt(ticket);

            // Create the cookie
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) {HttpOnly = true};
            HttpContext.Current.Response.SetCookie(cookie);

My understanding is that the forms authentication cookie is encrypted with machine key and then inside the user credentials are encrypted with a temporary AES 256 key that will live the lifecycle of the application.

When I need their credentials, I retrieve it from the cookie, decrypt, deserialize and use them

There is a small possibility of the app pool recycling under them invalidating their stored credentials since in the in-memory key will change - in that case I just catch the failure to decrypt, log them out and send them to log in again. (App pool recycles are scheduled so this won't be an issue at any rate.)

Thoughts? Improvements? Condemnations?


texts: Transforming UCI-move into bitboard, chess

texts:
I want to transform a UCI-move into bitboard.
for example a2a3 -> 32768, 8388608
I need to assign [7,6,...,0] to [a,b,...,h] so that for each letter i have the assigned number(n) to calculate 2^n
Which I can then left shift by the value in uci[1] or uci[3] *8 depending on start- or endfield.
This is my approach and it doesn't look very nice and redundant.
def ucitoBit(uci):
    if uci[0] == 'a':
        mask1 = 2 ** 7
    if uci[0] == 'b':
        mask1 = 2 ** 6
    if uci[0] == 'c':
        mask1 = 2 ** 5
    if uci[0] == 'd':
        mask1 = 2 ** 4
    if uci[0] == 'e':
        mask1 = 2 ** 3
    if uci[0] == 'f':
        mask1 = 2 ** 2
    if uci[0] == 'g':
        mask1 = 2 ** 1
    if uci[0] == 'h':
        mask1 = 2 ** 0
    mask1 = mask1 << 8 * (int(uci[1]) - 1)

    if uci[2] == 'a':
        mask2 = 2 ** 7
    if uci[2] == 'b':
        mask2 = 2 ** 6
    if uci[2] == 'c':
        mask2 = 2 ** 5
    if uci[2] == 'd':
        mask2 = 2 ** 4
    if uci[2] == 'e':
        mask2 = 2 ** 3
    if uci[2] == 'f':
        mask2 = 2 ** 2
    if uci[2] == 'g':
        mask2 = 2 ** 1
    if uci[2] == 'h':
        mask2 = 2 ** 0
    mask2 = mask2 << 8 * (int(uci[3]) - 1)
    bitstring = [np.uint64(mask1), np.uint64(mask2)]
    return bitstring


texts:
Below is some code that I've been working to simplify, however I feel there is more that can be done. Please note that I did clean up the articles.search method.

class HomeController < ApplicationController
    @@articles_per_page = 6
     def index
        @paged_articles = articles.search(:user_id=> @@user_id, :page=>'1', :per_page=>@@articles_per_page)
        @tags = get_tags
        @next_page_url = url_for(:controller =>:home, :action => :page, :page_id=>  2)
        @page_title = "Recent articles"
     end

    def tags
      @paged_articles = articles.search(:page=>'1',:tags=>params[:tag_name], :per_page=>@@articles_per_page)
       @tags = get_tags
       @next_page_url = url_for(:controller =>:home, :action => :page, :tag_name => params[:tag_name], :page_id=>  2)
       @page_title = "Search articles by tags"
       render :index
     end

    def about
       @page_title = "About"
    end

   private
    def get_tags
         articles.getTags 'param1', 'param2'
    end
   end

I simplified it this way

class HomeController < ApplicationController
  @@articles_per_page = 6
  @@first_page_articles_options = {:page=>'1', :per_page=>@@articles_per_page}
  @@second_page_url_options = {:controller =>:home, :action => :page, :page_id=>  2}

  def index
    @paged_articles = articles.search(@@first_page_articles_options)
    @tags = get_tags
    @next_page_url = url_for(@@second_page_url_options)
    @page_title = "Recent articles"
  end

  def tags
    @@first_page_articles_options[:tags]  = params[:tag_name]
    @paged_articles = articles.search(@@first_page_articles_options)
    @tags = get_tags

    @@second_page_url_options[:tag_name]  = params[:tag_name]
    @next_page_url = url_for(@@second_page_url_options)
    @page_title = "Search articles by tags"
    render :index
  end
   def about
      @page_title = "About"
  end

  private
  def get_tags
         articles.getTags 'param1', 'param2'
  end
end

So what do you think? Is there any way to make it more better and cleaner?


texts:
Background: I'm designing a system (VB/WinForms) that uses a database(MS SQL Server 2008 R2) to track people, their stock account #'s, which stocks they are investing in, and the payout of those stocks.

Basically, just reading/writing to the database and some time-elapsed functionality. (One payout per year, etc.) I have forms where users are entering employees to the database, adding accounts, etc.

My issue: I never truly understood OOP, however I am getting more involved with it now, and while my program works, I want the code to be better (look better, be more flexible, utilize classes/objects more, etc.)

That being said, how can I make this code more Objected-Oriented?

Note: I am also utilizing ReSharper, however that can only do so much and I don't want to have to rely on a tool for the rest of my career.

Note: This project utilizes an encryption class.

Imports System.Data.SqlClient
Public Class EmployeeUpdateFrm
    Private _id As String
    Dim _seqId As Integer

Private Sub Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim conn1 As New SqlConnection("Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True")

    Dim qry As String = "SELECT CMPNY_SEQ_ID, CMPNY_NM FROM CMPNY"

    Dim ds1 As New DataSet()
    Using da As New SqlDataAdapter(qry, conn1)
        'fill data set 1 for combobox
        da.Fill(ds1)
    End Using

    With CompanyCbx
        'what the user sees
        .DisplayMember = "CMPNY_NM"
        'value behind each display member
        .ValueMember = "CMPNY_SEQ_ID"
        .DataSource = ds1.Tables(0)
        .SelectedIndex = 0
    End With
    'close connection
    conn1.Close()
    Dim index As Integer = 1
    'The vertical spacing between rows of controls relative to the textboxes.
    Dim yMargin As Integer = 10
    Dim query As String
    'Create a new instance of the encryption class.
    Dim strKey As String = "Key1"
    Dim Crypto As ClsCrypt
    Crypto = New ClsCrypt(strKey)

    Dim eID As String = Crypto.EncryptData(_id)

    query = "SELECT EMPL_SEQ_ID, EMPL_ID, EMPL_LAST_NM, EMPL_FIRST_NM, EMPL_PREFRD_NM, EMPL_BIRTH_DT, EMPL_MAIL_STN_CD,"
    query &= "                 EMPL_ADDR1_TXT, EMPL_ADDR2_TXT, EMPL_CITY_NM, EMPL_STATE_CD, EMPL_POSTL_CD, EMPL_PYRL_CD, "
    query &= "                          EMPL_FILE_NO, EMPL_SPRTN_DT, CMPNY_SEQ_ID, EMPL_ACTV_IND, BEG_DT, END_DT "
    query &= "  FROM EMPL"
    query &= "  WHERE EMPL_ID = @ID; "

    'New DataSet object to hold employee records.
    Using ds As New DataSet()
        Using conn As New SqlConnection("Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True")
            Using da As New SqlDataAdapter()
                da.SelectCommand = New SqlCommand(query, conn)
                da.SelectCommand.Parameters.Add(New SqlParameter("@ID", eID))
                da.Fill(ds)
            End Using
        End Using

        If CompanyCbx.Items.Count > 0 Then
            CompanyCbx.SelectedIndex = ds.Tables(0).Rows(0).Item(15).ToString
        End If

        Try
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                For z As Integer = 0 To ds.Tables(0).Columns.Count - 1
                    If z <> 0 Then
                        'Decrypt all rows and columns
                        ds.Tables(0).Rows(i)(z) = Crypto.DecryptData(ds.Tables(0).Rows(i)(z))
                    End If
                Next
            Next
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

I also ask (without being opinionated), with programs like this (fairly small, read/write to database with no extraordinary functionality) how flexible is the coding? By that I mean, I don't really see how I could use something like:

Dim Person as New Person()

Class Person
Public firstName as String
Public lastName as String

etc.

Especially because I utilize DataSets so heavily.


texts: Generator expression in combination with StopIteration: kind of a hack?

texts:
The first piece of code should cover the standard expected data. But as you can easily see, the data not always conveys to this standard. The code works great but I wonder if this is thought be a miss-use of the try/except clause. Better to go with if/else?

try:
    short_name = short_name.upper()
    m = (k for k,v in c.countries_dict.iteritems() if v[0] == short_name).next()
    m = [m]
except StopIteration:
    if re_type == 'MAP_INFO' or re_type == 'SHAPE' or re_type == 'ARC_INFO':
        reg_dict = REGIONS
        short_name = short_name.lower()
    elif re_type == 'NAV_SHAPE':
        reg_dict = NAV_REGIONS
        short_name = short_name.upper()
    m = []
    for k,v in reg_dict.iteritems():
        if k == short_name:
            for tup in v:
                m.append(tup[1])


texts: Picking a time based on when the app was last used

texts:
I am trying to set up a time variable as a local storage property to be retrieved when I open my app in my browser.

If I open it for the first time, today, I'll set it up to today at midnight.

Otherwise, if the time property has already been set up today in a previous session, I'll provide the retrieved value to the session, and assign Date.now to the local storage property for next time I'll visit my app.

I am trying to use ternary operators in place of if statements, but I see duplicated code I am not able to avoid. I am sure I am missing a trivial logic error, but I am not seeing it right now.

const NotificationsStorage: { lastCheck: number } = JSON.parse(localStorage.getItem('NotificationsStorage'));
const today: number = moment().startOf('day').valueOf();
const now: number = moment().valueOf();

localStorage
    ? NotificationsStorage
        ? (NotificationsStorage.lastCheck && NotificationsStorage.lastCheck > today)
            ? (
                this.lastCheck = NotificationsStorage.lastCheck,
                localStorage.setItem('NotificationsStorage', JSON.stringify({ lastCheck: now }))
            )
            : (
                localStorage.setItem('NotificationsStorage', JSON.stringify({ lastCheck: today })),
                this.lastCheck = today
            )
        : (
            localStorage.setItem('NotificationsStorage', JSON.stringify({ lastCheck: today })),
            this.lastCheck = today
        )
    : console.warn('Current browser doesn\'t support Local Storage API');


texts:
Question copied from the book:

  (Game: eye-hand coordination) Write a program that displays a circle
  of radius 10 pixels filled with a random color at a random location on
  a panel, as shown in Figure 16.28c. When you click the circle, it
  disappears and a new randomcolor circle is displayed at another random
  location. After twenty circles are clicked, display the time spent in
  the panel, as shown in Figure 16.28d.

My solution:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class EyeHandCoordination extends JFrame {
    private final int CIRCLE_RADIUS = 10;
    private final int TOTAL_CIRCLES = 20;
    private RandomCirclePanel panel = new RandomCirclePanel();

    public EyeHandCoordination() {
        add(panel);
    }

    public static void main(String[] args) {
        EyeHandCoordination frame = new EyeHandCoordination();
        frame.setTitle("EyeHandCoordination");
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null); // Center the frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
      }

    private class RandomCirclePanel extends JPanel {
        private long startTime;
        private long endTime;

        private int circleX = 0;
        private int circleY = 0;

        private int currentCircle = 0;

        public RandomCirclePanel() {
            startTime = System.currentTimeMillis();

            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    // Check if in circle
                    if (inCircle(e.getX(), e.getY()) && currentCircle < TOTAL_CIRCLES) {
                        currentCircle++;
                        repaint();
                    }
                }
            });
        }

        /** Display circle at a random location **/
        private void changeCircleLocation() {
            circleX = (int)(Math.random() * (getWidth() - CIRCLE_RADIUS * 2));
            circleY = (int)(Math.random() * (getHeight() - CIRCLE_RADIUS * 2));
        }

        /** Check if inCircle **/
        public boolean inCircle(int mouseX, int mouseY) {
            if (distanceFromCenterOfCircle(mouseX, mouseY) <= CIRCLE_RADIUS) {
                return true;
            }

            return false;
        }

        private int distanceFromCenterOfCircle(int x, int y) {
            int centerX = circleX + CIRCLE_RADIUS;
            int centerY = circleY + CIRCLE_RADIUS;

            return (int)(Math.sqrt((centerX - x) * (centerX - x) + (centerY - y) * (centerY - y)));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            int width = getWidth();
            int height = getHeight();

            changeCircleLocation();

            if (currentCircle >= TOTAL_CIRCLES) {
                g.setColor(Color.BLACK);
                endTime = System.currentTimeMillis();
                FontMetrics fm = g.getFontMetrics();
                String s = "Time spent: " + ((endTime - startTime) / 1000.0) + " seconds";
                g.drawString(s, width / 2 - fm.stringWidth(s) / 2, height / 2 - fm.getAscent());
            }
            else {
                g.setColor(new Color((int)(Math.random() * 256), (int)(Math.random() * 256), (int)(Math.random() * 256)));
                g.fillOval(circleX, circleY, CIRCLE_RADIUS * 2, CIRCLE_RADIUS * 2);
            }
        }
    }
}


texts: PyQt frame which changes color with child focus

texts:
I am working on an application that has various "panels" contained within splitters. I wanted the panel border to change color when one of it's children gained focus. Here is a simple example of the solution I came up with. I think it is pretty clean and quite scalable, but I wanted to see if there is anything I might be able to improve about it, or if there was a better convention for this. I'm still quite new to class instantiation and there's always a ton more to learn about Qt! In particular I want to make sure I'm using super correctly, and my implementation of event filters is efficient.

import os
import sys
from PyQt4 import QtGui, QtCore

class BasePanel(QtGui.QWidget):
    """This is more or less abstract, subclass it for 'panels' in the main UI"""
    def __init__(self, parent=None):
        super(BasePanel, self).__init__(parent)
        self.frame_layout = QtGui.QVBoxLayout()
        self.frame_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.frame_layout)

        self.frame = QtGui.QFrame()
        self.frame.setObjectName("base_frame")
        self.frame.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)
        self.frame.setLineWidth(1)
        self.frame_layout.addWidget(self.frame)

        self.base_layout = QtGui.QVBoxLayout()
        self.frame.setLayout(self.base_layout)

        self.focus_in_color = "rgb(50, 255, 150)"
        self.focus_out_color = "rgb(100, 100, 100)"
        self.frame.setStyleSheet("#base_frame {border: 1px solid %s}" % self.focus_out_color)
        self.installEventFilter(self) # this will catch focus events'

    def eventFilter(self, object, event):
        if event.type() == QtCore.QEvent.FocusIn:
            self.frame.setStyleSheet("#base_frame {border: 1px solid %s}" % self.focus_in_color)
        elif event.type() == QtCore.QEvent.FocusOut:
            self.frame.setStyleSheet("#base_frame {border: 1px solid %s}" % self.focus_out_color)
        return False # passes this event to the child, i.e. does not block it from the child widgets

    def showEvent(self, event):
        super(BasePanel, self).showEvent(event)
        # this will isntal the focus in/out event filter in all children of the panel
        for widget in self.findChildren(QtGui.QWidget):
            widget.installEventFilter(self)

class LeftPanel(BasePanel):
    def __init__(self, parent=None):
        super(LeftPanel, self).__init__(parent)

        title = QtGui.QLabel("Left Panel")
        title.setAlignment(QtCore.Qt.AlignCenter)
        self.base_layout.addWidget(title)

        edit = QtGui.QLineEdit()
        self.base_layout.addWidget(edit)

class RightPanel(BasePanel):
    def __init__(self, parent=None):
        super(RightPanel, self).__init__(parent)

        title = QtGui.QLabel("Right Panel")
        title.setAlignment(QtCore.Qt.AlignCenter)
        self.base_layout.addWidget(title)

        edit = QtGui.QLineEdit()
        self.base_layout.addWidget(edit)

class MainApp(QtGui.QMainWindow):
    def __init__(self):
        super(MainApp, self).__init__()

        main_layout = QtGui.QHBoxLayout()
        central_widget = QtGui.QWidget()
        central_widget.setLayout(main_layout)
        self.setCentralWidget(central_widget)

        left_panel = LeftPanel()
        main_layout.addWidget(left_panel)

        right_panel = RightPanel()
        main_layout.addWidget(right_panel)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ex = MainApp()
    ex.show()

    sys.exit(app.exec_())


texts:
I have a dictionary structured as {a_1: [((b_11,c_11),d_11), ((b_12, c_12), d_12), ...], a_2: [...], ...}.

I want to extract the maximum abs(c) among all the possible c values. Currently I'm doing this throught two for loops. One for each a, and other for each of set {b,c,d}.

elements = {
            0: [((0, -4), 1)],
            1: [((1, -5), 1), ((0, -4), 1)],
            2: [((2, -3), 1)],
            3: [((3, -2), 1), ((0, -5), 1)],
            }

max_c = 0

for a in list(elements):
    for (b, c), d in elements[a]:
        max_c = max(max_c, abs(c))

Is there any way to do this without the for loops? and if it is, is it pythonic? or I should keep this way because it's more understandable?

Thanks in advance.


texts:
As a part of a console utilities module, I created a function that takes a table in the form of an array of arrays, and generates an ASCII table with the given contents.

I've also added the options of adding a header, determining the in-cell alignment, and adding a border to the table.

Table cells have auto computed lengths by the longest cell of their column, rows that have a small amount of elements get filled by blank cells to adjust their length.

I'm quite new to Python, so I wanted to know about whether my writing style is OK. Can I improve or shorten some parts of the code? Any other advice?

def ascii_table (table, **k):
    header = k.get('header', [])
    align = k.get('align', 'left')
    border = k.get('border', False)

    widths = []
    for i in range(max(map(len, table))): widths.append(max(max(map(len, [row[i] for row in table if len(row) > i])), len(header[i]) if len(header) > i else 0))

    printable = []

    if border:
        printrow = []
        for i in range(max(map(len, table))):
            if i > 0 and i < max(map(len, table)) - 1: printrow.append('─' * (widths[i] + 2))
            else: printrow.append('─' * (widths[i] + 1))
        printable.append('┌─' + '┬'.join(printrow) + '─┐')

    # header formatting
    if len(header) > 0:
        printrow = []
        for i in range(len(header)):
            assert header[i]
            if align == 'center': printrow.append(header[i].center(widths[i]))
            elif align == 'left': printrow.append(header[i].ljust(widths[i]))
            elif align == 'right': printrow.append(header[i].rjust(widths[i]))

        if border: printable.append('│ ' + ' │ '.join(printrow) + ' │')
        else: printable.append(' │ '.join(printrow))

        printrow = []
        for i in range(len(header)):
            if i > 0 and i < len(header) - 1: printrow.append('─' * (widths[i] + 2))
            else: printrow.append('─' * (widths[i] + 1))

        if border: printable.append('├─' + '┼'.join(printrow) + '─┤')
        else: printable.append('┼'.join(printrow))

    # table formatting
    for row in table:
        printrow = []
        for i in range(len(widths) - len(row)):
            row.append('')
        for i in range(len(row)):
            if align == 'center': printrow.append(row[i].center(widths[i]))
            elif align == 'left': printrow.append(row[i].ljust(widths[i]))
            elif align == 'right': printrow.append(row[i].rjust(widths[i]))

        if border: printable.append('│ ' + ' │ '.join(printrow) + ' │')
        else: printable.append(' │ '.join(printrow))

    if border:
        printrow = []
        for i in range(max(map(len, table))):
            if i > 0 and i < max(map(len, table)) - 1: printrow.append('─' * (widths[i] + 2))
            else: printrow.append('─' * (widths[i] + 1))
        printable.append('└─' + '┴'.join(printrow) + '─┘')

    return '\n'.join(printable)

Demo:

>>> from asciiart import ascii_table
>>> table = list(map(lambda x: x.split(), ['Jon Doe 20', 'Mark Waine 35', 'Donald Rory 43']))
>>> header = ['First Name', 'Last Name', 'Age']
>>> ascii = ascii_table(table, header=header, align='center', border=True)
>>> print(ascii)
┌────────────┬───────────┬─────┐
│ First Name │ Last Name │ Age │
├────────────┼───────────┼─────┤
│    Jon     │    Doe    │  20 │
│    Mark    │   Waine   │  35 │
│   Donald   │    Rory   │  43 │
└────────────┴───────────┴─────┘


texts: What is the better way to retrieve value from this cache implementaion?

texts:
I have the following methods in CacheUtil class

public void addCacheEntry(String key, Serializable entry) {
    //add to cache
}

public void removeCacheEntry(String key) {
   //remove from cache
}

public Serializable getCacheEntry(String key) {
   Serializable entry = // get from cache
   return entry;
}

And in the class where I use the cache, I have the following methods,

public List<String> fetchList() {
   List<String> aList = (List<String>) CacheUtil.getInstance().getCacheEntry("aList"); //IDE warns of unchecked casting
   if(aList == null) {
     aList = fetchFromDB():
     CacheUtil.getInstance().addCacheEntry("aList", new ArrayList<String>(aList));
   }
}

How could I have avoided the warning of unchecked cast? I can not change the methods in cache to store lists explicitly, as I want to store anything that is serializable in cache and that is just a library.

I believe there is a better way to do it.


texts: What is an optimal way of not repeating myself in the following code?

texts:
Following code works and i am simply looking for ways to not repeat myself as well keep to code clean and readable. Would love to see what methods that can be utilized to make it prettier.

const util = require("util");
const fs = require("fs");
const reader = util.promisify(fs.readFile);
const simpleParser = require('mailparser').simpleParser;

async function readFile(filepath) {
    try {
        return await reader(filepath)
    } catch (err) {
        return err
    }
};

async function getAttachment(filepath) {
    let file, email;
    try {
        file = await readFile(filepath);
    } catch (err) {
        return err
    }

    try {
        email = await simpleParser(file)
        return email.attachments[0].content.toString()
    } catch (err) {
        return err
    }
}

async function getFileName(filepath) {
    let file, email;
    try {
        file = await readFile(filepath);
    } catch (err) {
        return err
    }

    try {
        email = await simpleParser(file)
        return email.attachments[0].filename.toString()
    } catch (err) {
        return err
    }
}

async function main() {
    let attachment = await getAttachment('./mock-data/google-report.email')
    let filename = await getFileName('./mock-data/google-report.email')
    console.log(filename)
}

main()

module.exports = {
    getAttachment
}


texts: Find articulation points/ cut vertices in graph

texts:
I would like to get some feedback on my completed code that finds and displays the articulation vertices in an undirected graph.
I included a test case within the code, it should (and does) print c as the only articulation vertex.
Also I would like to clarify my understanding on some things,

This runs in \$\mathcal{O}(V+E)\$ time

In the final line of code I do,  low_vis[vertex] = min(low_vis[neighbour], discovered[vertex])
Does it make a difference if I use the fixed discovered position as shown above, or the lowest reachable visited vertex position (low_vis), my own tests showed no difference and the same answer was returned (c).

Thank you
class vertex:

  def __init__(self, key):

    self.neighbours = {}
    self.key = key

  def add(self, key, edge):
    self.neighbours[key] = edge

class graph:

  def __init__(self):

    self.root = {}
    self.nbnodes = 0
    self.curr = 0

  def add(self, key1, key2, edge=0):
    if key1 not in self.root:
      self.root[key1] = vertex(key1)
      self.nbnodes += 1
    if key2 not in self.root:
      self.root[key2] = vertex(key2)
      self.nbnodes += 1

    self.root[key1].add(key2, edge)
    self.root[key2].add(key1, edge)

  def cutver(self):

    visited = set()
    discovered = {}
    low_vis = {}
    parent = {}
    result = []

    for vertex in self.root:
        if vertex not in visited:
          parent[vertex] = -1
          self._cutver(vertex, parent, visited, discovered, low_vis, result)
    print(result)

  def _cutver(self, vertex, parent, visited, discovered, low_vis, result):

    visited.add(vertex)
    discovered[vertex] = self.curr
    low_vis[vertex] = self.curr
    children = 0
    self.curr += 1

    for neighbour in self.root[vertex].neighbours:

      if neighbour not in visited:
        parent[neighbour] = vertex
        children += 1
        self._cutver(neighbour, parent, visited, discovered, low_vis, result)

        low_vis[vertex] = min(low_vis[vertex], low_vis[neighbour])

        if children > 1 and parent[vertex] == -1:
          result.append(vertex)

        if parent[vertex] != -1 and low_vis[neighbour] >= discovered[vertex]:
          result.append(vertex)

      elif neighbour != parent[vertex]:
        low_vis[vertex] = min(low_vis[neighbour], discovered[vertex])

if __name__ == '__main__':
      a = graph()
      A = 'A'
      B = 'B'
      C = 'C'
      D = 'D'
      E = 'E'
      a.add(A,B)
      a.add(A,C)
      a.add(B,D)
      a.add(D,C)
      a.add(C,E)
      a.cutver()


texts: Early-termination foldLeft for Scala Streams

texts:
The foldRight and foldLeft methods for Scala Streams cannot terminate early, so here is my attempt to provide that functionality through the "enrich my library" pattern:

  implicit class StreamWithLazyFold[A](s: Stream[A]) {
    def foldLeft1[B](z: B)(f: (B, A) => (B, Boolean)): B = s match {
      case _ if s.isEmpty => z
      case h #:: t => {
        val (z1, stop) = f(z, h.asInstanceOf[A])
        if(stop) z1
        else t.asInstanceOf[Stream[A]].foldLeft1(z1)(f)
      }
    }
  }

Test:

  s.foldLeft1(true)((x, y) => {
    println("run!")
    val b = (y < 3) && x
    (b, !b)
  })

It prints "run!" only 3 times.

One question arises immediately: how do I generalize this to all Seqs?

All suggestions are welcome, of course.


texts: Factory pattern along with DI using Unity container

texts:
I am learning design patterns and this is my sample code where I have implemented Factory pattern and instance creation I have delegated to Unity container Framework(DI) to build the loosely coupled system.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;

namespace DesignPatternsDemo
{
    class Program
    {
        static void Main(string[] args)
        {

            iPaymentGateway gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.SHIFT4);
            gateway.CreatePaymentGateway();
            gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.WELLSFARGO);
            gateway.CreatePaymentGateway();
            gateway = PaymentGatwayFactory.NewPaymentGatway(GateWay.PROTOBASE);
            gateway.CreatePaymentGateway();
            Console.ReadLine();
        }

        enum GateWay
        {
            PROTOBASE = 1,
            SHIFT4 = 2,
            WELLSFARGO = 3
        }

         //Factory class
        class PaymentGatwayFactory
        {
            public static iPaymentGateway NewPaymentGatway(GateWay GateWayType)
            {
                 //Dependency injection using unity container
                var container = new UnityContainer();
                iPaymentGateway result = null;
                switch (GateWayType)
                {
                    case GateWay.SHIFT4:
                        container.RegisterType<iPaymentGateway, SHIFT4Gateway>();
                        result = container.Resolve<SHIFT4Gateway>();
                        break;
                    case GateWay.WELLSFARGO:
                        container.RegisterType<iPaymentGateway, WellsFargoGateway>();
                        result = container.Resolve<WellsFargoGateway>();
                        break;
                    default:
                        container.RegisterType<iPaymentGateway, ProtobaseGateway>();
                        result = container.Resolve<ProtobaseGateway>();
                        break;
                }

                return result;
            }
        }

        class WellsFargoGateway : iPaymentGateway
        {
            public void CreatePaymentGateway()
            {
                Console.WriteLine("Implement Wells Fargo logic");
            }
        }

        class SHIFT4Gateway : iPaymentGateway
        {
            public void CreatePaymentGateway()
            {
                Console.WriteLine("Implement SHIFT4 logic");
            }
        }

        class ProtobaseGateway : iPaymentGateway
        {
            public void CreatePaymentGateway()
            {
                Console.WriteLine("Implement Protobase logic");
            }
        }

        interface iPaymentGateway
        {
            void CreatePaymentGateway();
        }
    }
}

Is this is the right way of implementing Factory pattern and using the Unity framework?


texts: Process POSTed data and add default string if missing

texts:
My code takes the input submitted by $ _POST, via a checkbox array. I process the array and check the sent data if there is a particular string in it, which is set as my default. If I have a string, which is my default, I just go through implode and add ",", if my default string is missing in the data. I add and sort the array anew, with the first string being the default. I want to shorten the code because I can't make it shorter.
<?php
if(isset($_POST['submit'])) {
    //for update
    $site_id['locale'] = 'tr';

    //new
    $exampleArray = isset($_POST['lala']) ? $_POST['lala'] : '';

    $example = null;
    if(($key = array_search($site_id['locale'], $exampleArray, true)) !== false) {
        unset($exampleArray[$key]);

        $FirstString = array($site_id['locale']);
        $exampleArray = array_diff($exampleArray, $FirstString);
        usort($exampleArray);
        $exampleArray = array_merge($FirstString, $exampleArray);
        //print_r($exampleArray);
        $myArray = array();
        foreach ( $exampleArray as $key => $value ) {
            $myArray[] = $value;
        }
        echo implode( ', ', $myArray );
    } else {
        $FirstString = array($site_id['locale']);
        $exampleArray = array_diff($exampleArray, $FirstString);
        usort($exampleArray);
        $exampleArray = array_merge($FirstString, $exampleArray);
        //print_r($exampleArray);
        $myArray = array();
        foreach ( $exampleArray as $key => $value ) {
            $myArray[] = $value;
        }
        echo implode( ', ', $myArray );
    }

}
?>
<form method="POST" action="">
<input type="checkbox" name="lala[]" value="bg" />
<input type="checkbox" name="lala[]" value="us" />
<input type="checkbox" name="lala[]" value="gr" />
<input type="submit" name="submit" />
</form>


texts:
I've got this massive nested for loop with a few if and else statements in nodeJs. The output of all of this is just string which is combined from different values out of JSon object. What I want to do is rewrite it in more efficient way as JSlint plugin for sublime is complaining about complexity of it:

var instancesList = '';
    ec2.describeInstances(params,function(err, data) {
        if (err){
            console.log(err, err.stack);
        } else {
                for (var i in data.Reservations){
                    for (var j in data.Reservations[i].Instances[0].Tags){
                        if(data.Reservations[i].Instances[0].Tags[j].Key == 'Name'){
                            instancesList+= 'Name: ' + data.Reservations[i].Instances[0].Tags[j].Value +
                                           '  id: ' +data.Reservations[i].Instances[0].InstanceId +
                                           '  Status: ' + data.Reservations[i].Instances[0].State.Name +'\n';
                        }
                    }
                }
        }
console.log(instancesList);

Any help, ideas or a link on how to deal with these kind of situations would be greatly appreciated.


texts: Functional programming approach to repeated function application

texts:
Control like if..else and while

  If \$f\$ is a numerical function and \$n\$ is a positive integer, then we can form the \$n\$th repeated application of \$f\$, which is defined to be the function whose value at \$x\$ is \$f(f(...(f(x))...))\$. For example, if \$f\$ adds 1 to its argument, then the \$n\$th repeated application of \$f\$ adds \$n\$. Write a function that takes as inputs a function \$f\$ and a positive integer \$n\$ and returns the function that computes the \$n\$th repeated application of \$f\$:

def repeated(f, n):
    """Return the function that computes the nth application of f.

    f -- a function that takes one argument
    n -- a positive integer

    >>> repeated(square, 2)(5)
    625
    >>> repeated(square, 4)(5)
    152587890625
    """
    "*** YOUR CODE HERE ***"

The solution is implemented using functional paradigm style, as shown below:

from operator import mul
from operator import pow

def repeated(f, n):
    """Return the function that computes the nth application of f.

    f -- a function that takes one argument
    n -- a positve integer

    >>> repeated(square, 2)(5)
    625
    >>> repeated(cube, 2)(5)
    1953125
    """
    assert n > 0
    def apply_n_times(x):
        count = n
        next_acc = f(x)
        count = count - 1
        while count > 0:
            next_acc = f(next_acc)
            count = count - 1
        return next_acc
    return apply_n_times

def square(x):
    return mul(x, x)

def cube(x):
    return pow(x, 3)

print(repeated(square, 0)(2))

My questions:

If the code looks correct from a programming style perspective, can I further optimize this code written in function repeated?
Can the naming conventions and error handling be better?