texts:
This code calculates the distance between angles, particularly for n-tuples of angles. One example where this situation occurs is as follows:

I'm using a 2 arms, one 6 degree of freedom and the other 7 dof with revolute (rotating) joints. The position of the arm can be accurately represented as an n-d point representing the angle of each joint, with no need for orientation/pose on the surface of a torus, with 1 dimension for each joint.

Here is a simple image explaining the 2D case.

Therefore I don't need to worry about orientation but probably just the envelope/box which I believe is used for the data structure and the points themselves.

Here is an implementation, which should be easy to template for more general situations:

typedef boost::array<double,6> ArmPos;

template<typename T>
inline T normalizeRadiansPiToMinusPi(T rad)
{
  // copy the sign of the value in radians to the value of pi
  T signedPI = boost::math::copysign(boost::math::constants::pi<T>(),rad);
  // set the value of rad to the appropriate signed value between pi and -pi
  rad = std::fmod(rad+signedPI,(boost::math::constants::two_pi<T>())) - signedPI;

  return rad;
}

// functor for getting sum of previous result and square of current element
// source: http://stackoverflow.com/questions/1326118/sum-of-square-of-each-elements-in-the-vector-using-for-each
template<typename T>
struct square
{
    T operator()(const T& Left, const T& Right) const
    {
        return (Left + Right*Right);
    }
};

namespace boost { namespace geometry {

double comparable_distance(ArmPos const& p1, ArmPos const& p2 ) {
    ArmPos diff;
    boost::transform(p1,p2,diff.begin(),std::minus<ArmPos::value_type>());
    boost::transform(diff,diff.begin(),&normalizeRadiansPiToMinusPi<ArmPos::value_type>);
    return boost::accumulate(diff,0,square<ArmPos::value_type>());
}

template<typename Box>
double comparable_distance(ArmPos const& armpos, Box const& box ){
    namespace bg = boost::geometry;
    ArmPos normAP = normalizeRadiansPiToMinusPi(armpos);
    ArmPos mindiff;
    boost::transform(normAP,bg::get<bg::min_corner>(box),mindiff.begin(),std::minus<ArmPos::value_type>());
    boost::transform(mindiff,mindiff.begin(),&normalizeRadiansPiToMinusPi<ArmPos::value_type>);
    ArmPos maxdiff;
    boost::transform(normAP,bg::get<bg::max_corner>(box),maxdiff.begin(),std::minus<ArmPos::value_type>());
    boost::transform(maxdiff,maxdiff.begin(),&normalizeRadiansPiToMinusPi<ArmPos::value_type>);

    ArmPos::value_type final_distance = 0.0;
    for(int i = 0; i < armpos.size(); ++i){
        if(mindiff[i] >= 0.0 && maxdiff[i] <= 0.0) continue; // between the min and max means "in the box" for this dimension
        ArmPos::value_type min_dist = std::min(std::abs(mindiff[i]),std::abs(maxdiff[i]));
        final_distance+=min_dist*min_dist;
    }

    return final_distance;
//    diff (min<D> - p<D>), (p<D> - max<D>)
}

Full code can be found in this gist.


texts: Is this a good user control layout for WPF?

texts:
Below is a code snippet of how I have been laying out my WPF control XAML. I do it mainly because I get intellisense in the editor and I can change the implementation of the viewmodel and push the layout into a resource file.

However, I am not sure whether you gurus have a better insight into why I should not do this?

I'm just after a critique really.

<UserControl.Resources>
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="../../Styles/BaseStyles.xaml"/>
    </ResourceDictionary.MergedDictionaries>

    <DataTemplate x:Key="LayoutRoot"
                  DataType="{x:Type ns:IViewModel}">

        <Grid Height="200" Width="300">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Label Content="Some Label" Style="{StaticResource BoldLabel}" Margin="5, 0"
                   Target="{Binding ElementName=Lcb1}"/>

            <endorsements:LimitComboBox Grid.Row="0" Grid.Column="1" x:Name="Lcb1"
                            Limit="{Binding SomeData}" />

            <Label Grid.Row="1" Grid.Column="0" Content="Some Other Label"
                   Style="{StaticResource BoldLabel}" Margin="5, 0" Target={Binding ElementName=Lcb2/>

            <endorsements:LimitComboBox Grid.Row="0" Grid.Column="1" x:Name="Lcb2"
                            Limit="{Binding SomeOtherData}" />

            <StackPanel Grid.Row="3" Grid.Column="0" Orientation="Horizontal" HorizontalAlignment="Right" Grid.ColumnSpan="2">
                <Button Content="OK" Command="{Binding ApplyCommand}" IsDefault="True"/>
                <Button Content="Cancel" IsCancel="True"/>
            </StackPanel>
        </Grid>
    </DataTemplate>
</ResourceDictionary>


texts: Write to the event log without needing to check whether or not it exists by use of a `-Force` parameter

texts:
Below is some powershell to write to the event log; if the -Force parameter is specified this saves you the effort of writing additional code to first check whether the log exists.

I had to make use of Remove-Variable to allow some parameters to flow through; I'd not used that feature before / been aware of that nuance, so not sure whether this is the best approach?

cls
$myLog = 'Application'
$mySource = 'My PS Script'
$myEventId = 1
[System.Diagnostics.EventLogEntryType]$myEntryType = [System.Diagnostics.EventLogEntryType]::Error
$myMessage = 'This is a test message'
$myMessage2 = 'This is a test message (2)'
$myMessage3 = 'This is a test message (3)'

function Write-EventLog2
{
    [cmdletbinding()]
    param(
        [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [String]$LogName
        ,
        [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [String]$Source
        ,
        [Parameter(Position=3,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [Int32]$EventId
        ,
        [Parameter(Position=4,Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [System.Diagnostics.EventLogEntryType]$EntryType
        ,
        [Parameter(Position=5,Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
        [String]$Message
        ,
        [Parameter(Position=6,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
        [Int16]$Category
        ,
        [Parameter(Position=7,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
        [String]$ComputerName
        ,
        [Parameter(Position=8,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
        [Byte[]]$RawData
        ,
        [Parameter(Position=9,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
        [switch]$Force
    )

    begin
    {
        if($Force.IsPresent)
        {
            if (! ([System.Diagnostics.EventLog]::Exists($LogName) -and [System.Diagnostics.EventLog]::SourceExists($Source) ))
            {
                New-EventLog -LogName $LogName -Source $Source
            }
        }
    }
    process
    {
        if(!$EntryType) {Remove-Variable EntryType};
        if(!$Message) {Remove-Variable Message};
        if(!$Category) {Remove-Variable Category};
        if(!$ComputerName) {Remove-Variable ComputerName};
        if(!$RawData) {Remove-Variable RawData};
        Write-EventLog -LogName $LogName -Source $Source -EventId $EventId -EntryType $EntryType -Message $Message #-Category $Category -ComputerName $ComputerName -RawData $RawData
    }
    #end{} #no ending actions required
}

Write-EventLog2 $myLog $mySource $myEventId $myEntryType $myMessage -Force #ensure the log's created if doesn't exist
Write-EventLog2 $myLog $mySource $myEventId $myEntryType $myMessage2 -Force #just to demo that we don't get an error if source already exists
Write-EventLog2 $myLog $mySource $myEventId $myEntryType $myMessage3 #this is how we'd generall call once we were certain the command had been called at least once with -Force
Show-EventLog #check that the above code produced the expected logs


texts: Simplifying an AngularJs directive that counts the number of characters entered in a textarea

texts:
I am trying to implement an AngularJS directive that would count the number of characters entered into a textarea and display it to the user.

Note: it will actually become much more complex later on and will become a full-fledged component that will be similar to the js component used by Stack Overflow for user comments: users will be notified how many more characters they may or must enter with different font colors.

Here is how the markup would look for the initial version:

       <cmp>
         <enhanced-textarea ng-model="name"></enhanced-textarea>

{{name}}

         <notice></notice>
       <cmp>

My js code is as follows:

var myModule = angular.module('myModule', []);
myModule.directive('cmp', function(){
    return {
        restrict: 'E',
        controller: 'cmpCtrl',
        replace: true,
        transclude: true,
        scope: {
            name: '='
        },
        template: '

'
    };
})
.controller('cmpCtrl', function ($scope, $element, $attrs) {
   $scope.$parent.$watch('name', function(newVal){
       if(newVal){
            $scope.$parent.updatedSize = newVal.length;
            console.log(newVal.length);
       }
   }, true);
})
.directive('enhancedTextarea', function () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: '<textarea ng-transclude></textarea>'
    };
})
.directive('notice', function () {
    return {
        restrict: 'E',
        require: '^cmp',
        replace: true,
        scope: {
            updatedSize: '='
        },
        template: '
{{size}}
',
        link: function($scope, $element, $attrs, cmpCtrl){
            console.log(cmpCtrl);
            $scope.$parent.$watch('updatedSize', function(newVal){
               if(newVal){
                  $scope.size = newVal;
               }
           }, true);
        }
    };
});

function myController($scope) {
    $scope.name = 'test';
};

I find it overly complex and I am sure it can be simplified.

Can anyone please advise and help perhaps by providing alternatives together with explanations?

Here is the fiddle


texts:
I've just created a function to check if your IP is within an array of IPs. The IP array can contain ranges like 192.168/170.50.0/255. I have a working example, but it seems a bit clunky to me.
Is there anything wrong with my method, or anything I could improve?
Link to Ideone example.
<?php

function checkIpWhitelist($whitelist, $yIp){

    $ips = $whitelist;
    $ySplitIp = explode('.', $yIp);

    $found = null;

    // Loop each IP.
    foreach($ips as $ip){

        // Explode it into parts.
        $splitIp = explode('.', $ip);

        // Each part.
        foreach($splitIp as $index => $part){

            // If this IP has failed a part, skip the rest of it.
            if($found === false){
                continue;
            }

            // Default to an array of just the part value.
            $range = array($part);

            // If the part contains a /, it's a range.
            if(strpos($part, '/') !== false){

                // Split the range.
                $range = explode('/', $part);

                // Make a new array, containing the full range.
                $range = range($range[0], $range[1]);
            }

            // If the part is in the range.
            if(in_array($ySplitIp[$index], $range)){
                $found = true;
            } else {
                $found = false;
            }
        }

        // If $found is true, all IP sections are matched. If not, reset $found to null.
        if($found === true){
            return true;
        } else {
            $found = null;
        }
    }

    return $found;
}

$yIp = '192.168.59.3';
$whitelist = array(
    array(
        '192.168.60.1',
        '192.168.0/50.3',
        '192.160/170.59.4'
    ),
    array(
        '192.168.60.1',
        '192.168.0/50.3',
        '192.160/170.59.3',
        '192.168.59.3'
    ),
    array(
        '192.168.60.1',
        '192.168.0/50.3',
        '192.160/167.59.3',
        '190/193.160/169.50/60.0/5',
        '192.168.59.3'
    )
);

foreach($whitelist as $list){
    var_dump("\n\n" . (checkIpWhitelist($list, $yIp) ? 'IP in range!' : 'IP not in range') . "\n\n");
}
?>

The examples return:

IP not in range
IP in range!
IP in range!


texts: Review my prime factorization function. Is it complete?

texts:
This is a function designed to return all the prime factors of a given number, in sorted order from least to greatest, in a list. It relies on another function that checks if a given number is prime. Here is the prime checking function:

def isPrime(x):
    if x <= 1 or isinstance(x,float):
        return False
    else:
        for divisor in range(2,x,1):
            if x % divisor == 0:
                return False
        return True

Here is the prime factorization function:

def allPrimeFactors(y):
    primeFactors = []
    restart = True
    while restart:
        restart = False
        for i in range(2,y,1):
            if y % i == 0 and isPrime(i):
                primeFactors.append(i)
                y = y / i
                if isPrime(y) and y == i:
                   primeFactors.append(y)
                else:
                   pass
                restart = True
            else:
                pass

    primeFactors.sort()
    return primeFactors

The while loop is designed to restart the for loop at the first iterable value, which is, in this case, 2. This is so that, if y factors into 2, or any other prime, more than once, it will appear in the final list more than once, how ever many times it, or any other prime, is part of the factorization of y. I found that, if a number's prime factorization was 2 primes of the same value, it would return an incomplete list, therefore I added the if statement to the end of the function so that if the final value of y was prime AND equal to the current value of i, it would append the final value of y to the end of the list, therefore making it complete.

This is a looping function I made to test the prime factorization function with a large set of numbers:

def primeFactorsTester(d,e):
for f in range(d,e+1,1):
    if f == 1:
        print "1 is undefined"
    elif isPrime(f):
        print str(f) + " is prime"
    else:
        print "the prime factors of " + str(f) + " are "+ str(allPrimeFactors(f))

It is meant to produce an output that is human readable, and is primarily a testing function.

Does my prime factorization function seem complete or incomplete? Any general feedback to give? I would love to know.


texts:
I just wanted to post my code to request for any improvement. Originally, I did NOT come up with this code, but rather I 'improved' it visually (i.e. not performance). This code originally had several if statements that I wanted to improvise with a dictionary.

In summary, this will generate a canvas named "c" that will start blank. As the click() function is performed, it will randomly select a side on a dice while also animating it. There is an actual 'dice roll' feature to this using Tkinter's grid.

enter code here
import tkinter as tk
from random import randint

def create_dice():
    """
    Creates the dice with all the sides drawn in a list.
    The sides are drawn by the draw_dice function.

    :return: dice list
    """
    dice = list()
    dice.append(draw_dice('dot0'))  # empty
    dice.append(draw_dice('dot4'))  # center dot --> 1
    dice.append(draw_dice('dot3', 'dot5'))  # dice head 2
    dice.append(draw_dice('dot2', 'dot4', 'dot6'))  # dice head 3
    dice.append(draw_dice('dot1', 'dot2', 'dot6', 'dot9'))  # dice head 4
    dice.append(draw_dice('dot1', 'dot2', 'dot4', 'dot6', 'dot9'))  # dice head 5
    dice.append(draw_dice('dot1', 'dot2', 'dot3', 'dot5', 'dot6', 'dot9'))  # dice head 6
    return dice

def draw_dice(*args):
    """
    Creates the individual heads passed in through the
    create_dice function.

    :param args: string(s) for certain dots for certain heads
    :return: c canvas
    """
    w, h = 23, 23 # sets width and height
    x, y, r = 2, 2, 5 # sets x, y, and radius
    c = tk.Canvas(root, width=w, height=h, bg='white') # creates canvas c

    #Dictionary containing lambda functions to draw dots on canvas c
    dots = {
        'dot0': lambda x, y, r: c,
        'dot1': lambda x, y, r: c.create_oval(x, y, x + r, y + r, fill='black'),
        'dot2': lambda x, y, r: c.create_oval(x + 16, y, (x + 16) + r, y + r, fill='black'),
        'dot3': lambda x, y, r: c.create_oval(x, y + 8, x + r, (y + 8) + r, fill='black'),
        'dot4': lambda x, y, r: c.create_oval(x + 8, (y + 8), (x + 8) + r, (y + 8) + r, fill='black'),
        'dot5': lambda x, y, r: c.create_oval(x + 16, (y + 8), (x + 16) + r, (y + 8) + r, fill='black'),
        'dot6': lambda x, y, r: c.create_oval(x, y + 16, x + r, (y + 16) + r, fill='black'),
        'dot9': lambda x, y, r: c.create_oval(x + 16, y + 16, (x + 16) + r, (y + 16) + r, fill='black')
    }

    for arg in args:
        dots.get(arg)(x, y, r) # Gets the dictionary keys while passing in x, y, and r values

    return c

def click():
    """
    Performs the operation of clicking the button. This will roll through
    the different dice heads

    :return: None
    """
    t = 100 # start with a time delay of 100 ms and increase it as the dice rolls
    stop = randint(13, 18) # chooses random number between 13 - 17
    for x in range(stop):
        dice_index = x % 6 + 1 # gets the randomly selected dice head by modulo
        dice_list[dice_index].grid(row=1, column=0, columnspan=3)
        root.update()
        if x == stop - 1:
            # set text to the selected result
            text.set(str(x % 6 + 1))
            break
        root.after(t, dice_list[dice_index].grid_forget()) # forgets the grid and restarts
        t += 25

# create the window form
root = tk.Tk()
root.title("Dice Roll")

# StringVar() updates result label automatically
text = tk.StringVar()

# set initial value of text
text.set("")

# create the result label
result = tk.Label(root, textvariable=text, fg='black')
result.grid(row=3, column=0, columnspan=3)
dice_list = create_dice()

# start with an empty canvas
dice_list[0].grid(row=1, column=0, columnspan=3)
button1 = tk.Button(root, text="Roll", command=click)
button1.grid(row=2, column=0, padx=3, pady=3)
button2 = tk.Button(root, text="Quit", command=root.destroy)
button2.grid(row=2, column=1, pady=3)

# start of program event loop
root.mainloop()


texts: Custom ResponseModel for Spring Controller - ResponseEntity

texts:
I created a custom responseModel to have a standard json responseModel for some of my different RestController.

Superclass TransactionResponseModel:

public class TransactionResponseModel {

    private HttpStatus httpStatus;
    private Double amount;
    private String transactionId;
    private String message;

    public SvsTransactionResponseModel() {
        super();
    }

    public SvsTransactionResponseModel(HttpStatus httpStatus, String message) {
        super();
        this.httpStatus = httpStatus;
        this.message = message;
    }
   //public getter/setter
}

Class BalanceInquiryResponseModel:

public class BalanceInquiryResponseModel extends SvsTransactionResponseModel {

    private final BalanceInquiryResponse balanceInquiryResponse;

    public BalanceInquiryResponseModel(BalanceInquiryResponse balanceInquiryResponse) {
        super();
        this.balanceInquiryResponse = balanceInquiryResponse;
        if (this.balanceInquiryResponse != null && this.balanceInquiryResponse.getBalanceInquiryReturn() != null) {
            setAmount(this.balanceInquiryResponse);
            setMessage(this.balanceInquiryResponse);
            setTransactionId(this.balanceInquiryResponse);
            setHttpStatus();
        }
    }

    private void setAmount(BalanceInquiryResponse balanceInquiryResponse) {
        if (balanceInquiryResponse.getBalanceInquiryReturn().getBalanceAmount() != null) {
            setAmount(balanceInquiryResponse.getBalanceInquiryReturn().getBalanceAmount().getAmount());
        }
    }

    private void setTransactionId(BalanceInquiryResponse balanceInquiryResponse) {
        setTransactionId(balanceInquiryResponse.getBalanceInquiryReturn().getTransactionID());
    }

    private void setMessage(BalanceInquiryResponse balanceInquiryResponse) {
        if (balanceInquiryResponse.getBalanceInquiryReturn().getReturnCode() != null) {
            setMessage(balanceInquiryResponse.getBalanceInquiryReturn().getReturnCode().getReturnDescription());
        }
    }

    private void setHttpStatus() {
        setHttpStatus(HttpStatus.OK);
    }
}

The BalanceInquiryResponseModel expects a BalanceInquiryResponse Object for setting different attributes. Nearly all attributes for my BalanceInquiryResponseModel are coming from a thiry-party Object BalanceInquiryResponse. This third-party object has to many information and because of that I dont want to response this object to the caller but set instead all the necessary attributes manually.

In my Controller I just return a ResponseEntity<? extends SvsTransactionResponseModel>.

@PostMapping(value = "/balanceInquiry")
public ResponseEntity<TransactionResponseModel> getBalanceInquiry(
        @Valid @RequestBody BalanceInquiryModel balanceInquiry, Errors errors) {
    if (errors.hasErrors()) {
        return new ResponseEntity<>(
                new TransactionResponseModel(HttpStatus.BAD_REQUEST, errors.getAllErrors().toString()),
                HttpStatus.BAD_REQUEST);
    }
    BalanceInquiryResponse balanceInquiryResponse = null;
    //logic to get the balanceInquiryResponse.

    return new ResponseEntity<>(new BalanceInquiryResponseModel(balanceInquiryResponse), HttpStatus.OK);
}

For other controllers I will have the other responseModels extending TransactionResponseModel.

Is this a good approach for a custom responseModel?

Tech-Stack:

spring-boot


texts:
I have a Back function, and it is growing.  I also think this is terrible, but I don't seem to get how it can be improved:

public void GoBack()
{
    NavButtonUsed = true;

    Forward.Insert(0, Back[0]);
    Back.RemoveAt(0);

    if (Back[0].Title.StartsWith(" ") && CurrentItem.Menu != Back[0].Menu)
    {
        switch (Back[0].Menu)
        {
            case Menus.WSOneNote:
                CurrentItem = ItemList[0];
                break;

            case Menus.WSMainMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("MainMenu"), typeof(WindowsData.MainMenu), Menus.WSMainMenu))];
                break;

            case Menus.WSTextMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("TextMenu"), typeof(WindowsData.TextMenu), Menus.WSTextMenu))];
                break;

            case Menus.WSTextBlockMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("TextBlockMenu"), typeof(WindowsData.TextBlockMenu), Menus.WSTextBlockMenu))];
                break;

            case Menus.WSTableMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("TableMenu"), typeof(WindowsData.TableMenu), Menus.WSTableMenu))];
                break;

            case Menus.WSTableCellsMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("TableCellsMenu"), typeof(WindowsData.TableCellsMenu), Menus.WSTableCellsMenu))];
                break;

            case Menus.WSDrawMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("DrawMenu"), typeof(WindowsData.DrawMenu), Menus.WSDrawMenu))];
                break;

            case Menus.WSDrawnItemsMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("DrawnItemsMenu"), typeof(WindowsData.DrawnItemsMenu), Menus.WSDrawnItemsMenu))];
                break;

            case Menus.WSPictureMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("PictureMenu"), typeof(WindowsData.PictureMenu), Menus.WSPictureMenu))];
                break;

            case Menus.WSFileMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("FileMenu"), typeof(WindowsData.File), Menus.WSFileMenu))];
                break;

            case Menus.WSAppBarsMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("AppBarsMenu"), typeof(WindowsData.AppBar), Menus.WSAppBarsMenu))];
                break;

            case Menus.WSCharmsMenu:
                CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("CharmsMenu"), typeof(WindowsData.Charms), Menus.WSCharmsMenu))];
                break;

            default:
                break;
        }
    }

    CurrentItem = ItemList[ItemList.IndexOf(Back[0])];
    NavButtonUsed = false;
}

I have more menus to account for, but I haven't implemented going back to them yet as I do not have them fully implemented.  What is really going on here is I need to programmatically select a menu to open it so I can select a menu item within it.  If I do not open the menu, ItemList will not have CurrentItem, so the app will crash.

This is CurrentItem:

private MenuItem _currentItem = new MenuItem(resourceFile.GetString("OneNote"), typeof(WindowsData.OneNote), Menus.WSOneNote);
public MenuItem CurrentItem
{
    get { return _currentItem; }
    set
    {
        if (value == _currentItem) { return; }
        _currentItem = value;
        OnPropertyChanged();
    }
}

ItemList, Back, and Forward are just ObservableCollections of MenuItems (they can't be Lists because they are bound to XAML objects that need to know when they are updated).


texts:
I want to construct a form builder for an internal project in mvc4. I am using partial views to load the various controls. However I feel that having ten or 20 action-results in my HomeController would not be the best way to go.
So I am wondering how I could do the following more efficiently.

As you see here I have three different posts happening for three partials views anyway to get this down to one. And what way would be best to save the form generated below. I was thinking of putting each of the actions in a POCO class, which would store the names of the controls etc.

<input id="btnLoad" type="button" value="LoadRegistrationTemplate"/>
<input id="btnDropDown" type="button" value="Load DropDown"/>
<input id="txtarea" type="button" value="Text Area"/>

And also the same case in my HomeController I have the same three different Result Partials.

    [HttpPost]
    public ActionResult HtmlControlTest()
    {
        return PartialView("HtmlControlTest");
    }

    [HttpPost]
    public ActionResult DropDown()
    {
        return PartialView("DropDown");
    }

    [HttpPost]
    public ActionResult TextArea()
    {
        return PartialView("TextArea");
    }

I feel that this would be best method to go by as under each actionresult I could store the control info in a class. But I don't know how I would pass variables to the actionresult.


texts:
I'm working on a simple CMS. It's working quite ok, but I think my code can be improved a bit. I work with a section.php, which is included from the index.php with (example):

switch($_GET['key'])
{
case '': $page='section'; $id='1'; break;
case 'home': $page='section'; $id='1'; break;
}
include ('header.php');
include ($page.'.php');
include ('footer.php');

But I would like some feedback on my section.php code. I have very little knowledge of OOP, but if possible I would like to use it for section.php. I used it a little for $validator which checks for clean URLs. But I have trouble with re-using the same $sql_queries.

section.php:

<?php

        #-------------------------------------------#
        # SIDEBAR                                   #
        #-------------------------------------------#

echo "
";
$result = mysql_query('SELECT ID,title,tagline FROM cmsarticles WHERE section = '.$id.' ORDER BY id ASC LIMIT 4');
    while ($row = mysql_fetch_array($result)){
    $path = 'photos/';
    $safeid = $validator->clean_url($row['title'].'-'.$row['ID']);
    $get_photo = "SELECT name,artId,posId FROM images WHERE artId = ".$row['ID']." AND posId = 2 LIMIT 3";
    $photothumbs = mysql_query($get_photo) or die(mysql_error());
        while($photothumb = mysql_fetch_array($photothumbs)){
        echo '';
        }
    }
echo "
";

        #-------------------------------------------#
        # CONTENT                                   #
        #-------------------------------------------#

echo "
";
$query= mysql_query('SELECT cmsarticles.ID AS artID, cmsarticles.title, cmsarticles.tagline, cmsarticles.thearticle, cmsarticles.section, cmssections.ID, cmssections.name
FROM cmsarticles, cmssections
WHERE cmsarticles.section = cmssections.ID
AND cmsarticles.section ='.$id.' ORDER BY cmsarticles.ID ASC');
$num_results = mysql_num_rows($query);
if ($num_results == 0){
echo 'Nothing here at the moment.';
}else{
    while($result = mysql_fetch_array($query)) {
    $safeid = $validator->clean_url($result['title'].'-'.$result['artID']);
    echo "

".$result['title']."
";
    $query2 = mysql_query('SELECT name,artId,posId FROM images WHERE artId = '.$result['artID'].' AND posId = 1 LIMIT 1');
        while($result2 = mysql_fetch_array($query2)){
        echo '';
        }
    echo"
".$result['thearticle']."

";
    }
}
echo "
";

?>


texts: Program that teaches kids Chinese characters

texts:
I wrote code that chooses a random set of Chinese characters, asks the user what the characters are, and if they meet a certain criteria they level up (ex. get more than 50% correct). I want to know if there is a better way to have fewer lists, better organization, etc.

# -*- coding: utf-8 -*-
import random

allnumbers = {"一": "one", "二": "two", "三": "three", "四": "four", "五": "five",
              "六": "six", "七": "seven", "八": "eight", "九": "nine", "十": "ten"}

Numbers = {"四": "four", "五": "five", "六": "six", "七": "seven", "八": "eight",
           "九": "nine", "十": "ten"}

People = {"我": "I or me", "你": "you", "他": "He or him", "她": "Her or she"}

Family = {"爸": "Dad", "妈": "Mom", "哥": "Older brother", "弟": "Younger brother",
          "姐": "Older sister", "妹": "Younger sister"}
NotLearned = [Numbers, People, Family]
Learned = []
Practiced = []
LevelOne = []
LevelTwo = []
Mastered = []
setlist = {"Numbers": Numbers, "People": People, "Family": Family}
allLev = [NotLearned,Learned,LevelOne,LevelTwo,Mastered]
all = [Numbers, People, Family]

charlist = []
set = random.choice(all)
k = set.keys()
k = random.sample(k, len(k))
outof = 0
total = len(set)
while True:
    print "Welcome! Just type in the character requested! If you want to exit, type quit."
    for x in range(0, len(set)):
        char = k[x]
        question = raw_input("Write Chinese for \"{}\" (Hint: it's {}): ".format(set[char], char))
        if question == char:
            print "You got it right!"
            outof += 1
        else:
            print "Sorry, that's incorrect"
    score = float(outof)/float(total)
    print "You got {}%. Good Job!".format(100 * score)

    if set in NotLearned:
        print "Good job learning that set!"
        NotLearned.remove(set)
        Learned.append(set)
    if set in Learned:
        if score >= .5:
            print "Good job practicing!"
            Learned.remove(set)
            Practiced.append(set)
    if set in Practiced:
        if score >= .6:
            print "Good job getting to Level One!"
            Practiced.remove(set)
            LevelOne.append(set)
    if set in LevelOne:
        if score >= .75:
            print "Good job getting to Level Two!"
            LevelOne.remove(set)
            LevelTwo.append(set)
    if set in LevelTwo:
        if score == 1:
            print "Great job mastering {}".format(set)
            LevelTwo.remove(set)
            Mastered.append(set)


texts:
Please review the following code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char *some_text = "THIS IS SOME ARBITRARY TEXT FOR TESTING THE STRLEN AND COPY FUNCTIONS";

    char *test = malloc(strlen(some_text) + 1);
    strncpy(test, some_text, strlen(some_text));
    strcat(test, "\0");

    printf("%s\n", test);
    if (test != NULL) free (test);
}

create a char* some_text with constant string;
create a char*test with and allocate memory the size of some_text
copy the content of some_text to test
concatenate the termination character to test
print out the test
free the test pointer

If I run this with valgrind, it says:

==31176== Conditional jump or move depends on uninitialised value(s)
==31176==    at 0x4008667: __GI_strlen (mc_replace_strmem.c:404)
==31176==    by 0x861DD4: puts (in /lib/libc-2.12.so)
==31176==    by 0x80484DF: main (strlen_and_copy.c:13)

The line mentioned in valgrind output strlen_and_copy.c:13 is below:

printf("%s\n", test);

Is it avoidable or should it be ignored? What is wrong with my code above?  Someone please explain.


texts:
This query performs a FizzBuzz in SQLite 2.8.17 without creating any tables or sprocs.

First attempt:

select case when fb <> '' then fb else n end from (
    select g + f * 2 + e * 4 + d * 8
        + c * 16 + b * 32 + a * 64 as n,
    coalesce(fizz, '') || coalesce(buzz, '') as fb
    from
    (select 0 union select 1 as a),
    (select 0 union select 1 as b),
    (select 0 union select 1 as c),
    (select 0 union select 1 as d),
    (select 0 union select 1 as e),
    (select 0 union select 1 as f),
    (select 0 union select 1 as g)
    left join (select 'Fizz' as fizz, 3 as fizzstep)
        on n % fizzstep = 0
    left join (select 'Buzz' as buzz, 5 as buzzstep)
        on n % buzzstep = 0
    where n between 1 and 100
);

Second attempt:

select case
    when n % 3 = 0 and n % 5 = 0 then 'FizzBuzz'
    when n % 3 = 0 then 'Fizz'
    when n % 5 = 0 then 'Buzz'
    else n
end from (
    select g + f * 2 + e * 4 + d * 8 +
        c * 16 + b * 32 + a * 64 as n from
    (select 0 union select 1 as a),
    (select 0 union select 1 as b),
    (select 0 union select 1 as c),
    (select 0 union select 1 as d),
    (select 0 union select 1 as e),
    (select 0 union select 1 as f),
    (select 0 union select 1 as g)
    where n between 1 and 100
);

Can it be improved, either by:

making it shorter / less redundant, or
making it significantly faster, or
making it more portable so it also works in another RDBMS (including SQLite 3)?

Note that CTEs are not available until later versions of SQLite. Also note that this won't work as written on sqlfiddle.com; they're using SQLite 3.


texts:
What do you think of this idea?  It's supposed to be a dict that makes a reasonable guess at the key you were trying to access for getters and deleters.  Setters should be untouched.

Similar to how tab completion in bash works, if some command you are typing only has one reasonable completion then pressing tab will fill it out for you.

The logic should be like this, if the query_key is not in the dict but there is only one dict_key satisfying the expression query_key in dict_key then we can assume that is the key.  For string keys, additionally, it should be case-insensitive.

class FriendlyDict(dict):

    def _guess_key_or_die(self, q):
        possibilities = []
        for key in self:
            try:
                if q in key or q.lower() in key.lower():
                    possibilities.append(key)
            except (TypeError, AttributeError):
                pass
        if len(possibilities) == 1:
            return possibilities[0]
        err = KeyError(q)
        err.data = possibilities
        raise err

    def __getitem__(self, key):
        try:
            return super(FriendlyDict, self).__getitem__(key)
        except KeyError:
            guess = self._guess_key_or_die(key)
            return super(FriendlyDict, self).__getitem__(guess)

    def __delitem__(self, key):
        try:
            return super(FriendlyDict, self).__delitem__(key)
        except KeyError:
            guess = self._guess_key_or_die(key)
            return super(FriendlyDict, self).__delitem__(guess)

    def __contains__(self, key):
        if super(FriendlyDict, self).__contains__(key):
            return True
        try:
            self._guess_key_or_die(key)
        except KeyError:
            return False
        else:
            return True

Are there any more __dunder__ methods which really should be overridden?
Are there any gotchas I may have missed which might make the class behave in weird/unpredictable ways?
Are there any other nice features that could be added which are consistent with the general idea of this?
Is it better as a subclass or would it be possible to make it a mixin to use with other types of mappings, e.g. OrderedDict?


texts: Rails controller method that conditionally filters results

texts:
This code for my blog checks to see if tags are in the params hash. If they are, then only posts that are tagged will be paginated. Otherwise, all of the posts are paginated.

class PostsController < ApplicationController
  def index
    if params[:tag]
      @posts = Post.tagged_with(params[:tag]).paginate(page: params[:page])
    else
      @posts = Post.all.paginate(page: params[:page])
    end
  end
end

I feel like this checking of params shouldn't be the concern of the controller, but of some other model like PostParameterChecker. How do you feel about this? Where does this code actually belong?


texts:
This is a follow up from this question. The goal is to make some function that can return the number of possible permutations with repetitions. As Gareth pointed out there is a nice formula for this problem:

$$
\frac{m!}{n_1!\,n_2! \ldots n_k!}
$$

Where \$m\$ is the length of our permutations and \$n_i\$ is the number of times the \$i\$th letter appears in \$m\$. A simple example can be shown with the word Mississippi.

$$
P(\text{Mississippi}) = \frac{11!}{4!\,4!\,2!}
$$

A simple implementation of this can be done in Python as follows:

from numpy import prod
def count_unique_perms(obj):
    obj = str(obj)
    f = [factorial(i) for i in Counter(obj).values()]
    return factorial(len(obj))/prod(f)

I include this code as a basetest for the "improved" version below. Questions were raised whether this approach works for large factorials, and it was said that the running time was at worst \$O(n^3(log n)^2)\$

I used the ideas from my previous question. To try to improve the answer. First I find the number of factors in \$m!\$ then I subtract the factors from \$n_1!\,n_2! \ldots n_k!\$. A small optimization I did was avoiding calculating duplicates.

My question if this is a decent improvement. It seems much slower until really big string. For example, it is slightly faster for str(Mississippi)*500. Any other tips or algorithms are also welcome =)

from collections import Counter
from math import factorial, log
from numpy import prod
from primesieve import generate_primes

def count_unique_perms(obj):
    obj = str(obj)
    f = [factorial(i) for i in Counter(obj).values()]
    return factorial(len(obj))/prod(f)

def fast_unique_perms(obj):
    obj = str(obj)
    factors = factors_factorial(len(obj))

    obj_count = Counter([i for i in Counter(obj).values() if i > 1])
    for p in obj_count:
        count_p = factors_factorial(p, obj_count[p])
        for prime in count_p:
            factors[prime] -= count_p[prime]

    num_perms = 1
    for p in factors:
        num_perms *= p**factors[p]
    return num_perms

def factors_factorial(n, multiplicity=1):
    "Calculates all the facors of n!"
    count = Counter()
    for p in generate_primes(n+1):
        mul = 0
        for k in range(1, int(1+log(n)/log(p))):
            mul += int(n/p**k)
        count[p] = multiplicity*mul
    return count

if __name__ == '__main__':
    import timeit

    lst = 1123
    string = 'mississippi'
    print count_unique_perms(string)
    print fast_unique_perms(string)
    times = 100
    t1 = timeit.timeit("count_unique_perms('mississippi'*1000)",
                       setup="from __main__ import count_unique_perms", number=times)/float(times)
    t2 = timeit.timeit("fast_unique_perms('mississippi'*1000)",
                       setup="from __main__ import fast_unique_perms", number=times)/float(times)

    print "fast_unique_perms: ", 1000*t2, "ms"
    print "count_unique_perms:  ", 1000*t1, "ms"
    print "The count_unique_perms solution was:   ", t2/float(t1), "times faster than fast_unique_perms."


texts:
Here is my Countdown word solver.

This code aims to find all possible permutations of any length of a given input (which in the Countdown words game is any random assortment of letters).
It then compares each permutation with the dictionary and prints it if it is a valid word. For example the letters "PHAYPC" could yield the following words (not limited to):

Chap
Happy
Hay

I've used the enchant library as my dictionary checker.

import itertools
import enchant

word = input("Please enter the letters or words to scramble: ")
perm_words = itertools.chain.from_iterable(itertools.permutations(word, i) for i in range(3,len(word)))
list_possible = []
list_words_print = []

for item in perm_words:
    list_possible.append("".join(item).lower())

dictionary = enchant.Dict("en_UK")
for word in list_possible:
    if dictionary.check(word):
        if word not in list_words_print: list_words_print.append(word)

print (list(item for item in list_words_print))
exit_key = input("Press any key to exit")


texts:
I have written a program to display the kth permutation sequence of a string made up of letters 'O' and 'Z' . I tried optimizing it but my code have not passed test cases due to timeout issues.Looking for someone who can guide me in optimizing the code i posted below.

public static void main(String[] args) throws IOException {

    /*
     * Sample Input
     * 1
     * 3 2 // Passing two inputs as single string
     *
     * Sample Output
     * OOZ
     */

    // Scanner in = new Scanner(System.in);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = br.readLine();
    // Getting 2 integer inputs with space
    String[] k1 = br.readLine().split("\\s");

    // String b1 = br.readLine();
    String eol = System.getProperty("line.separator");
    // byte[] eolb = eol.getBytes();

    long t = Integer.parseInt(line);

    long k = Integer.parseInt(k1[0]);
    long b = Integer.parseInt(k1[1]);
    char set1[] = { 'O', 'Z' };
    ArrayList<String> prefixlist = new ArrayList<String>();
    printAllKLength(set1, k, prefixlist, b);

}

static void printAllKLength(char set[], long k,
        ArrayList<String> prefixlist, long b) throws IOException {
    int n = set.length;
    BufferedOutputStream bout = new BufferedOutputStream(System.out);
    printAllKLengthRec(set, "", n, k, prefixlist);
    Collections.sort(prefixlist);
    if (b <= prefixlist.size()
            && prefixlist.contains(prefixlist.get((int) (b + 1)))) {

        byte b1[] = String.valueOf(prefixlist.get((int) (b - 1)))
                .getBytes();
        bout.write(b1);
        bout.write(System.lineSeparator().getBytes());
        bout.flush();
        // System.out.println(prefixlist.get((int) (b - 1)));
    } else {
        byte b1[] = "-1".getBytes();
        bout.write(b1);
        bout.write(System.lineSeparator().getBytes());
        bout.flush();
    }
}

static void printAllKLengthRec(char set[], String prefix, int n, long k,
        ArrayList<String> prefixlist) {

    if (k == 0) {

        if (!prefix.contains("ZZ")) {

            prefixlist.add(prefix);
        }

        return;
    }

    for (int i = 0; i < n; ++i) {

        String newPrefix = prefix + set[i];

        printAllKLengthRec(set, newPrefix, n, k - 1, prefixlist);
    }

}


texts: This is a CSS/HTML/PHP dynamic text list

texts:
I'm wondering if there is a better way to write the same exact thing? I wrote it to display three different dynamic messages, but I feel like there can be a lot of improvements...

Any help/idea would be appreciated.

        .list-wrapper {
            width: 100%;
        }

        .list {
            margin: 0 auto;
            height: 25px;
            position: relative;
        }

        .list-item:nth-child(2) {
            -webkit-animation-delay: 4s;
            -moz-animation-delay: 4s;
            animation-delay: 4s;
        }

        .list-item:nth-child(3) {
            -webkit-animation-delay: 8s;
            -moz-animation-delay: 8s;
            animation-delay: 8s;
        }

        .list-item {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            opacity: 0;
            font-size: 12px;
            color: #33302d;
            line-height: 1.6px;
            -webkit-transition: 1s;
            -moz-transition: 1s;
            transition: 1s;
            padding: 6px 20px;
            text-align: center;
            -webkit-animation: Liste 12s 0s infinite;
            -moz-animation: Liste 12s 0s infinite;
            animation: Liste 12s 0s infinite;
        }

        @-webkit-keyframes Liste {
            0% { opacity: 0; }
            17% { opacity: 1; z-index: 3; }
            25% { opacity: 1;}
            40% { opacity: 0; z-index: 1; }
            100% { opacity: 0; }
        }

        @-moz-keyframes Liste {
            0% { opacity: 0; }
            17% { opacity: 1; z-index: 3; }
            25% { opacity: 1;}
            40% { opacity: 0; z-index: 1; }
            100% { opacity: 0; }
        }

        @keyframes Liste {
            0% { opacity: 0; }
            17% { opacity: 1; z-index: 3; }
            25% { opacity: 1;}
            40% { opacity: 0; z-index: 1; }
            100% { opacity: 0; }
        }

And I call it with:

        <?php echo $list['list1']?>
        <?php echo $list['list2']?>
        <?php echo $list['list3']?>

If you have any improvements in mind, here is a working fiddle.

UPDATE:

I've put in PHP foreach for lists, looks much cleaner now.

        <?php $i = 1; ?>
        <?php foreach ($liste as $value) : ?>
            <span class="list-item list-item<?php echo $i++; ?>"><?php echo $value['text']?>
        <?php endforeach; ?>

Does anybody else have any more ideas?


texts:
This is part of a Tampermonkey script that generates a box in the top right of a webpage and generates a list of checked boxes from the specified list selector (list chosen through buttons). The script works as expected; however, I am not a web guy and do not pretend to be one. My main source of contention is how poorly designed the UI is. Any advice on improving the code and UI would be much appreciated.

var zNode       = document.createElement ('div');
zNode.innerHTML = '
Create List of Items

Not SelectedSelected
'  +
    '<button id="hospNotSelectBtn" type="button">Hospitals</button>'                   +
    '<button id="hospSelectBtn" type="button">Hospitals</button>
'                               +
    '<button id="deptNotSelectBtn" type="button">Departments</button>'                 +
    '<button id="deptSelectBtn" type="button">Departments</button>
'                             +
    '<button id="jobNotSelectBtn" type="button">Job Titles</button>'                   +
    '<button id="jobSelectBtn" type="button">Job Titles</button>
'                               +
    '<button id="jobFunctionNotSelectBtn" type="button">Job Functions</button>'        +
    '<button id="jobFunctionSelectBtn" type="button">Job Functions</button>'
;
zNode.setAttribute ('id', 'myContainer');
document.body.appendChild (zNode);

GM_addStyle ( multilineStr ( function () {/*!
    #myContainer {
        position:               absolute;
        top:                    0;
        right:                  0;
        font-size:              20px;
        color:                  white;
        background:             green;
        border:                 3px outset black;
        margin:                 2px;
        padding:                2px 2px;
        text-align:             center;
    }
    #myContainer span {
        margin:                 0 10px;
    }
*/} ) );

//Function provided by Brock Adams of SE
function multilineStr (dummyFunc) {
    var str = dummyFunc.toString ();
    str     = str.replace (/^[^\/]+\/\*!?/, '') // Strip function () { /*!
        .replace (/\s*\*\/\s*\}\s*$/, '')   // Strip */ }
        .replace (/\/\/.+$/gm, '') // Double-slash comments wreck CSS. Strip them.
    ;
    return str;
}


texts:
I'm trying to loop through two separate sheets going row by row starting at row 2 comparing multiple columns (Product Number, Date, Quantity) in Excel using VBA.

My nested loops are taking way too long. Is there another way to loop through, while cutting down on time, but being able to compare multiple columns at the same time?

For i = 2 To lastRow22
    If ws2.Cells(i, 80) = 1 Or ws2.Cells(i, 80) = 2 Then
            x = ws2.Cells(i, 79)
        ElseIf ws2.Cells(i, 80) = 0 Then
            x = ws2.Cells(i, 1)
        End If
    x2 = Trim(ws2.Cells(i, 81))
    xDate = Trim(ws2.Cells(i, 19))
    xQD = Trim(ws2.Cells(i, 20))
    For j = 2 To lastRow33
        y = Trim(ws3.Cells(j, 28))
        y2 = Trim(ws3.Cells(j, 10))
        yDate = Trim(ws3.Cells(j, 13))
        yQD = Trim(ws3.Cells(j, 17))
        If x = y And xDate = yDate And xQD = yQD And ws2.Cells(i, 82) = 0 And ws3.Cells(j, 27) = 0 Then
            ws3.Cells(j, 1).Interior.Color = vbGreen
            ws2.Cells(i, 1).Interior.Color = vbGreen
            ws2.Cells(i, 82) = 1
            ws3.Cells(j, 27) = 1
        ElseIf x2 = y2 And xDate = yDate And xQD = yQD And ws2.Cells(i, 82) = 0 And ws3.Cells(j, 27) = 0 Then
            ws3.Cells(j, 1).Interior.Color = vbGreen
            ws2.Cells(i, 1).Interior.Color = vbGreen
            ws2.Cells(i, 82) = 1
            ws3.Cells(j, 27) = 1
        End If
    Next j
Next i


texts:
I have following code that creates parallel swathes of specified sizes. Can someone suggest a better way of doing this?

import matplotlib.pyplot as plt
import numpy as np
len=10; width=5;
pts=[];
for i in xrange(1,width+1):
    y_curr=i-1;
    if y_curr%2==0 :
        for j in xrange(0,len+1):
            pts.append([j,y_curr]);
    elif y_curr%2==1:
        for j in  xrange(1,len+2):
            pts.append([len+1-j,y_curr]);
pts=np.asarray(pts);
plt.plot(pts[:,0], pts[:,1])
plt.axis([-1, len+1, -1, width])
plt.show()


texts: Migrating data using entity framework, linq and recursion

texts:
I have a piece of code to migrate data from an old app to a new app. The data represents the user's websites.

In the old app the user only had one section for websites, on which you could add any website, even social links.

In the new app, the user can add personal websites, social links (only Facebook, Twitter and LinkedIn are considered social links) and what we call custom social networks (eg. Reddit, Meetup, Tumblr, etc)

This is the code:

public async Task ImportWebsites(int userId)
{
    string[] socialNetworksStr =
    {
        "linkedin.",
        "twitter.",
        "facebook.",
    };

    string[] customSocialNetworksStr =
    {   "deviantart.",
        "viadeo.",
        "reddit.",
        "xing.",
        "pinterest.",
        "tumblr.",
    };

    List<UserLinkDTO> personalWebsites = new List<UserLinkDTO>();
    List<UserSocialNetworkDTO> socialNetworks = new List<UserSocialNetworkDTO>();
    List<UserLinkDTO> customSocialNetworks = new List<UserLinkDTO>();
    List<UserLinkDTO> personalWebsitesRemoved = new List<UserLinkDTO>();

    using (OldContext ctx = new OldContext())
    {
        if (await (ctx.UserSettings.AnyAsync(u => u.UserId == userId)) == false)
            throw new RelatedEntityNotFoundException($"{userId} not be found!");

        personalWebsites = await ctx.PersonalWebsite.AsNoTracking()
                                    .Where(w => w.UserId == userId)
                                    .Select(w => new UserLinkDTO
                                    {
                                        UserId = w.UserId,
                                        Description = w.PersonalWebsiteDescription,
                                        Url = w.PersonalWebsiteURL,
                                        Name = w.PersonalWebsiteName
                                    }).ToListAsync().ConfigureAwait(false);
    }

    for (int i = 0; i < personalWebsites.Count; i++)
    {
        string url = personalWebsites[i].Url;
        if (!url.StartsWith("http://"))
        {
            personalWebsites[i].Url = "http://" + url;
        }
    }

    if (personalWebsites.Any())
    {
        foreach (var personalWebsite in personalWebsites)
        {
            foreach (var socialNetwork in socialNetworksStr)
            {
                if (personalWebsite.Url.Contains(socialNetwork))
                {
                    socialNetworks.Add(new UserSocialNetworkDTO() {
                        SocialNetworkId = (short)(Array.IndexOf(socialNetworksStr, socialNetwork) + 1),
                        Account = personalWebsite.Url
                    });
                    personalWebsitesRemoved.Add(personalWebsite);
                }
            }
            foreach (var customSocialNetwork in customSocialNetworksStr)
            {
                if (personalWebsite.Url.Contains(customSocialNetwork))
                {
                    customSocialNetworks.Add(personalWebsite);
                    personalWebsitesRemoved.Add(personalWebsite);
                }
            }
        }

        personalWebsites = personalWebsites.Except(personalWebsitesRemoved).ToList();
        var personalInfo = await PersonalInfoService.GetPersonalInfo(userId);

        personalInfo.Result.PersonalWebsites = personalWebsites;
        if(socialNetworks.Any()) personalInfo.Result.SocialNetworks = socialNetworks;
        if(customSocialNetworks.Any()) personalInfo.Result.CustomSocialNetworks = customSocialNetworks;

        var response = await PersonalInfoService.SavePersonalInfo(personalInfo.Result);
    }
}

    var response = await PersonalInfoService.SavePersonalInfo(personalInfo.Result);
}

My code does its job, but it takes some time, on those foreaches, and I think it's a little bit redundant, and I think it may be optimzed. How would you improve this?

PS I think I included all the necessary info, sorry If I forgot something.


texts:
Based on a question on SO I thought I'd knock up a cmdlet to perform an unpivot on an object.  I've not yet considered all the options (e.g. what happens when objects with empty lists are passed), so there are likely a few issues, but I wanted to get it out to the community early / see if people think this is useful or if better alternatives already exist in PS natively.

cls

function UnPivot-Object
{
    param
    (
        [Parameter(
            Mandatory=$true,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true
        )][psobject]$InputObject
        ,[Parameter(
            ValueFromPipelineByPropertyName=$true
        )][string[]]$Properties
        ,[Parameter(
            ValueFromPipelineByPropertyName=$true
        )][string]$ExpandProperty
    )
    process
    {
        $InputObject | %{
            $x = $_ ;
            $_ | select -ExpandProperty $ExpandProperty | %{
                $y = $_ ;
                $x | select $Properties | select *, @{Name="$ExpandProperty";Expression={$y}}
            }
        }
    }
}

$x = @(
     (New-Object –TypeName PSObject –Prop @{Name='one';   Var='this'; Var2='How';   List=@('a','b','c');})
    ,(New-Object –TypeName PSObject –Prop @{Name='two';   Var='test'; Var2='now';   List=@('d','e','f');})
    ,(New-Object –TypeName PSObject –Prop @{Name='three'; Var='is'  ; Var2='brown'; List=@('g','h','i');})
    ,(New-Object –TypeName PSObject –Prop @{Name='four';  Var='a'   ; Var2='cow';   List=@('j','k','l');})
    ,(New-Object –TypeName PSObject –Prop @{Name='five';  Var='test'; Var2=$null;   List=@('m','n','o');})
)

$x | UnPivot-Object -Properties Name, Var -ExpandProperty List


texts: Combining a list of realtime responses with a list of static responses

texts:
I have written this code that accepts a list of static times and a list of realtime-delayed times.  These are frequently being refreshed and there are times where a train, for example train 23, is scheduled for 2:00PM, so after 2:00PM it leaves the list.

But if it's delayed, I still want it to be a part of the final list (predictionArray), which is why I have the boolean flag set the way it is. So basically it compares every static response with every realtime response, and if true, it won't append to predictionArray (since all realtime responses are in there already).
Is there a way I could do this maybe without booleans?

Again, I need realtime responses in the predictionArray to begin with in case there are any realtime trains that have been added that aren't on the returned static schedule.

def coalesceMetraData(staticResponses, realtimeResponses):
    predictionArray = list(realtimeResponses)
    for response in staticResponses:
        responseExists = False
        for responseReal in realtimeResponses:
            if (response['key'] == responseReal['key']):
                responseExists = True
                break
        if (responseExists != True):
            predictionArray.append(response)

    predictionArray = sorted(predictionArray, key=lambda d:d['time'])

    return predictionArray[:5]


texts:
Preface: I'm starting to learn C# and I don't want to port any of my bad habits from other languages, so I'm following convention wherever possible.

Using the default Visual Studio code formatting, this relatively simple function requires 14 lines of code.

public void add(int[] values, Func<int, int> transform = null)
{
    foreach (int v in values)
    {
        if (transform == null)
        {
            add(v);
        }
        else
        {
            add(transform(v));
        }
    }
}

My first thought was to use the ?? operator to do something like the following snippet, but apparently that's gibberish.

public void add(int[] values, Func<int, int> transform = null)
{
    foreach (int v in values)
    {
        add(transform(v) ?? v);
    }
}

Is there a more concise and/or readable way to write the following method?


texts:
I have created an open source config loader in PHP, but I wish to improve on the loading of the config files, as I think how I handle the loading is good.

At the moment, this is my ConfigLoader class:

<?php

namespace CodeRichard\SimpleConfig;

use CodeRichard\SimpleConfig\Exception\MissingDependencyException;
use CodeRichard\SimpleConfig\Exception\UnsupportedFileTypeException;
use CodeRichard\SimpleConfig\Reader\FileReader;

class ConfigLoader
{
    /**
     * @var string
     */
    private $file;

    /**
     * Initialize a new loader
     *
     * @param string $file The file to load
     */
    public function __construct($file)
    {
        $this->file = $file;
    }

    /**
     * Load the config
     *
     * @param string $file A config file, may be null
     *
     * @return array
     */
    public function loadConfig($file = null)
    {
        $file = $file !== null ? $file : $this->file;

        $reader = $this->getSuitableReader($file);

        try
        {
            $reader->checkDependencies();
        }

        catch(MissingDependencyException $e)
        {
            $message = 'An error occured while trying to load the reader: ' . $e->getMessage();
            trigger_error($message, E_USER_ERROR);
        }

        return $this->readConfig($reader, $file);
    }

    /**
     * Use the config reader to read the file
     *
     * @param \CodeRichard\SimpleConfig\Reader\FileReader $reader
     * @param string                                      $file
     *
     * @return array
     */
    private function readConfig(FileReader $reader, $file)
    {
        return $reader->read($file);
    }

    /**
     * Get the most suitable config reader
     *
     * @param string $file
     *
     * @return Reader\IConfigReader
     * @throws UnsupportedFileTypeException
     */
    private function getSuitableReader($file)
    {
        $ext = pathinfo($file, PATHINFO_EXTENSION);

        if(!ConfigLoaderRegistry::hasRegistered($ext))
        {
            throw new UnsupportedFileTypeException($ext);
        }

        return ConfigLoaderRegistry::getReader($ext);

    }
}

How can I improve this class in particular?

My project can be found here: https://github.com/CodeRichard/simple-config

Edit 14-04

So far, I have moved instantiating and checking if the config reader is supported to the ConfigLoaderRegistry class. Like so:

/**
 * Check whether or not the given file type has a reader registered to it
 *
 * @param string $fileExt The file extension to check on
 *
 * @return bool True if a reader is registered for that file type, false if not
 */
public static function hasRegistered($fileExt)
{
    $fileExt = strtolower($fileExt);
    return isset(self::$registry[$fileExt]);
}

/**
 * Get a reader by its file extension and return an instantiated reader
 *
 * @param string $fileExt The file extension to get the reader from
 *
 * @return FileReader
 */
public static function getReader($fileExt)
{
    $fileExt = strtolower($fileExt);

    $classPath = self::$registry[$fileExt];

    return self::instantiateReader($classPath);
}

/**
 * Instantiate a new reader by its class path
 *
 * @param string $classPath The class path to instantiate from
 *
 * @return FileReader A new instance of the given reader
 */
protected static function instantiateReader($classPath)
{
    $reflClass = new \ReflectionClass($classPath);

    return $reflClass->newInstanceWithoutConstructor();
}


texts:
I have used code which looks a little like this in an app I'm working on:

module App
  module Settings

    class << self
      attr_accessor :console, :file
    end

    self.console ||= true
    self.file    ||= []

  end
end

I decided to use this method because I like the interface, I had the idea after reading the Singleton examples from Design Patterns in Ruby.

I can then require 'app/settings' from any file in my app and read/write the settings

p App::Settings.console
App::Settings.file << "afile.rb"
p App::Settings.file

etc...

Is this a reasonable way to keep my settings in a single file? I feel I am unnecessarily repeating myself. Any ideas for DRYing?


texts: A helper class for creating icons from a PNG image and colour in Swift

texts:
I have made a helper struct in Swift that creates circular icons from a PNG image (a white icon on transparent background) and a background UIColor. These variables are user-definable in my app, and the created icons are used in notifications and Spotlight, for example.

The PNG images are named iconA.png, iconB.png etc. and are all a standard 100-points square. The default image is a fully transparent one called iconEmpty.png. I wanted to provide a CGSize argument so that I could use this method for other purposes as well, should the need arise.

It works as expected, but I am wondering how it might be improved or made more efficient, as I am not very experienced with drawing contexts.

import UIKit

struct IconMaker {

    func makeIcon(with color: UIColor, size: CGSize, icon: UIImage = UIImage(named: "iconEmpty.png")!) -> UIImage {

        // Make solid color background
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        color.setFill()
        UIRectFill(rect)
        let backgroundImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        // Add other image (which has transparency)
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        backgroundImage.draw(in: rect, blendMode: .normal, alpha: 1)

        icon.draw(in: rect, blendMode: .normal, alpha: 1)

        let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        // Circular mask
        let cornerRadius = newImage.size.height/2
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        let bounds = CGRect(origin: CGPoint.zero, size: size)
        UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip()
        newImage.draw(in: bounds)
        let finalImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return finalImage!
    }
}


texts: Date picker consisting of three component pickers

texts:
I made a UI picker tool, like a "rolling select" to pick vales (demo here).

I made first a independent module with a ES6 Class, basically:

class ComponentPicker {

    constructor(target, data){
        // init stuff
    }

  deployHTML(target, data) {...}
    getValue(){...}
    setValue(val){...}
    onChange(callback){...}
}

Then I added a new layer to it. A Date picker that needs 3 component pickers. I thought about extending the class ComponentPicker but I didn't find a way to call 3 times super, it would look like

class DatePicker extends ComponentPicker{
  constructor(length) {
      this.pickers = data.map(component=>{
            return super(target, component); // <-- weird and wrong

        });
  }

So I ended up doing a "good old" ES5- style of class like:

function DatePicker (target, data) {
    this.wrapper = document.createElement('div');
    this.wrapper.className = 'date-picker';
    target.appendChild(this.wrapper);
    this.pickers = data.map(component=>{
        return new ComponentPicker(target, component);
    });
    return this;
}
DatePicker.prototype.getValue = function(){
    return this.pickers.map(picker=>{
        return picker.getValue();
    });
}
DatePicker.prototype.setValue = function(values){
    // etc

and calling it with new DatePicker();

It works, but is there another way to reuse/extend the first class into another one that needs to interact with 3 of the original?


texts:
What I needed to do was check whether a given string matches a certain pattern. The pattern is this:

00:00:00,000 --> 00:00:00,000

Things to keep in mind:

The 0s can be numbers from 0 to 9.

The pattern must be alone in a single line; the line has to only consist of the pattern.

I came up with this:

"^(\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d) --> (\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d)"

I tested it a few times and strings that respect the pattern return true, the ones that don't, return false, as they should.

Here's a test case:

import java.util.regex.Pattern;

public class TestCaseRegex {

    public static void main(String[] args) {
        //will return true
        String testOne = "00:01:23,846 --> 00:01:26,212";

        //will return false, there's a letter where a number should be
        String testTwo = "00:01:23,84a --> 00:01:21,221";

        //will return true
        String testThree = "00:05:54,846 --> 00:01:16,450";

        //will return false. The string doesn't match the format.
        String testFour = "00:05:54,6 --> 00:0116,450";

        System.out.println(patternMatch(testOne));
        System.out.println(patternMatch(testTwo));
        System.out.println(patternMatch(testThree));
        System.out.println(patternMatch(testFour));
    }

    public static boolean patternMatch(String str) {
        Pattern p = Pattern.compile("^(\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d) "
                + "--> (\\d\\d):(\\d\\d):(\\d\\d),(\\d\\d\\d)");
        return p.matcher(str).matches();
    }

}

As I'm very new to regex, I'm wondering if this is the most efficient/correct way to accomplish this.


texts: Structure of website columns and navigation

texts:
I have made this HTML5 structure for a new website I am working on. I'd like to know if there is a more elegant approach to doing it.

Is the wrapper for the two column considered bad practice?
Should the secondary navigation on the left be an article or a div?

header

H1 title

Lorem ipsum dolor sit amen lorem ipsum dolor sit amen

- main navigation

- main navigation

- main navigation

button call to action

Title h2 secondary menu

navigation

navigation

navigation

Title h2 secondary menu

navigation

navigation

navigation

slideshow widget

review widget

product grid title

Text text text lorem ipsum dolor sit amen

product 1

product 2

product 3

<

product grid title

Text text text lorem ipsum dolor sit amen

product 1

product 2

product 3

/div>

footer


texts: Check digital input signals that is sent as an integer using bitwise checking

texts:
I have a program that works with a hardware via an ActiveX API. The API have events that is triggered by the hardware.
In the hardware there is an IO card. There is 16 in and 16 out. Changes in input signal triggers the event handler below.
The event uses an int to show which signal is set/unset. This by using binary addresses for each signal

Signal          Mask
INPUT_0         0x01;
INPUT_1         0x02;
INPUT_2         0x04;
INPUT_3         0x08;
...
INPUT_11        0x800

(there are some signals that are used for something else and can't be used as Input)

The signals can be set/unset in any order, but the event will trigger every time a change is done!
The value, p_nBits, will include all signals state. This means that if INPUT_0 is set and then INPUT_1 is set
then p_nBits will be 3, i.e. both signals! But INPUT_0 has already been handled and should not be handled again until it is unset.
I have an integer currentBits that is the current state of the input signals.

Any error in logic?
What can be improved?
Is it possible to make it faster?

// Current state of Input signals
int currentBits = 0;

public void IoPort_sigInputChange(int p_nBits)
{
    lock (lockObj)
    {

        if ((p_nBits & INPUT_0) == INPUT_0)
        {
            if ((currentBits & INPUT_0) != INPUT_0)
            {
                currentBits |= INPUT_0;
                RaiseRunModeEvent(true);
            }
        }
        else
        {
            if ((currentBits & INPUT_0) == INPUT_0)
            {
                currentBits &= ~INPUT_0;
                RaiseRunModeEvent(false);
            }
        }

        if ((p_nBits & INPUT_1) == INPUT_1)
        {
            if ((currentBits & INPUT_1) != INPUT_1)
            {
                currentBits |= INPUT_1;
                RaiseAllPositionsSetEvent(true);
            }
        }
        else
        {
            if ((currentBits & INPUT_1) == INPUT_1)
            {
                currentBits &= ~INPUT_1;
                RaiseAllPositionsSetEvent(false);
            }
        }

        if ((p_nBits & INPUT_2) == INPUT_2)
        {
            if ((currentBits & INPUT_2) != INPUT_2)
            {
                currentBits |= INPUT_2;
                RaiseOrderEndedEvent(true);
            }
        }
        else
        {
            if ((currentBits & INPUT_2) == INPUT_2)
            {
                currentBits &= ~INPUT_2;
                RaiseOrderEndedEvent(false);
            }
        }

        // more checks may occur
    }
}


texts: Custom Vector and Matrix classes in python for machine learning

texts:
I am creating a machine learning tool set from scratch in python. I have never done something of this kind and I don't usually use python but I thought it would be good to expand my horizons. I am really looking for aspects of the code that would really hinder performance and things to consider since this will be used for a neural network implementation.

class vector:
    def __init__(self, size):
            self.elems = [0] * size
            self.size = size
    def __repr__(self):
            return repr(self.elems)
    def __mul__(self, other):
            if(self.size != other.size):
                    raise ArithmeticError("vectors of two different lengths")
            a = 0
            for i in range(self.size):
                    a += self.elems[i] * other.elems[i]
            return a
    def set(self, array):
            for i in range(self.size):
                    self.elems[i] = array[i]
                    self.mag =  sum([i**2 for i in self.elems])**.5
    def normalize(self):
            a =  vector(self.size)
            a.set([i/self.mag for i in self.elems])
            return(a)

class matrix:
    def __init__(self, r, c):
            self.coloums = [vector(c) for i in range(r)]
            self.r = r
            self.c = c
    def __repr__(self):
            return repr(self.coloums)
    def __mul__(self, other):
            if(type(other) != vector):
                    raise TypeError("matrices can only be multiplied by vectors")
            if(self.c != other.size):
                    raise ArithmeticError("rows and lengths do not match")
            a = vector(self.r)
            a.set([(other*self.coloums[i]) for i in range(self.r)])
            return a
    def set(self, multiarray):
            for i in range(self.c):
                    self.coloums[i].set(multiarray[i])

I am aware this has no way of multiply by a scalar but I have no need for that just yet and it would be pretty trivial to implement.


texts:
This does the job, but is not especially elegant.

What is the preferred Pythonic idiom to my childish nests?

def bytexor(a, b):
    res = ""
    for x, y in zip(a, b):
        if (x == "1" and y == "0") or (y =="1" and x == "0"):
            res += "1"
        else:
            res += "0"

    return res

def get_all():
    res = []
    bit = ["0","1"]
    for i in bit:
        for j in bit:
            for k in bit:
                for l in bit:
                    res.append(i+j+k+l)
    return res

if __name__=="__main__":

    for k0 in get_all():
        for k1 in get_all():
            for k2 in get_all():
                for k3 in get_all():
                    for k4 in get_all():
                        if bytexor(bytexor(k0, k2), k3) == "0011":
                            if bytexor(bytexor(k0, k2), k4) == "1010":
                                if bytexor(bytexor(bytexor(k0,k1),k2),k3) == "0110":
                                    print k0, k1, k2, k3, k4
                                    print bytexor(bytexor(bytexor(k0, k1),k2),k4)


texts: Divide and conquer approach in search for max element, take 2

texts:
Adopted some suggestions from the answer of my previous post. Here is the code:

trait MaxElem<T> {
    fn max_elem<'a>(&'a self) -> &'a T;
}

impl<T> MaxElem<T> for [T] where T: Ord {
    fn max_elem<'a>(&'a self) -> &'a T {
        max_elem_helper(self, 0, self.len())
    }
}

fn max_elem_helper<'a, T>(array: &'a [T], left: usize, right: usize) -> &'a T
    where T: Ord
{
    if right - left == 1 {
        return &array[left];
    }
    let mid = (left + right) / 2;
    let max1 = max_elem_helper(array, left, mid);
    let max2 = max_elem_helper(array, mid, right);
    if max1 > max2 {
        max1
    } else {
        max2
    }
}

#[cfg(test)]
mod test {
    use max_elem::MaxElem;
    #[test]
    fn test_max_elem() {
        let array = [11, 2, 9, 1, 3, 88];
        let m = array.max_elem();
        assert_eq!(*m, 88);
    }
}

All suggestions are welcome.


texts: Replacing the occurence of the character in string

texts:
Given a string (for example: "a?bc?def?g"), write a program to
  generate all the possible strings by replacing ? with 0 and 1.

Example:
Input : a?b?c?
Output: a0b0c0, a0b0c1, a0b1c0, a0b1c1, a1b0c0, a1b0c1, a1b1c0, a1b1c1.

I have developed a program as shown below but please advise if something more efficiently can be done.

public class ReplaceQuestionMark {
    public ArrayList<String> replace(String target){
        return replaceHelper(target, target.length()-1);
    }

    public ArrayList<String> replaceHelper(String target, int to){
        char c = target.charAt(to);
        if (to == 0){
            ArrayList<String> res = new ArrayList<String>();
            if (c == '?'){
                res.add("0");
                res.add("1");
            }
            else{
                res.add(c+"");
            }
            return res;
        }
        ArrayList<String> res = new ArrayList<String>();
        ArrayList<String> preRes = replaceHelper(target, to-1);
        if (c == '?'){
            for (String token: preRes){
                res.add(token + "0");
                res.add(token + "1");
            }
        }
        else{
            for (String token: preRes){
                res.add(token + c);
            }
        }
        return res;
    }

    public static void main(String[] args){
        ReplaceQuestionMark rqm = new ReplaceQuestionMark();
        ArrayList<String> res = rqm.replace("a?b?c?");
        for (String s: res){
            System.out.println(s);
        }
    }
}


texts:
There is a 1-to-many relationship between the posts table and the votes table, and they join on posts.id = votes.postid. I would like to know how many posts have 1, 2, 3, 5, etc. votes.

Thanks to Waffles' most controversial posts query, it was trivial to write this:

declare @VoteStats table (PostId int, up int)

set nocount on

insert @VoteStats
select
    PostId,
    up = sum(case when VoteTypeId = 2 then 1 else 0 end)
from Votes
where VoteTypeId in (2,3)
group by PostId

set nocount off

select up, count(*)
from @VoteStats
group by up;

However, it runs in a full 22 seconds on the Stack Overflow data dump.

Am I overlooking an obvious way to speed this query up, perhaps avoiding the creation of  the VoteStats table?


texts: Simple C# console application to read from csv and query DB

texts:
I wrote a simple console application that reads contents from a CSV file, and using that input, checks a database table to see if the contents are within it. If there is a match, then the program will output the name of the file that the input is included in to a text file.

I feel like I should break this application up into more compartmentalized functions, such as separating the DB connection from DB read.

Any input for this greatly appreciated!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.IO;
using Microsoft.VisualBasic.FileIO;

namespace MLMSpellingReader
{
    class SpellingReader
    {
        static void Main(string[] args)
        {
            SpellingReader.readCSV();
            MessageBox.Show("Evaluation is complete, press OK to continue");
        }

        public static void readCSV(){

            string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string outputFile = filePath + @"\outputFile.txt";
            string queryString = null;
            using (TextFieldParser parser = new TextFieldParser(@"c:\users\myuser\Documents\spellcheck.csv"))
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                while(!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();
                    foreach(string field in fields)
                    {
                        string eval = field;
                        queryString = "select Name from myTable where Logic like '%" + eval + "%' and active = '1'";
                        SpellingReader.connectToDB(outputFile, queryString, eval);
                    }
                }
            }
        }

        public static void connectToDB(string outputFile, string queryString, string eval)
        {
            string connectionString = "Server=myServer;Database=myDBTable;Integrated Security=True;";
            string checkSpellingQuery = queryString;
            SqlConnection conn;
            conn = new SqlConnection(connectionString);
            try
            {
                SqlCommand command = new SqlCommand(checkSpellingQuery, conn);
                conn.Open();
                SqlDataReader reader = command.ExecuteReader();
                using(StreamWriter file = new StreamWriter(outputFile, true))
                {
                    while(reader.Read())
                    {
                        file.WriteLine("The misspelling " + eval + " was found in: " + reader["Name"]);
                    }
                }
                reader.Close();
                conn.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Cannot open connection: " + ex.ToString());
            }
        }

    }
}


texts: Taking objects from literal with many objects

texts:
I have data returned from an API coming back in a response: response.data

[
    {"amount":"45342",
    "comment":"random text",
    "currency":"USD"},
    {"city":"LA",
    "amount":"54366",
    "lane_id":{"$oid":"5645999965a5b0"}}
]

I need to take only the amount and create a new set of objects like this:
[{amount: "45342"}, {amount: "54366"}]

The obvious way would be to push it through a loop like so:

var newArray = [];
var newObject;
var i, len;
for (len = response.data.length, i=0; i<len; ++i){
  newObject = response.data[i];
  newArray.push({amount: newObject.amount});
};

Is there a better way? I am running on angular 1.5 and jquery


texts: Prime numbers that are also a prime number when reversed

texts:
This is a challenge on Codewars I took years ago. Task is to find all prime numbers that are also a prime number when reversed, i.e. 13 -> 31 is such a number.
This is still the answer with the most upvotes in the categories 'Best practice' as well as in 'Clever'.
Any improvements or thoughts about this piece of code? Please keep in mind in code challenges like this I always try to code as concise as possible.
Examples in => output :
    backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97]
    backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967]
    backwardsPrime(501, 599) => []

code:
public class BackWardsPrime {

    public static String backwardsPrime(long start, long end) {
        StringBuilder sb = new StringBuilder();
        while(start <= end){
            long rev = Long.parseLong(new StringBuilder(
            String.valueOf(start)).reverse().toString());
            if(start > 12 && isPrime(rev) && isPrime(start) && start != rev)
                sb.append(start + " ");
            start++;
        }
        return sb.toString().trim();
    }

    static boolean isPrime(long n) {
        if(n % 2 == 0) return false;
        for(int i = 3; i * i  <= n  ; i += 2) {
            if(n % i == 0)
                return false;
        }
        return true;
    }
}


texts: Codeigniter 3 - Set Flashdata Array issue

texts:
I need help about CodeIgniter $this->session->set_flashdata array.

I think my code is so long, is there any way to simplify my code?

Script at my views

<?php
for($i=0; $i<$max; $i++) {
   if($this->session->flashdata("'warning".$i."'"))
      echo $this->session->flashdata("'warning".$i."'");
   if($this->session->flashdata("'info".$i."'"))
      echo $this->session->flashdata("'info".$i."'");
}
?>
<form action="xxxx/insertMember" method="post">
   <?php for($i=0; $i<$max; $i++) { ?>
      <label>Username <?php echo $i; ?></label>
      <input type="text" placeholder="username" name="username[<?php echo $i; ?>]>
   <?php } ?>
   <button type="submit">Submit</button>
</form>

Script at my controller

...
parent::__construct();
$max = 5;

public function insertMember() {
....form was validated & return true...
   $name = $this->input->post('username',TRUE);
   $a = 1;
   $b = 1;
   for($i=0; $i<$max; $i++) {
      if($name[$i] != '') {
         //check username was registered on database or not.
         $doCheck[$i] = $this->model->check($name[$i]);

         //if already registered
         if(!empty($doCheck[$i])) {
            $this->session->set_flashdata("'warning".$a."'",$name[$i].' was registered');
            $a++;
         }

         //if not registered
         else {
            $this->model->insert($name[$i]);
            $this->session->set_flashdata("'warning".$b."'",$name[$i].' sucessfully registered');
            $b++;
         }

         redirect('registerpage');
}


texts: Turning a byte array into a C# object whose type is unknown at compile time

texts:
I'm trying to turn an array of bytes into a C# object. I only the know the type of the object at runtime.

Right now, I'm using the JsonConvert.DeserializeObject<T> to do this, but the result is clunky, mostly because I don't know T at compile time.

If I knew T at compile time, I could simply do:

string json = System.Text.Encoding.UTF8.GetString(buffer);
return JsonConvert.DeserializeObject<MyType>(json);

But since I don't, I must do:

string json = System.Text.Encoding.UTF8.GetString(buffer);
var deserializeInfoMethodInfo = typeof(JsonConvert).GetMethods().Where(method => method.Name == "DeserializeObject" && method.IsGenericMethod).First();
return deserializeInfoMethodInfo.MakeGenericMethod(paramInfo.ParameterType).Invoke(null, new object[] { json });

Is there a way to make this simpler?

I have experimented with something like this:

using (MemoryStream stream = new MemoryStream(buffer, bufferIndex, paramLengths[i])) {
    using (JsonTextReader jsonReader = new JsonTextReader(new StreamReader(stream))) {
        var serializer = new JsonSerializer();
        return serializer.Deserialize(jsonReader, paramInfo.ParameterType);
    }
}

This is arguably more readable, but I don't like how I have to get the buffer (which I got from calling stream.Read(buffer, 0, length) in another place), turn it back into a stream, and then have the serializer iterate through the stream again.

Is there a way to trim down the second snippet, or should I stop whining and use the third?


texts:
I've been writing my code like this for a really long time now, I am wondering if there is a more efficient way to do this. This is especially after a senior developer said my code was very amateurish.

App Purpose: I need to set some data for new employees when they join our organisation. This is a simple command app written in .net that takes an argument, splits it and then assigns the variables. A command might look like this:

Setdata.exe -Marcus -true -true -false -false.

The output is a file that we install on one of our sql servers.

The example below is a small one, but it is not common for the settings to hit 40-50 lines.

Code:

  internal static void ExportSolution(SqlService service, string parms)
    {
        try
        {
            parms = parms.Replace(" ", "");
            string[] args = parms.Split('-');

            string solutionName = args[1];
            bool managed = Convert.ToBoolean(args[2]);
            bool prefix= Convert.ToBoolean(args[3]);
            bool profile= Convert.ToBoolean(args[4]);
            bool email= Convert.ToBoolean(args[5]);
            bool calendar= Convert.ToBoolean(args[6]);
            bool appSettings= Convert.ToBoolean(args[7]);

            AppSettingsRequestAppSettingsRequest= new AppSettingsRequest();

            AppSettingsRequest.SolutionName = solutionName;

            AppSettingsRequest.Managed = (managed == true) ? true : false;

            AppSettingsRequest.prefix= (prefix== true) ? true : false;

            AppSettingsRequest.Managed profile= (profile== true) ? true : false;

            AppSettingsRequest.email= (email== true) ? true : false;

            AppSettingsRequest.calendar= (calendar== true) ? true : false;

            AppSettingsRequest.appSettings= (appSettings== true) ? true : false;

            byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
            string filename = solutionName + ".zip";
            File.WriteAllBytes(filename, exportXml);

            Console.WriteLine("Solution exported to {0}.", filename);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

Initial thoughts are that I could create a new class and then instantiate a new object with these variables, but is there anything to gain from doing this?


texts: Matching a pattern in many lines of text

texts:
This is the relevant piece of my code (false is returned if the whole cycle is finished, pattern is a String passed to the function):

for (FileLine fileLine : fileLines) {
    itemText = fileLine.getText();

    itemStrings = new ArrayList<String>();
    itemStrings.addAll(Arrays.asList((itemText).split(" ")));
    for (String itemString : itemStrings) {
        if (itemString.equalsIgnoreCase(pattern)) {
            return true;
        }
    }
}

How can I speed this up? I've tried using regex, something like:

//before the for cycle
Pattern regexPattern = Pattern.compile(pattern);

//in the cycle
if (regexPattern.matcher(itemText).matches())
    return true;

But it doesn't work for some reason. Maybe I'm doing it wrong, or there's a completely different way of accomplishing this?


texts:
I'm learning to use MVC in my JavaScript apps and I thought it might be good practice to write my own MVC implementation. I'd like to know if you see any ways I could improve it or any potential issues I could run into using it.

class Model {

  constructor() {
    this.listenerStorage = {};
  }

  trigger(event) {
    if (this.listenerStorage[event]) {
      this.listenerStorage[event].forEach((callback) => {
        callback();
      });
    }
  }

  on(event, callback) {
    this.listenerStorage[event] = this.listenerStorage[event] || [];
    this.listenerStorage[event].push(callback);
  }

  set(propObj, value) {
    if (value) { // propObj is just a string
      this[propObj] = value;
      this.trigger("change:" + propObj);
    } else { // propObj is an object with multiple values to change
      for (var prop in propObj) {
        this[prop] = propObj[prop];
        this.trigger("change:" + prop);
      }
    }

    this.trigger("all");
  }

}

class User extends Model {

  constructor(firstName, lastName, age) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

}

class Controller {

  constructor(user) {
    this.user = user;
    this.initializeListeners();
  }

  initializeListeners() {
    document.getElementById("submit").addEventListener("click", (event) => {
      event.preventDefault();
      this.updateUser();
      return false;
    });
  }

  updateUser() {
    let firstNameInput = document.getElementById("firstNameInput");
    let lastNameInput = document.getElementById("lastNameInput");
    let ageInput = document.getElementById("ageInput");

    const newFirstName = firstNameInput.value;
    const newLastName = lastNameInput.value;
    const newAge = ageInput.value;

    this.user.set({
      "firstName": newFirstName,
      "lastName": newLastName,
      "age": newAge
    });
  }
}

class View {

  constructor(user) {
    this.user = user;
    this.initializeListeners();
    this.updateInputs();
    this.displayGreeting();
  }

  initializeListeners() {
    this.user.on("all", () => {
      this.displayGreeting();
    });
  }

  displayGreeting() {
    let greeting = `<p>Hello ${this.user.firstName} ${this.user.lastName}! You're ${this.user.age} years old.</p>`;
    let greetingElem = document.createElement("p");
    greetingElem.innerHTML = greeting;

    let greetingWrapper = document.getElementById("greeting");
    greetingWrapper.innerHTML = null;
    greetingWrapper.appendChild(greetingElem);
  }

  updateInputs(user) {
    document.getElementById("firstNameInput").value = this.user.firstName;
    document.getElementById("lastNameInput").value = this.user.lastName;
    document.getElementById("ageInput").value = this.user.age;
  }

}

document.addEventListener("DOMContentLoaded", () => {
  let user = new User("Joe", "Bob", 21);
  let view = new View(user);
  let controller = new Controller(user);
});
input,
label,
button,
p {
  float: left;
  clear: left;
  margin: 5px;
}
<form>

User

  First Name:
  <input type="text" id="firstNameInput" name="firstName">

  Last Name:
  <input type="text" id="lastNameInput" name="lastName">

  Age:
  <input type="text" id="ageInput" name="age">

  <button id="submit">Submit</button>
</form>


texts: Reading content of directory for each HTTP request

texts:
I have a piece of code written in node and I wanted to know if I am in the right direction. Basically I have a site where the homepage lists 6 vehicle cards. Every time the page is requested I do the following:

Take 16 vehicles off neo4j (skip x amount if not first page)
For each of the 16th vehicle objects, check if there exist a directory, if yes then read its content (i.e. vehicle images, max 5 per directory)
Return jade template with all data to client

Initially I was using fs.readdirSync and I have just updated the code to use fs.readdir async version.

My worry is how would the following piece of code that read directory and lists its images including finding out its dimension perform in real life for hundreds of concurrent requests?

vehicles.forEach(function(vehicle) {
  var images = [];
  fs.readdir(__dirname + '/photos/' + v.vehicle_id, function(err, files) {
    if(err && err.code == 'ENOENT') {
      logger.info('No images found for vehicle.');
      modifiedVehicles.push(v);
    } else {
      files.forEach(function(file) {
        if(file.indexOf("thumbnail") != 0) {
          var dimension = sizeOf(__dirname + '/photos/' + v.vehicle_id +'/' + file);
          var temp = {
            filename: file,
            width: dimension.width,
            height: dimension.height
          };
          images.push(temp);
        }
      });
      v.images = images;
      modifiedVehicles.push(v);
    }
  });
});
callback(modifiedVehicles);

As a single request to a page of 16 vehicle cards with only 8 of those 16 vehicles having at least 1 image the time it took is:

benchmark took 5135013 nanoseconds (5.1 milliseconds)

Assuming that I host with VM that runs SSD, is the above the right solution? I am thinking of the following options:

Method 1

I could return the response to the user request without list of images but, then as soon as the page is loaded I send a subsequent req to retrieve list of images for all vehicles

Method 2

Retrieve list of images only when the vehicle card is viewed. Ajax request.

Method 3

When the app is started, for each of most recent vehicle (latest 500) read its images and insert them as key (vehicle_id) and value (array of images) to Redis and then retrieve values from Redis for each http request. Not sure how much of a difference Redis instead of Disk I/O can be.

Method 4

Store filename of of vehicles images in mongodb when the vehicle is created/updated. For each http request query mongodb for all images with vehicle ids IN (...)

Any other method that you think I should consider? please share.


texts: Using a single validation handler for all controllers in a form

texts:
In input validation I'm using this validation method in my all Forms. Here I have a single handler for all TextBoxes in my Form and if I have other controllers like ComboBoxes I would use a separate handler for all ComboBoxes and so on.

My only doubt in this approach is how users would feel about this as you can't focus on other text boxes while keeping the current one empty if it's not an optional field!

Could you please review this and provide your feedback?

public partial class frmForm : Form
    {
    public frmForm()
            {
                InitializeComponent();

                foreach (TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
                {
                    tb.Validating += textBox_Validating;
                }
            }

            private void textBox_Validating(object sender, CancelEventArgs e)
            {
                TextBox currenttb = (TextBox)sender;
                if (currenttb.Name != OptionalFields .txtPolicy.ToString())
                {
                    if (string.IsNullOrWhiteSpace(currenttb.Text))
                    {
                        MessageBox.Show(string.Format("Empty field {0 }", currenttb.Name.Substring(3)));
                        e.Cancel = true;
                    }

                    else
                    {
                        e.Cancel = false;
                    }
                }

            }

            private enum OptionalFields
            {
                txtPolicy, txtRemarks
            }
    }