texts:
Link to the Problem
Here is my code to compute the length of the longest common subsequence of two integer arrays arr[] and brr[]:

#include <bits/stdc++.h>
using namespace std;
//Dynamic programm solution
int mem[10004][10004];//mem[i][j] stores length of the longest common subsequence, up to index i of arr and index j of brr
vector<int> arr,brr;
int lcs(int i,int j){
    if (i<0||j<0) return 0;
    if (mem[i][j]!=-1) return mem[i][j];// if already computed, return mem[i][j]
    else {
        int tmp = 0;
        tmp = max(lcs(i-1,j),lcs(i,j-1));
        if (arr[i]==brr[j]) tmp = max(tmp,lcs(i-1,j-1)+1);
        mem[i][j] = tmp;
    }
    return mem[i][j];
}
main(){
    int n,m;// n,m are the length of the first and second array
    memset(mem,-1,sizeof(mem));
    cin >> n >> m;
    arr.resize(n+1);brr.resize(m+1);
    for (int i = 0;i<n;++i){
        cin >> arr[i];
    }
    for (int i = 0;i<m;++i){
        cin >> brr[i];
    }
    //calculate length of longest common subsequence of two array arr and brr
    cout << lcs(n-1,m-1);
}

The time complexity of the above approach is O(m*n). The running time of the program exceeds 1000ms when m and n are both as large as 10000. How can I improve the above program's speed to solve this problem in the case m = n = 10000 under 1000ms ? (I was trying to solve this problem in Codeforces, and there's a test case where m = n = 10000 and my program failed to solve it under 1000ms)


texts: Density-based clustering of image keypoints

texts:
I have implemented the DBSCAN algorithm for clustering image keypoints.  I have been following the pseudocode on the wiki page pretty strictly, and it's working, but I get the feeling its a very naive implementation and could be improved in terms of performance.  I was hoping you could offer me some feedback on how to improve it.

/* DBSCAN - density-based spatial clustering of applications with noise */

vector<vector<KeyPoint>> DBSCAN_keypoints(vector<KeyPoint> *keypoints, float eps, int minPts)
{
vector<vector<KeyPoint>> clusters;
vector<bool> clustered;
vector<int> noise;
vector<bool> visited;
vector<int> neighborPts;
vector<int> neighborPts_;
int c;

int noKeys = keypoints->size();

//init clustered and visited
for(int k = 0; k < noKeys; k++)
{
    clustered.push_back(false);
    visited.push_back(false);
}

//C =0;
c = 0;
clusters.push_back(vector<KeyPoint>()); //will stay empty?

//for each unvisted point P in dataset keypoints
for(int i = 0; i < noKeys; i++)
{
    if(!visited[i])
    {
        //Mark P as visited
        visited[i] = true;
        neighborPts = regionQuery(keypoints,&keypoints->at(i),eps);
        if(neighborPts.size() < minPts)
            //Mark P as Noise
            noise.push_back(i);
        else
        {
            clusters.push_back(vector<KeyPoint>());
            c++;
            //expand cluster
            // add P to cluster c
            clusters[c].push_back(keypoints->at(i));
            //for each point P' in neighborPts
            for(int j = 0; j < neighborPts.size(); j++)
            {
                //if P' is not visited
                if(!visited[neighborPts[j]])
                {
                    //Mark P' as visited
                    visited[neighborPts[j]] = true;
                    neighborPts_ = regionQuery(keypoints,&keypoints->at(neighborPts[j]),eps);
                    if(neighborPts_.size() >= minPts)
                    {
                        neighborPts.insert(neighborPts.end(),neighborPts_.begin(),neighborPts_.end());
                    }
                }
                // if P' is not yet a member of any cluster
                // add P' to cluster c
                if(!clustered[neighborPts[j]])
                    clusters[c].push_back(keypoints->at(neighborPts[j]));
            }
        }

    }
}
return clusters;
}

vector<int> regionQuery(vector<KeyPoint> *keypoints, KeyPoint *keypoint, float eps)
{
float dist;
vector<int> retKeys;
for(int i = 0; i< keypoints->size(); i++)
{
    dist = sqrt(pow((keypoint->pt.x - keypoints->at(i).pt.x),2)+pow((keypoint->pt.y - keypoints->at(i).pt.y),2));
    if(dist <= eps && dist != 0.0f)
    {
        retKeys.push_back(i);
    }
}
return retKeys;
}


texts: Getting device's location once in Android

texts:
In my Android app I need to get device's location once after user clicks a button. I don't really need to keep updating localization after I get the location coordinates.

I created a class which uses Location Manager in order to get the localization, whole code is part of an AsyncTask. At the application Activity I'm just doing an anonymous instantiating and invoking execute method.

This is what my class looks like:

public class SourcesOnLocationServices extends AsyncTask<Location, Integer, JSONArray> {

    private HttpURLConnection urlConnection;

    @Override
    protected JSONArray doInBackground(Location... params) {

        Location currentLocation = params[0];

        double latitude = currentLocation.getLatitude();
        double longitude = currentLocation.getLongitude();

        try {
            final URL requestUrl = new URL( "http://location.beagleafgano.com/places/near?lat=" +
                                            String.valueOf(latitude) + "&long=" +
                                            String.valueOf(longitude) +
                                            "&maxDistance=700");

            urlConnection = (HttpURLConnection) requestUrl.openConnection();
            urlConnection.setRequestMethod("GET");

            urlConnection.connect();

            if (urlConnection.getResponseCode() != 200) {
                Log.e("AsyncTask", "Request failed");
                return null;
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((urlConnection.getInputStream())));
            StringBuilder sb = new StringBuilder();
            String output;
            while ((output = br.readLine()) != null) sb.append(output);

            return new JSONArray(sb.toString());

        } catch (MalformedURLException e) {
            return null;
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            Log.e("JSON",e.toString());
            return null;
        }

        return null;
    }

    @Override
    protected void onPostExecute(JSONArray json) {
        System.out.println(json.toString());
    }
}

So, I'm using it just by new SourcesOnLocationServices().execute(this) from Activity.

I wonder and care for:

Is this really getting actual location?
Is this really finishing after onPostExecute?
What if I wanted to keep updating for a few secs later?
I'm not implementing LocationListener ... so?


texts:
This is part of the project I started just now. It is a function that returns the offset address of a first occurrence of a string match into a given range of memory blocks.

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

typedef struct
{
    unsigned long offset;
    unsigned long terminal;
} Range;

unsigned long memgr_locate (char string[], Range iRange)
{
    unsigned char * ptr = (char*)iRange.offset;
    unsigned long i;
    unsigned long c = 0;

    for(i = iRange.offset; i <= iRange.terminal; i += 1)
    {
        ptr = (char*)i;

        (*ptr == string[c]) ? (c++) : (c=0);
        if(string[c + strlen(string) - 1] == '\0')
            break;
    }
    return i;
}

int main(void)
{
    char * test = malloc(100);
    strcpy(test, "Looking for Sample string directly in memory..");

    Range iRange = {test, test + 50};

    printf("%s", (char*)memgr_locate("Sample", iRange));

    return 0;
}

Test result:

  Sample string directly in memory..

Note that the string searcher function is constructed like so to return the closest result.

Example:

If we look for the string "s" it will return the offset byte of the first word from the memory range that starts with "s". If we look for "str" it will return the first word starting with "str". This behavior IS intended.


texts: Schema.org combining different categories

texts:
This is the follow up version of a previous question on combining different categories and their properties.

The home page contains the overarching company information.
The product page contains product information and links to the home page.

I do not get any error messages in Google testing tool. But I feel that the code is clunky. I am concerned that a lot of the information is hidden and that search prefer to index information that is also visible to the user.

Home page

Organization
<meta itemprop="name" content="Organizaton name" />

short description on home page

Product page

<link itemprop="url" href="http://www.sub-company-url/">
<meta itemprop="name" content="Sub-company name" />

NAME OF PRODUCT
The cost of

NAME OF PRODUCT
<meta itemprop="priceCurrency" content="EUR">€600


texts:
This program detects whether an expression is balanced or not. I would like to know how I can make this more efficient.

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

struct Stack{
char data;
struct Stack *next;
};

void push(struct Stack **top,char data)
{
        struct Stack *new_node;
        new_node=malloc(sizeof(struct Stack));
        new_node->data=data;
        new_node->next=*top;
        *top=new_node;
}
int compare(char str,char op)
{
        if( (op == '(' && str == ')') || (op == '{' && str == '}') || (op == '[' && str == ']') || (op == '<' && str == '>') )
                return 1;
        else
                return 0;
}
int pop(struct Stack **top,char str)
{
        char op,ret;
        struct Stack *temp=*top;
        if(*top==NULL)
                return 0;

        else if(*top!=NULL)
        {
                // Pop the element and then call comapre function
                op=(*top)->data;
                free(temp);
                *top=(*top)->next;
                return(ret=compare(str,op));
        }
return 1;
}
void display(struct Stack *top)
{
        struct Stack *temp=top;
        while(temp!=NULL)
        {
                printf("%c ",temp->data);
                temp=temp->next;
        }
printf("\n");
}
int isNotEmpty(struct Stack *top)
{

        if(top!=NULL)
                return 1;
        else
                return 0;
}
int main(void)
{
        struct Stack *top=NULL;
        int i=0,y,flag=0;
        char str[]="((A+B)+(C+D)>";
        printf("\n Running the programe to check if the string is balanced or not ");
        for(i=0;str[i]!='\0';++i)
        {
                if( str[i] == '(' || str[i] == '[' || str[i] == '{' || str[i] == '<' )
                        push(&top,str[i]);
                else if( str[i] == ')' || str[i] == ']' || str[i] == '}' || str[i] == '>')
                {
                        y=pop(&top,str[i]);
                        if(!y)
                        {
                                printf("\n Unbalanced Expression ");
                                flag=1;
                        }
                }
        }
        if(!flag)
        {
                if(isNotEmpty(top))
                        printf(" \nUnbalanced Expression ");
                else
                        printf(" \n Balanced Expression ");
        }
        printf("\n");
        return 0;
}


texts: Reorder objects based on provided enumerable order

texts:
This code feels like it goes through too many conversions to accomplish my goal:

  based on an IEnumerable of ids get those objects from a data store and
  set their DisplayOrder property to the position of the associated
  id.

Is there a more elegant solution that I'm missing?

public void ReorderElements(IEnumerable<int> elementSks)
{
    var elementsToReorder = GetSession().QueryOver<DocumentElement>()
        .WhereRestrictionOn(de => de.DocumentElementSk).IsIn(elementSks.ToArray()).List();

    var elementOrder = elementSks.Select((sk, i) => new { Sk = sk, Order = i })
        .ToDictionary(p => p.Sk, p => p.Order);

    elementsToReorder.ToList()
        .ForEach(e => e.DisplayOrder = elementOrder[e.DocumentElementSk]);

    this.Save(elementsToReorder);
}


texts:
I looked at a search filter code code and edited it to catered to my functional needs. I understood most of the JavaScript except the extend method bit. Can someone explain that?  Also, is this the best way to create such a filter?  Please let me know of any ways to improve the code.

    <input type="text" id="search-text" placeholder="search">

red

orange

yellow

pink

blue

green

violet

purple

Indigo

grey

white

black

  No items to show..


texts:
So this question might be a bit opinion based but I am a bit confused, say i have these two code snippets -

if (eventArgs != null && eventArgs is OnZoomEventArgs)
        {
            var zoomEventArgs = eventArgs as OnZoomEventArgs;
            if (zoomEventArgs.focus != null)
            {
                var line = zoomEventArgs.focus.GetComponent<AssemblyLine>();
                if (line != null)
                {
                    SetLine(line);
                } else
                {
                    ResetLine();
                }
            }
            else
            {
                ResetLine();
            }
        }
        else
        {
            ResetLine();
        }

and

var zoomEventArgs_ = eventArgs as OnZoomEventArgs;
        if(zoomEventArgs_.focus != null)
        {
            SetLine(zoomEventArgs_.focus.GetComponent<AssemblyLine>());
        } else
        {
            ResetLine();
        }

Which one is better in the sense of readability and in terms of performance maybe.
My question is should I instead check for null reference this many times or should I instead try to not pass a null reference. Is there any other way I can make these code snippets more readable.
I tried to replace

if (line != null)
                {
                    SetLine(line);
                } else
                {
                    ResetLine();
                }

with ternaries but I cannot as both SetLine() and ResetLine() have void as return type.


texts: Performance Improvement for Subtree for another tree

texts:
I was doing this algo on leetcode: https://leetcode.com/problems/subtree-of-another-tree/

Question:
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

For which I wrote this solution

var isSubtree = function(s, t) {
    const reduceMainTreeToString = JSON.stringify(s)
    const reduceGivenTreeToString = JSON.stringify(t)
    if (reduceMainTreeToString.includes(reduceGivenTreeToString)) return true
    else return false
};

I was super confident that it should be good performance and memory wise but unfortunately, I wasn't even able to cross 50% mark (though I was able to have 100% more memory efficient code).

This is how input s looks like

TreeNode {
  val: 3,
  right: TreeNode { val: 5, right: null, left: null },
  left:
   TreeNode {
     val: 4,
     right: TreeNode { val: 2, right: null, left: null },
     left: TreeNode { val: 1, right: null, left: null } } }

And this is how input t looks like

TreeNode {
  val: 4,
  right: TreeNode { val: 2, right: null, left: null },
  left: TreeNode { val: 1, right: null, left: null } }

This is the constructor:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

Can someone please suggest to me how I can improve the above code?


texts: Hibernate - entity design with multiple dependencies

texts:
I am currently working on an API and came across the following design.

    // not mandatory
    @ManyToOne
    @JoinColumn(name = "person_id")
    private Person person;

Actually, a telephone number should belong to a company, person or a contact form. However, this is logically not possible with the current design. So there is a small validation at the service level to make sure that there is always at least one dependency.

Now I was wondering if there is a better way to solve this. Because theoretically something can always go wrong and dependencies can be lost and the data would still be valid according to today's status.

I thought about creating a separate phone number object for each entity that inherits from the phone number. But somehow I don't really like the solution, but I think it's better than the previous one. What I don't like so much is that a lot more objects are created which also contain inheritance.

Is the new approach ok or how do you solve such problems?


texts: Python: pass "mutable integer" in recursion

texts:
I'm working on some code to find the max depth/height in a tree. I came up with a recursive solution, and I find myself needing to pass an integer "by reference". Currently, I'm using a mutable container to achieve this, but is there a more Pythonic way?

class Node:
"""
Node in a tree, with children stored in a list.
"""
   def __init__(self, keyParam, childrenParam = None):
    self.key = keyParam #some id of the node; not strictly required, but often needed.

       if childrenParam is None:
           self.children = []
       else:
           self.children = childrenParam

def dfsWithDepth(node, currentDepth, currentMaxContainer):
    currentDepth += 1
    if currentDepth > currentMaxContainer[0]:
        currentMaxContainer[0] = currentDepth

    for child in node.children:
        if child is not None:
            dfsWithDepth(child, currentDepth, currentMaxContainer)

# %% Construct tree
rootNode = Node('n1')
rootNode.children = [Node('n2'), Node('n3')]
tempNode = rootNode.children[0]  # n2
tempNode.children = [Node('n3'), Node('n4')]
tempNode = tempNode.children[1]  # n4
tempNode.children = [None, Node('n5')]

currentMaxContainer = [0]
dfsWithDepth(rootNode, 0, currentMaxContainer)

print(currentMaxContainer)


texts:
I wanted to know if there was any way to improve on this solution. I believe it uses the least amount of variables. Also wanted to know how are my variable names? Are they sufficient? Do I need anymore indenting? I'm looking for perfection in a way. At least a clear, correct and readable program.

/*
 * File: FindTwoLargest.java
 * ----------------------
 * This program finds the two largest integers in a list.
 *
 */

/* Library packages */
import acm.program.*;

public class FindTwoLargest extends ConsoleProgram {
    public void run() {
        println("This program finds the two largest integers in a list.");
        println("Enter values, one per line, using a 0 to signal the end of list.");
        int n = readInt("? ");
        int largest = n;
        int secLargest = n;
        while (true) {
            n = readInt("? ");
            if (n == SENTINEL) break;
            secLargest = n;
            while (true) {
                n = readInt("? ");
                if (n == SENTINEL) break;
                if (n > largest) {
                    secLargest = largest;
                    largest = n;
                } else if (n < largest && n > secLargest) {
                    secLargest = n;
                }
            }
            break;
        }
        println("The largest value is " + largest);
        println("The second largest value is " + secLargest);
    }

    /* Private constant */
    private static final int SENTINEL = 0;
}


texts: Handling SMS replies to register/unregister phone numbers

texts:
I'm working on a Django Twilio app, and I believe it's coming along well. I just want to improve my code writing skills. How can I improve the below code?

def save_number(request):
    from_number = request.POST.get('From', '')
    try:
        obj = SaveNumber.objects.get(phone_number=from_number)
        if obj == obj:
            subscribe = request.POST.get('Body', )
            if subscribe.lower().strip() == "stellar":
                enter = SaveNumber.objects.get(phone_number=from_number)
                enter.subscribed = True
                enter.save()
                r = twiml.Response()
                r.message("You're in. Always text outtahere, and we'll remove you.")
                return r
            elif subscribe.lower().strip() == "outtahere":
                remove = SaveNumber.objects.get(phone_number=from_number)
                remove.subscribed = False
                remove.save()
    except SaveNumber.DoesNotExist:
        obj = SaveNumber(phone_number=from_number)
        obj.save()
        r1 = twiml.Response()
        r1.message("Reply with stellar and you're in! :-)")
        return r1


texts:
So I have this array:

$arr = ('a' => 343, 'b' => 34, 'c' => 65, 'd' => 465);

which could also be

$arr = ('a' => 343, 'b' => 34, 'c' => 65);

Can the following code be improved into one line?

if(isset($arr['d'])) $something = $arr['d'];
unset($arr['d']);


texts:
(See the next iteration.)

I have this template function for computing standard deviation in one pass over the data. The underlying math is here.

coderodde_sd.h:

#ifndef CODERODDE_SD_H
#define CODERODDE_SD_H

#include <cmath>
#include <iterator>
#include <sstream>
#include <stdexcept>

namespace net {

    namespace coderodde {

        namespace stat {

            template<class Iter>
            double sd(Iter begin, Iter end)
            {
                typedef typename std::iterator_traits<Iter>::difference_type
                                                             difference_type;

                difference_type distance = std::distance(begin, end);

                if (distance < 2)
                {
                    std::stringstream ss;
                    ss << "The standard deviation cannot be computed for "
                          "less than two elements. The input sequence has "
                       << distance
                       << " elements.";

                    throw std::runtime_error(ss.str());
                }

                typedef typename std::iterator_traits<Iter>::value_type
                                                             value_type;

                double x = 0.0;
                double x_squared = 0.0;

                for (Iter it = begin; it != end; ++it)
                {
                    x += *it;
                    x_squared += (*it) * (*it);
                }

                return std::sqrt((x_squared - (x * x) / distance) /
                                 (distance - 1)
                                );
            }

        } /* net::coderodde::stat */

    } /* net::coderodde */

} /* net */

#endif  /* CODERODDE_SD_H */

main.cpp:

#include <iostream>
#include <list>
#include "coderodde_sd.h"

using net::coderodde::stat::sd;
using std::cout;
using std::list;

int main(int argc, char** argv) {
    double bad_array[]{1.0};

    try
    {
        sd(bad_array, bad_array);
    }
    catch (std::runtime_error& error)
    {
        cout << "ERROR: " << error.what() << "\n";
    }

    try
    {
        sd(bad_array, bad_array + 1);
    }
    catch (std::runtime_error& error)
    {
        cout << "ERROR: " << error.what() << "\n";
    }

    std::list<int> my_list = { 1, 5, 2, 4, 3 };

    cout << "Standard deviation: "
         << sd(my_list.begin(), my_list.end())
         << "\n";

    return 0;
}

I tried hard to write idiomatic C++; please tell me where I failed to reach that ideal + any other critique.


texts: Partitions of an integer and filtering by number of elements

texts:
I have Python code to get the partitions of an integer and then display those who have a certain number of elements. The problem is, the program is rather slow and takes a considerable amount of time to complete the partitions of numbers beyond 25. I am certain my algorithm is not optimal and would like to know how to improve it.

#Function to create a partition, receives the integer n
def particion(n):
    if n == 1:
        return [[1]]

#Add the number itself to the results
    res = [[n]]

#Go through all the numbers
    for i in range(1, n):
        a = n-i
        R = particion(i)
    #Add the results of the recursion
        for r in R:
            if r[0] <= a:
                res.append([a] + r)

    return res

#Only print the partitions of length x
resultado=particion(n)
for i in range(0,len(resultado)):
    if len(resultado[i])==x:
        print(resultado[i])


texts:
I wrote a function to implement a generalised version of binary search that can find the minimum or maximum index in a given sorted list that satisfies a provided predicate.

My Code

def xbinsearch(pred, lst, type = "min", default = None):
    """
        * Finds the minimum or maximum index of a sorted list such that the value at that index satisfies a given predicate.

        *   Params:
            *   `pred`: Predicate function.
                *   Params:
                    *   `idx`: The index of the value to be tested.
                    *   `lst`: The list to search for said value in.
                *   Return: An ordered pair of the form `(x, y)`.
                    *   `x`: Boolean indicates whether or not `lst[idx]` satisfies the predicate.
                    *   `y`: `-1`, `1` or `None`.
                        *   `-1` indicates that if `lst[idx]` does not satisfy the predicate, then all values below `lst[idx]` also do not satisfy the predicate.
                        *   `1` indicates that if `lst[idx]` does satisfy the predicate, then all values above `lst[idx]` also do not satisfy the predicate.
                        *   `None` is given with `True` for the first index of the ordered pair.
                        *   It is used to determine which "half" to discard in the binary search.
    """
    low, hi, best = 0, len(lst)-1, default
    while low <= hi:
        mid = (low+hi)//2
        p = pred(mid, lst)
        if p[0]:    #The current element satisfies the given predicate.
            if type == "min":
                if best == default or lst[mid] < lst[best]: best = mid
                hi = mid-1
            elif type == "max":
                if best == default or lst[mid] > lst[best]: best = mid
                low = mid+1
        elif p[1] == 1:     #For all `x` > `lst[mid]` not `P(x)`.
            hi = mid - 1
        elif p[1] == -1:    #For all `x` < `lst[mid]` not `P(x)`.
            low = mid + 1
    return best

Sample Use Case

Problem
Element equals its index

  Given a sorted array of distinct integers, write a function index_equals_value that returns the lowest index for which array[index] == index.
  Return-1` if there is no such index.
  Your algorithm should be very performant.

  [input] array of integers ( with 0-based nonnegative indexing )
  [output] integer

  Examples:

input: [-8,0,2,5]
output: 2 # since array[2] == 2

input: [-1,0,3,6]
output: -1 # since no index in array satisfies array[index] == index

  Random Tests Constraints:

  Array length: 200 000

  Amount of tests: 1 000

  Time limit: 1.5 s

My Code

def identity(idx, lst):
    tpl, val = [None, None], lst[idx]
    tpl[0] = val == idx
    if val < idx:   tpl[1] = -1
    elif val > idx: tpl[1] = 1
    return tuple(tpl)

def xbinsearch(pred, lst, type = "min", default = None):
    low, hi, best = 0, len(lst)-1, default
    while low <= hi:
        mid = (low+hi)//2
        p = pred(mid, lst)
        if p[0]:    #The current element satisfies the given predicate.
            if type == "min":
                if best == default or lst[mid] < lst[best]: best = mid
                hi = mid-1
            elif type == "max":
                if best == default or lst[mid] > lst[best]: best = mid
                low = mid+1
        elif p[1] == 1:     #For all `x` > `lst[mid]` not `P(x)`.
            hi = mid - 1
        elif p[1] == -1:    #For all `x` < `lst[mid]` not `P(x)`.
            low = mid + 1
    return best

def index_equals_value(lst):
    return xbinsearch(identity, lst, default = -1)


texts:
To display all the shops, I get data from a database (Firestore) and push them into array and setState, and use map to display shops from this.state{ shops }.

This is working okay, but I am wondering if there are better ways.

export default class Shop extends Component {
  constructor(props) {
    super(props);
    this.state = {
      shops: [],
    };
  }

  async componentDidMount() {
    const querySnapshot = await db.mShopsCollection().get();
    const shops = [];
    querySnapshot.forEach((doc) => {
      const shop = {
        id: doc.id,
        address1: doc.data().address1,
        address2: doc.data().address2,
        address3: doc.data().address3,
        name: doc.data().name,
        prefecture: doc.data().prefecture,
        zip_code: doc.data().zip_code,
      };
      shops.push(shop);
    });
    this.setState({ shops });
  }

  render() {
    const { shops } = this.state;
    return (
      <View>
        {shops.map((shop) => (
          <TouchableOpacity onPress={this.handleShowMap} key={shop.id}>
            <View>
              <View>
                <Text>{shop.name}</Text>
                <Text>
                  〒
                  {shop.zip_code}
                  {'\n'}
                  {shop.prefecture}
                  {shop.address1}
                  {shop.address2}
                  {'\n'}
                  {shop.address3}
                </Text>
            </View>
          </TouchableOpacity>
        ))}
      </View>
    );
  }
}
```


texts: Pulling from data from SQLite DB on Android

texts:
Apart from merging the 2 get methods, what else can I do to optimise this?
Both input and output cannot be changed. Is there a way to iterate a map while writing to it?

// String condition - "cust" for customer group, "item" for itemGroup
public HashMap<String, ArrayList<PriceTable>> getPromoForViewGroup(
            String condition) {
    String custGroup = "custType";
    String itemGroup = "itemType";
    HashMap<String, ArrayList<PriceTable>> valueMap = new HashMap<String, ArrayList<PriceTable>>();

    if (condition.equals(CUST)) {
        getPromoForViewGroupHelperCust(custGroup, condition, valueMap);
    }

    if (condition.equals(ITEM)) {
        getPromoForViewGroupHelperItem(itemGroup, condition, valueMap);

    }

    return valueMap;
}

private Map<String, ArrayList<PriceTable>> getPromoForViewGroupHelperItem(
            String searchGroup, String condition,
            Map<String, ArrayList<PriceTable>> valueMap) {

    List<PriceTable> allList = new ArrayList<PriceTable>();

    Cursor cursor = database.rawQuery("Select * from PriceTable where "
            + searchGroup + " IS NOT NULL", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        PriceTable pt = cursorToPriceTable(cursor);
        if (!pt.getItemType().equals(""))
            allList.add(pt);

        cursor.moveToNext();

    }

    for (PriceTable pt1 : allList) {
        ArrayList<PriceTable> set = valueMap.get(pt1.getItemType());
        if (set == null) {
            set = new ArrayList<PriceTable>();
            set.add(pt1);
        } else {
            set.add(pt1);
        }
        valueMap.put(pt1.getItemType(), set);

    }
    cursor.close();

    return valueMap;

}

private Map<String, ArrayList<PriceTable>> getPromoForViewGroupHelperCust(
        String searchGroup, String condition,
        Map<String, ArrayList<PriceTable>> valueMap) {

    List<PriceTable> allList = new ArrayList<PriceTable>();

    Cursor cursor = database.rawQuery("Select * from PriceTable where "
            + searchGroup + " IS NOT NULL", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        PriceTable pt = cursorToPriceTable(cursor);
        if (!pt.getCustType().equals(""))
            allList.add(pt);

        cursor.moveToNext();

    }

    for (PriceTable pt1 : allList) {
        ArrayList<PriceTable> set = valueMap.get(pt1.getCustType());
        if (set == null) {
            set = new ArrayList<PriceTable>();
            set.add(pt1);
        } else {
            set.add(pt1);
        }
        valueMap.put(pt1.getCustType(), set);

    }
    cursor.close();
    return valueMap;

}

private PriceTable cursorToPriceTable(Cursor cursor) {
        PriceTable priceTable = new PriceTable();

        priceTable.setPromoNum(cursor.getString(0));
        priceTable.setPromoType(cursor.getString(1));
        priceTable.setPromoRank(cursor.getString(2));
        priceTable.setPromoName(cursor.getString(3));
        priceTable.setItemType(cursor.getString(4));
        priceTable.setItemCode(cursor.getString(5));
        priceTable.setCustType(cursor.getString(6));
        priceTable.setCustCode(cursor.getString(7));
        priceTable.setStartDate(cursor.getString(8));
        priceTable.setEndDate(cursor.getString(9));
        priceTable.setPercent(cursor.getString(10));
        priceTable.setSalesPrice(cursor.getString(11));

        return priceTable;
    }


texts:
I've am trying to read a large text file and output the distinct words in it along with it's count. I've tried a couple of attempts so far, and this is by far the fastest solution I have come up with.

private static readonly char[] separators = { ' ' };

public IDictionary<string, int> Parse(string path)
{
    var wordCount = new Dictionary<string, int>();

    using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
    using (var streamReader = new StreamReader(fileStream))
    {
        string line;
        while ((line = streamReader.ReadLine()) != null)
        {
            var words = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);

            foreach (var word in words)
            {
                if (wordCount.ContainsKey(word))
                {
                    wordCount[word] = wordCount[word] + 1;
                }
                else
                {
                    wordCount.Add(word, 1);
                }
            }
        }
    }

    return wordCount;
}

How I am measuring my solution

I have a 200MB text, which I know the total word count for (via a text editor). I'm using the Stopwatch class and counting the words to ensure accuracy and measuring the time taken. So far, it is taking around 9 seconds.

Other attempts

I have tried to utilise multithreading to split out the work via the TPL library. This involved batching multiple lines, sending out the processing of the batch of lines to a separate task and locking the read/write operations in the dictionary. This however, seems to not provide me any performance improvements.

It took around 30 seconds. I suspect the locking to read/write to the dictionary is too costly to gain any performance.I am sure there is a faster way to achieve this! Any suggestions/criticisms to my solution are welcome.

Here is the link to the test file I'm using.


texts:
I set out to make a simple dynamic resize method for images. Obviously, it's better to serve images that are pre-sized to avoid unnecessary server loads. But it was fun to make for a novice/beginner jQuery project and not really meant for a production project. For many of you, I'm sure it'll be rudimentary at best, but that's why I'm posting it here, to get some advice on ways to improve it.

The goal,

Add wrappers dynamically (using the wrapInner method for content structure inside the collection of elements with class topic), add wrapper around images to constrain the content image sizes.
dynamic width & height attributes on images - onLoad & onResize
Dynamic query string on img.src (URL adds ?width=###&height=###)
onLoad & resize (for demo purposes I'm using "placehold.it/###x###") this is
only needed for content images in the DOM.
Real width & height of image set to parent (figure) as max-width/height
onLoad
Debounce/throttle resize events to avoid excess events begin fired. (used a method displayed on css-tricks.com and can be found here)

The CSS and HTML is more to make the demo look nice but if you have some input for that as well, by all means. Like I said, I'm certainly not a jQuery developer, though I'm trying to learn as quickly as possible to augment my skill set. So if you have any advice or input on areas that can improve, I'd greatly appreciate it.

Fiddle: DEMO

$(function() {
    // demo fun
    $('.topic').each(function() {
        var $this = $(this),
            ifMedia = $this.find('.media');
        $this.wrapInner('<section class="content"/>');

        if (ifMedia.length) {
            $this.addClass('media-support');
        }
        if ($this.hasClass('media-support')) {
            $('.media-support:odd').addClass('inverse');
        }
    });
});

var sizeTimer;
$(window).on('load', function() {
    var img = new Image();
    $('img').each(function() {
        var $this = $(this),
            image = new Image(),
            _imgWidth = $(this).width(),
            _imgHeight = $(this).height(),
            _naturalWidth = this.naturalWidth,
            _naturalHeight = this.naturalHeight;
        image.src = $(this).attr("src");
        $this.attr({
            'width': +_imgWidth,
            'height': +_imgHeight,
            'src': '//placehold.it/' + _imgWidth + 'x' + _imgHeight
        }).wrap('<figure class="image" />').closest('.image').css({
            'max-width': _naturalWidth,
            'max-height': _naturalHeight
        });
    });
}).on('resize', function() {
    clearTimeout(sizeTimer);
    sizeTimer = setTimeout(function() {
        $('img').each(function() {
            var $this = $(this),
                _imgWidth = $(this).width(),
                _imgHeight = $(this).height();
            $this.attr({
                'width': _imgWidth,
                'height': _imgHeight,
                'src': '//placehold.it/' + _imgWidth + 'x' + _imgHeight
            });
        });
    }, 250);
});


texts:
Please help me review this code. I want to make it both accurate and more Go-styled.

Go Playground code

package main

import(
    "fmt"
)

type TreeNode struct {
    val int
    left *TreeNode
    right *TreeNode

}

func isSameTree(p *TreeNode , q *TreeNode ) (bool){
    if p == nil && q == nil {
        return true
    }
    if p != nil && q == nil{
        return false;
    }
    if p ==nil && q != nil {
        return false;
    }
    if (p.val == q.val) && (isSameTree(p.left,q.left)) && (isSameTree(p.right ,q.right)){
        return true;
    } else {
        return false;
    }
}
func main(){
    p := &TreeNode{val: 1}
    p.left = &TreeNode{val: 2}
    p.right = &TreeNode{val: 3}

    q := &TreeNode{val: 1}
    q.left = &TreeNode{val: 2}
    q.right = &TreeNode{val: 3}

    isSame := isSameTree(p,q)
    fmt.Println("is same?: ", isSame)
}


texts:
I am building a ticket management system for a state server we use at work.  Back end is node.js with multiple front ends.  I am rewriting my back end to be more maintainable as the scope grows.

For this particular function I start with this:

[
    {
        "id": 4993,
        "ticket": "A142032570",
        "sort": "07/22/14"
    },
    {
        "id": 5060,
        "ticket": "A142043078",
        "sort": "07/23/14"
    }
]

with many more entries than shown here.  My function takes this data and creates this:

[
    {
        "date": "07/22/14",
        "tickets": [
            {
                "id": 4993,
                "ticket": "A142032570"
            }
        ]
    },
    {
        "date": "07/23/14",
        "tickets": [
            {
                "id": 5060,
                "ticket": "A142043078"
            }
        ]
    }
]

The function used is:

function sortMyTicketsByDate(data){
    var arr = [];
    for(var o in data){
        arr.push(data[o].sort);
    }
    arr = _.uniq(arr);
    for(var i in arr){
        arr[i] = {date: arr[i]};
    }
    for(var d in arr){
        console.log(arr[d]);
        arr[d].tickets = [];
        var elem = arr[d]['date'];
        for(var o in data){
            //data[o].sort, ticket, id
            if (elem === data[o].sort) {
                arr[d]['tickets'].push({id: data[o].id, ticket: data[o].ticket});
            };
        }
    }
    return arr;
}

What improvements can be made to sortMyTicketsByDate to be more efficient/understandable?


texts:
I've been working on longest mountain in array on Leetcode:

  Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:

  B.length >= 3
  There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]

  (Note that B could be any subarray of A, including the entire array A.)

  Given an array A of integers, return the length of the longest mountain.

  Return 0 if there is no mountain.

  Example:

  Input: [2,1,4,7,3,2,5]
  Output: 5
  Explanation: The largest mountain is [1,4,7,3,2] which has length 5.

I've come up with a solution that passes the test but only beats 17% of javascript submissions. I just want to know if there's anything I can do with my code to optimize it's performance. Also please let me know if the code could be written better.

The idea is as followed. In a mountain array we have a start, peak, and an end. I keep track of when a mountain starts, when a mountain peaks and when a mountain ends. When the mountain ends i pop off my start value from the start stack and use the spread operator to add it to a result array which contains the peak and the end of a mountain.

For example the array [1,3,8]... the mountain starts at index 1, peaks at index 3 and ends at index 8. In order to find the length of the array I then subtract the end from the start.

A mountain can have multiple peaks and thus an array such as [[1,3,8],[8,13,18]] is possible. I'm handling this situation by having a maxDifference variable to store the maximum differences if a mountain is complete [start, peak, end].

var longestMountain = function(A) {

    let maxDifference = 0;
    let startPeakEnd = [];
    const start = [];
    const innerLoop = [];

    if(A[1]>A[0])start.push(0)
    else start.push(1);

    for(let i = 0; i < A.length; i++){
        if(A[i-1]<A[i] && A[i+1]<A[i]){
            startPeakEnd.push(i);
        }else if(A[i-1]>=A[i] && A[i+1]>=A[i]){
            startPeakEnd.push(i);
            innerLoop.push([start.pop(),...startPeakEnd]);
            start.push(i)
            startPeakEnd = [];
        }else if(A[i+1]===undefined){
            startPeakEnd.push(i);
            innerLoop.push([start.pop(),...startPeakEnd]);
        }
    }

    for(let item of innerLoop){
        if(item.length===3){
            if(item[2]-item[0]+1>maxDifference){
                maxDifference=item[2]-item[0]+1;
            }
        }
    }

    return maxDifference;

};


texts: Validating a form and alerting the server if passed

texts:
This is my first script in object-oriented JavaScript (jQuery 1.5.2). Its purpose is to simply validate a form (nothing fancy at the moment just checks if any value is present on required fields) and if validation is passed it submits the form via Ajax and alerts the server's response.

It would be great if more experienced programmers could review this and tell me what could be improved and what's dead wrong.

Here is the full working page:

<form action="script.php" method="post">
     Choose Username

     <input type="text" name="username" />

     Choose Password

     <input type="text" name="password" />

     Message to Admin

     <textarea name="message"></textarea>

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

Contents of script.php

<?php

    while (list($key, $value) = each($_POST)) {
        echo $_POST[$key].' - ';
    }

?>


texts: Determines whether a number is a power of 2

texts:
The task:

Write a method that takes in a number and returns true if it is a power of 2. Otherwise, return false.
You may want to use the % modulo operation. 5 % 2 returns the remainder when dividing 5 by 2; therefore, 5 % 2 == 1. In the case of 6 % 2, since 2 evenly divides 6 with no remainder, 6 % 2 == 0."

Model solution:

def is_power_of_two?(num)
  if num < 1
    return false
  end

  while true
    if num == 1
      return true
    elsif num % 2 == 0
      num = num / 2
    else
      return false
    end
  end
end

My solution:
def is_power_of_two?(num)

0.upto(num) do |i|
  return true if 2**i == num
  return false if 2**i > num
end
end

This is a problem from a beginner's course. I'm trying to return to these problems now that I've learned some more idiomatic Ruby.
Generally, are there any advantages to the model solution? Specifically, how could I improve my solution?


texts:
I've got some pages that may or may not load with a ReturnUrl parameter, and some links that will be generated without that parameter (though I've applied a class to them).

The site uses jQuery, and I think I've found the most elegant and least breaky solution as follows:

$(document).ready(function() {
    $('a.my_returnlink').each(function(){
        $(this).attr('href',$(this).attr('href')+window.location.search);
    });
});

That is, given a page url like http://example.com/page.aspx?ReturnUrl=blahblahblah and the following link on the page: Some link, that link will end up pointing to http://example.com/someotherpage.aspx?ReturnUrl=blahblahblah.

Is there any reason not to do it this way?


texts:
I'm trying to implement balanced tree checking by python like following.

# Balanced tree definition:
# if tree's left and right sub tree are balanced, and their height difference is not bigger than 1, then the tree is balanced else not.

class Node:
    def __init__(self, val):
        self.left = None
        self.right = None
        self.val = val

def is_balanced(root):
    # root: Node
    # return: boolean
    ret, h = is_balanced_helper(root)
    return ret

def is_balanced_helper(root):
    if not root:
        return True, 0
    else:
        retl, hl = is_balanced_helper(root.left)
        retr, hr = is_balanced_helper(root.right)
        h = max(hr, hl)+1
        if retl and retr:
            return abs(hl-hr) < 2, h
        else:
            return False, h

Please help me review above code.

And I feel returning 2 return values are not elegant. And return -1 when the tree is not balanced is also not elegant. Or shall I raise exception when tree is not balanced? What's your suggestion when handle such case?


texts: Concatenate the square of all the digits of a number

texts:
Task: given a number (positive or negative), square every digit of it and concatenate them, forming a resulting number.

For example:

9119 should become 811181 = 9^2*10^0 + 1*10^1 + 1*10^2 + 9^2*10^3
(-1) should become (-1)

My code:

-- convert a number to the list of digits
-- doesn't work with negative numbers
digs :: Integral x => x -> [x]
digs 0 = [0]
digs x = let
      helper :: Integral x => x -> [x]
      helper 0 = []
      helper n = helper (n `div` 10) ++ [n `mod` 10]
  in
      helper x

squareDigit :: Int -> Int
squareDigit n = let sign = signum n
                    digits = (digs (abs n))
                    digs_sq = map (^ 2) digits
                    -- we can't concat squares as they may have more then 1 digit
                    digs_sq_flat = map digs digs_sq >>= id
                in
                  sign * foldl (\acc x -> x + (acc * 10)) 0 digs_sq_flat

Basically, it works:

*SquareDigit> squareDigit 9119
811181
*SquareDigit> squareDigit (-9119)
-811181

But maybe, my solution can be made more elegant.


texts:
I'm trying to read some SNMP packets on my own. So far so good, I was able to put up some functions to write some SNMP TRAP packets as I need them. However, now I need to be able to read them and while my code works, I'm not happy with it.

I'd like to see if any of you could please tell me if there's a better way to do and/or optimize my current code. My binary-fu isn't as good so I'd love if I could get some proposals without bit shifting as that confuses me and could confuse other people I program with.

I've heard and seen SNMP libraries for .NET but it's overkill for what I need to do. Also, I'm not allowed to use external libraries, and so far the code works, I just want to simplify it more and optimize it too, as it'll be used very extensively under high network traffic.

This is my (sample) code:

private void ReadSNMP(byte[] buf, int size)
{
    if (size > 0)
    {
        // IS UNIVERSAL SEQUENCE?
        if (buf[0] == 0x30)
        {
            int iPos = 0;
            int pckSize = ReadSNMPInt(buf, ref iPos);
            int version = ReadSNMPInt(buf, ref iPos);
            String comm = ReadSNMPString(buf, ref iPos);
        }
    }
}

And this is a sample ReadSNMPInt function:

private int ReadSNMPInt(byte[] buf, ref int iPos)
{
    MemoryStream ms = new MemoryStream();

    iPos++;
    if (buf[iPos] > 0x80) // > 80 = BER :(
    {
        if (buf[iPos] == 0x81)
            ms.Write(new byte[] { buf[iPos + 1], 0x00, 0x00, 0x00 }, 0, 4);
        if (buf[iPos] == 0x82)
            ms.Write(new byte[] { buf[iPos + 2], buf[iPos + 1], 0x00, 0x00 }, 0, 4);
        if (buf[iPos] == 0x83)
            ms.Write(new byte[] { buf[iPos + 3], buf[iPos + 2], buf[iPos + 1], 0x00 }, 0, 4);
        if (buf[iPos] == 0x84)
            ms.Write(new byte[] { buf[iPos + 4], buf[iPos + 3], buf[iPos + 2], buf[iPos + 1] }, 0, 4);

        iPos += buf[iPos] - 0x80;
    }
    else
    {
        iPos++;
        ms.Write(new byte[] { buf[iPos], 0x00, 0x00, 0x00 }, 0, 4);
    }

    iPos++;
    return BitConverter.ToInt32(ms.ToArray(), 0);
}

It works, but I noticed that when I needed to make the ReadSNMPString function, it needed kinda the same logic but different. I'm using these docs as reference (they're the best I've found, and so far their documentation helped to make the production code work). Also, replace snmp.htm with ber.htm to find out other links.

I'm trying to find out how to make a generic function to read at least one function for each datatype I need (simple though, only ints and strings) without using such ugly code.

I managed to make a new function now but I feel it can be a bit slower and/or not as optimized as I'd like.

public static class ASN1Int
{
    public static int Read(Stream s)
    {
        int preByte = s.ReadByte();
        if (preByte <= 0x79)
            return s.ReadByte();

        int bSize = preByte - 0x80;

        MemoryStream ms = new MemoryStream();
        using (BinaryWriter b = new BinaryWriter(ms))
        {
            for (int i = 0; i < 4 - bSize; i++)
                b.Write((byte)0x0);
            for (int i = 0; i < bSize; i++)
                b.Write((byte)s.ReadByte());
        }

        byte[] rv = ms.ToArray();
        Array.Reverse(rv, 0, rv.Length);
        return BitConverter.ToInt32(rv, 0);
    }
}

Any ideas are really welcome, and if someone's gonna close this on here please do a bit more research before going trigger-happy on me.


texts:
Scope is to throw any mail, html or plain or multipart into this and receive a readable formatted text that deals with special characters and html issues. Field of usage: System that imports mails into a mysql db, or prints them to pdf etc.

What can I improve here?

import imapclient, pyzmail, html2text

"""
Connect to IMAP. Login and select folder.
retreive UID of Mails and fetch the latest.
return the body of the latest message
"""

def latestMail():
    imapObj = imapclient.IMAPClient('imap.server.com', ssl=False)
    imapObj.login('username', 'password')
    imapObj.select_folder('INFO', readonly=True)
    UIDs = imapObj.search(criteria='ALL', charset=None)
    rawMessages = imapObj.fetch(UIDs[0], ['BODY[]', 'FLAGS'])
    message = pyzmail.PyzMessage.factory(rawMessages[UIDs[0]]['BODY[]'])
    return message

"""
Open message object, check if content is html or plain or both.
If both, only plain will be taken. for Plain, decodes the
message if charset is given, if not we will use system default
for html, additionally format html so the information
is exportable to any db.
"""

def parser(message):
    if message.text_part is not None and message.html_part is not None:
        multipart = True
    else:
        multipart = False

    if message.text_part is not None:
        try:
            body = message.text_part.get_payload().decode(message.text_part.charset)
        except TypeError:
            body = message.text_part.get_payload()

    if message.html_part is not None and multipart is False:
        try:
            body = html2text.html2text(message.html_part.get_payload().decode(message.html_part.charset))
        except Exception:
            raise Systemexit
    return body

print parser(latestMail())


texts:
This is my first attempt to do unit test for one of my controllers.

@RunWith(MockitoJUnitRunner.class)
public class AddressControllerUnitTests {

    private MockMvc mockMvc;

    @Mock
    SubmissionService submissionService;

    @Mock
    MessageSource messageSource;

    @InjectMocks
    AddressController addressController;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(addressController).build();
    }

    @Test
    public void submitSuccess() throws Exception {
        when(submissionService.isEmailAvailable("email@email.com",0)).thenReturn(true);
        when(messageSource.getMessage("form.submitted.success", null, Locale.ENGLISH)).thenReturn("Form has been submitted successfully");
        this.mockMvc
                .perform(post("/address")
                        .param("address", "my address")
                        .param("phone", "08123456789")
                        .param("email", "email@email.com")
                        .param("userId", "14"))
                .andExpect(status().isFound())
                .andExpect(flash().attribute("message", "Form has been submitted successfully"))
                .andExpect(redirectedUrl("/address"));
    }
}

Do I really need to perform expect on the flashAttribute ? Or Should I just remove it completely ? It looks funny that I have to set

when(messageSource.getMessage("form.submitted.success", null, Locale.ENGLISH)).thenReturn("Form has been submitted successfully");

and then

.andExpect(flash().attribute("message", "Form has been submitted successfully"))


texts: Digit Sum find number of ways and max people

texts:
I applied for a job, and the prospective employer sent me the following HackerRank problem, which cannot be found in the public area.

There is a lottery with n coupons and n people take a part in it. Each person picks exactly one coupon. Coupons are numbered from a to b. The winner of lottery is any person who owns a coupon with the sum of digits written on it equal to s, and if there are more such people, then the prize is split equally among them. Determine s in such a way the is at least one winner and the prize is split among the most people.

How many ways can the required sum be chosen so that the lottery is split among the maximum number of people?

For example, there are n = 10 participants in the lottery coupons are numbered from a = 1 to b = 10. The sums of the digits of each coupon are [1,2,3,4,5,6,7,8,9,1]. Any sum from 2 to 9 has only 1 winner. If the sum of digit is 1, however, there are two winners, tickets 1 and 10. The answer is s = 1 with two participants winning the lottery.

Function Description

Complete the function waysToChooseSum. The function must return an array of Long integers with 2 elements: the total number of ways to choose sum so that maximum possible participants win the lottery and the number of participants who will win the lottery.

waysToChooseSum has the following parameter(s):
a - a Long integer, that starting index of lottery coupons,
b - a Long integer, that ending index of lottery coupons

Constraints

1 <= a < b <= 10^18

Solution

fun Long.sum(): Long {
    var sum = 0L
    for(ch in toString())
        sum += ch.toString().toLong()
    return sum
}

fun waysToChooseSum(a: Long, b: Long): Array<Long> {
    val sums = HashMap<Long, Long>()
    var variants = 0L
    var maxPeople = 1L

    for(i in a..b) {
        val sum = i.sum()
        if(!sums.containsKey(sum))
            sums[sum] = 1
        else {
            sums[sum] = sums[sum]!!.plus(1)
            if(sums[sum]!! > maxPeople) {
                variants = 0
                maxPeople = sums[sum]!!
            }
        }

        if(sums[sum]!! == maxPeople)
            variants++

    }

    return arrayOf(variants, maxPeople)
}

I'm trying to improve performance, correctness in unanticipated cases in the solution above to successfully pass programming test.
Any advice or potential issues in the code?

Sample Case 1

Sample Input

a = 1, b = 5

Sample Output

[5, 1]

The sum of digits for all participants is different, i.e. [1,2,3,4,5], hence there are 5 ways to choose the sum with 1 winner each.

Sample Case 2

Sample Input

a = 3, b = 12

Sample Output

[1, 2]

The sum of digits of 10 numbers are [3,4,5,6,7,8,9,1,2,3]. The sum 3 is seen twice. So, there is 1 way to choose, with the maximum of 2 winners.


texts: Group and send all files to filetype folder

texts:
I have around ~2M of files in one folder, which I need to manage. So, I want to separate them in groups by their filetypes.

Example:

filenames

1.A, 2.A, 3.A, 2.B, 3.B, 4.B, 5.C, 6.C

My code:

import os
all_files = os.listdir(".")
filetypes = list(set([i.split(".")[-1] for i in all_files]))
for i in filetypes:
    os.system("mkdir -p %s"%i)
    os.system("mv *.%s %s"%(i, i))

How can I improve this?


texts: Longest increasing subsequence and common substring

texts:
I wrote a program that computes longest increasing subsequences and common substrings.

Can you please suggest more elegant and eloquent ways for this program? (Perhaps better ways to represent a graph with vertices and edges?)

Longest increasing subsequences using longest increasing suffixes:

from functools import lru_cache

def maxima(iterable, key=lambda e: e):
    maxima = []
    for e in iterable:
        if not maxima or key(e) == key(maxima[0]):
            maxima.append(e)
        elif key(e) > key(maxima[0]):
            maxima = [e]
    return maxima

def lis(a):
    @lru_cache(maxsize=None)
    def lisuff(i):
        cases = [e + [i]
                 for j in range(i)
                 for e in lisuff(j)
                 if a[e[-1]] <= a[i]] # 0 <= j < i
        return maxima(cases, key=len) or [[i]]
    z = maxima((e
                for i in range(len(a))
                for e in lisuff(i)), key=len)
    return list(z)

assert [[2, 3, 4], [2, 5, 6]] == lis((7, 8, 1, 5, 6, 2, 3))

Longest common substrings using longest common suffixes:

def lcs(a, b):
    @lru_cache(maxsize=None)
    def lcsuff(i, j): # returns a tuple of (offset, count)
        if i == -1 or j == -1 or a[i] != b[j]:
            return (i, 0)
        o, c = lcsuff(i-1, j-1)
        return (o, c+1) if c > 0 else (i, 1)
    m, n = len(a), len(b)
    z = maxima((lcsuff(i, j) for i in range(m) for j in range(n)), key=lambda e: e[1])
    return [a[s:s+c] for s, c in z]

assert ['aba', 'bab'] == lcs('abab', 'baba')


texts: Limiting the save content of file to certain size

texts:
The goal here is to only save (to file) the most recent Objects created if Object::maxMemoryOfObjects is exceeded.

#include <iostream>
#include <list>
#include <algorithm>
#include <fstream>
#include <map>

struct Object {
    const int ID;
    Object() : ID(++lastObjectID) {}
    static const int maxMemoryOfObjects = 200;
    static int totalMemoryOfObjects, lastObjectID;
};
int Object::totalMemoryOfObjects = 0, Object::lastObjectID = 0;

struct Location {
    std::list<Object*> objectsLyingAround;
    Location() {
        for (int i = 0; i < 12; i++) {
            Object* object = new Object;
            objectsLyingAround.push_back(object);
            Object::totalMemoryOfObjects += sizeof(*object);
        }
    }
};

struct Person {
    void visitLocation (const Location*) {}
};

std::list<Location*> itinerary;

void saveObjects() {
    std::ofstream outfile ("Objects.txt");
    std::map<int, Object*/*, std::greater<int>*/> objectMap;
    for (Location* x : itinerary)
        for (Object* o : x->objectsLyingAround)
            objectMap.emplace (o->ID, o);
    std::cout << "Objects being saved (from oldest to newest) IDEALLY are:\n";
    for (const auto& x : objectMap)
        std::cout << x.first << ' ';
    if (Object::totalMemoryOfObjects > Object::maxMemoryOfObjects) {
        std::cout << "\nAlert!  totalMemoryOfObjects > maxMemoryOfObjects!  Will save only the newest objects.\n";
        auto it = objectMap.begin();
        while (Object::totalMemoryOfObjects > Object::maxMemoryOfObjects) {
            Object::totalMemoryOfObjects -= sizeof(*it->second);
            std::cout << "totalMemoryOfObjects reduced to " << Object::totalMemoryOfObjects << std::endl;
            it = objectMap.erase(it);
        }
        std::cout << "Objects being saved (from oldest to newest) NOW are:\n";
        for (const auto& x : objectMap)
            std::cout << x.first << ' ';
    }
outfile << objectMap.size() << std::endl;
for (const auto& x : objectMap)
    outfile << x.first << ' ';
}

void loadObjects() {
    int numObjects;
    std::ifstream infile ("Objects.txt");
    infile >> numObjects;
    // etc...
}

int main() {
    Person sam;
    for (int i = 0; i < 5; i++) {
        Location* nextLocation = new Location;
        itinerary.push_back (nextLocation);
        sam.visitLocation (nextLocation);
    }
    saveObjects();
    loadObjects();
}

Output:

Objects being saved (from oldest to newest) IDEALLY are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 5
7 58 59 60
Alert!  totalMemoryOfObjects > maxMemoryOfObjects!  Will save only the newest objects.
totalMemoryOfObjects reduced to 236
totalMemoryOfObjects reduced to 232
totalMemoryOfObjects reduced to 228
totalMemoryOfObjects reduced to 224
totalMemoryOfObjects reduced to 220
totalMemoryOfObjects reduced to 216
totalMemoryOfObjects reduced to 212
totalMemoryOfObjects reduced to 208
totalMemoryOfObjects reduced to 204
totalMemoryOfObjects reduced to 200
Objects being saved (from oldest to newest) NOW are:
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

But the way I'm doing it ironically adds more memory to the Object class (its ID data member). Is there a better way to do this?  We assume here that the Objects are being saved and loaded many times until megabytes or even gigabytes of data are being stored in memory, at which a max should be enforced.  Really old items that are lying around in Locations but never picked up will assume to be discarded first since they are probably forgotten anyway.


texts: I have code that loops through a column of a dataframe. How can I make this code faster? (Python/Pandas)

texts:
I have datasetA with 90,000 rows and datasetB with 5,000 rows. Each dataset has a column called "ID" with employee IDs. My goal is to to create another column in datasetA that identifies whether the employee ID in datasetA is also in datasetB with a True/False. Additionally, there are most likely some multiples for certain employees/employee ids in both datasets. I am fairly certain that the code I wrote works, but it is way too slow, and I was wondering what I could change to make it faster? Thanks!
#Creating the new column to identify whether the ID in datasetA is also in datasetB.

datasetA["inB"] = "Empty"

# Looping through

for id_num in datasetA["ID"]:
    filt = (datasetA["ID"] == id_num)
    if (datasetB["ID"] == id_num).any():
        datasetA.loc[filt, "inB"] = True
    else:
        datasetA.loc[filt, "inB"] = False
```


texts: Implementing a REST API in Go using gorilla/mux and Gorm

texts:
While learning Go I decided to implement a simple REST API to get to know the language and since I am inexperienced in Go I would appreciate any feedback on the code.

Please post any thoughts you have. They don't have to be constructive, but if you have some constructive feedback that will be great.

Q: In particular, I would like to ask the next questions: Are there any bad patterns? Is there something you would do another way? What could be improved? Do I violate any code style rules (say, type names, variables)? Is it ok to place all this code in one file?

Note: I used gorilla/mux and gorm here.

type student struct {
    ID   string `gorm:"primary_key" json:"id"`
    Name string `json:"name"`
    Age  int    `json:"age"`
}

type App struct {
    DB *gorm.DB
}

func (a *App) start() {
    db, err := gorm.Open(
        "postgres",
        "user=go password=go dbname=go sslmode=disable")
    if err != nil {
        panic(err.Error())
    }
    a.DB = db
    db.AutoMigrate(&student{})
    r := mux.NewRouter()
    r.HandleFunc("/students", a.getAllStudents).Methods("GET")
    r.HandleFunc("/students", a.addStudent).Methods("POST")
    r.HandleFunc("/students/{id}", a.updateStudent).Methods("PUT")
    r.HandleFunc("/students/{id}", a.deleteStudent).Methods("DELETE")
    http.ListenAndServe(":8080", r)
}

func (a *App) getAllStudents(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    var all []student
    err := a.DB.Find(&all).Error
    if err != nil {
        sendErr(w, http.StatusInternalServerError, err.Error())
    } else {
        json.NewEncoder(w).Encode(all)
    }
}

func (a *App) addStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    s := student{}
    err := json.NewDecoder(r.Body).Decode(&s)
    if err != nil {
        sendErr(w, http.StatusBadRequest, err.Error())
    } else {
        err = a.DB.Save(&s).Error
        if err != nil {
            sendErr(w, http.StatusInternalServerError, err.Error())
        } else {
            w.WriteHeader(http.StatusCreated)
        }
    }
}

func (a *App) updateStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    s := student{}
    err := json.NewDecoder(r.Body).Decode(&s)
    if err != nil {
        sendErr(w, http.StatusBadRequest, err.Error())
    } else {
        s.ID = mux.Vars(r)["id"]
        err = a.DB.Save(&s).Error
        if err != nil {
            sendErr(w, http.StatusInternalServerError, err.Error())
        }
    }
}

func (a *App) deleteStudent(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    s := student{}
    a.DB.First(&s, mux.Vars(r)["id"])
    err := a.DB.Delete(s).Error
    if err != nil {
        sendErr(w, http.StatusInternalServerError, err.Error())
    }
}

func sendErr(w http.ResponseWriter, code int, message string) {
    response, _ := json.Marshal(map[string]string{"error": message})
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(code)
    w.Write(response)
}

func main() {
    app := App{}
    app.start()
}

Update: I've got some great feedback and I have an additional question related to that. In both the answers you suggest me to get rid of else blocks / use an early return. Is it a common practice in Go? Is it because of error handling in Go which makes you create more if/else blocks? I am asking because in other languages (such as Java) it is considered a bad practice. The main reason is that it hides complexity. Every time you create a return inside an if block you make a the code more flat hiding the real complexity.


texts:
I have implemented functions that will let me reverse a one-to-many value 'Map', that is a plain JavaScript object.

For example,

var map = {'foo': 'bar', 'baz': 'bar', 'moo': 'zoo'};

becomes

var reversedMap = {'zoo': ['moo'], 'bar': ['foo', 'baz']}

and also a function to bring back reversed map to a non-reversed map.

Here's a jsbin to show that my solution is working.

In the following code I have used lo-dash utility toolbelt, but you need not be acquainted with it in order to understand the code. Assume that I trust in performance of lo-dash and what I'm trying to optimize is my own code.

Just for sake of clarity, _.forOwn iterates over object's own properties, and _.forEach iterates over each element of an array.

var identity = function(x) {return x;};
var reverseMapFromMap = function(map, callback) {
    callback = callback || identity; //callback helps to parseInt numeric values, otherwise every object key is a string by default
    var reversedMap = {};
    _.forOwn(map, function(value, key) {
        key = callback(key);
        if (_.isUndefined(reversedMap[value]))
            reversedMap[value] = [key];
        else
            reversedMap[value].push(key);
    });
    return reversedMap;
};

var mapFromReverseMap = function(reverseMap, callback) {
    callback = callback || identity;
    var map = {};
    _.forOwn(reverseMap, function(revMembers, revKey) {
        _.forEach(revMembers, function(revMember) {
            map[revMember] = callback(revKey);
        });
    });
    return map;
};

I'm pretty confident in my solution as it's quite basic, but as it is a frequent part of my code, I'd like to know if you can see any ways to improve performance, or alternatively if there's a better way to solve this problem.


texts:
Since today is apparently a good day for...unlikely FizzBuzz implementations, I decided to contribute another, this one in C++:

#include <iostream>
#include <functional>
#include <vector>
#include "xrange.h"

int main() {
    std::vector<std::function<void(int)> > funcs {
        [](int i) { std::cout << i << "\n"; },
        [](int i) { std::cout << "fizz\n";  },
        [](int i) { std::cout << "buzz\n";  },
        [](int i) { std::cout << "fizzbuzz\n"; }
    };

    auto test = [](int i){return (i % 3 == 0) + 2 * (i % 5 == 0); };

    for (auto i : xrange(1, 101))
        funcs[test(i)](i);
}

This uses the same xrange I posted in a previous answer.

I'd be particularly interested in eliminating having to use test, but a sequence like: [[ is parsed as introducing an attribute rather than using the return from a lambda as an index (and inserting white space doesn't seem to help). I could use .at() instead, but that imposes runtime overhead I'd also rather avoid.


texts:
This is the main code.  Here I'm joining vertices by edges.

node[] gra=new node[5];
{
    for (int i = 0; i < 5; i++)
        gra[i] = new node(i);  //I'm allocating memory for all the vertices.
}
void add_edge(int to,int from)  //to represent the vertice the edge is going and from is now self explanatory
{
    node new_vert=new node(to);
    node temp=gra[from];
    while(temp.next!=null)
        temp=temp.next;
    temp.next=new_vert;
}

Now to do this operation I'm using this loop in main method.

for(int i=0;i<5;i++)  //For simplicity I have taken 5 vertices
    {
        int n=sc.nextInt();                     //N is Number of edges from the vertices, for example in figure for vertex 0 the number of edges are 2.
        for(int j=0;j<n;j++)
        {
            int to=sc.nextInt();
            obj.add_edge(to,i);
        }
    }

Is my implementation correct or efficient enough so that I can use this code for further use?

Feel free to ask if you don't understand the code; I will try to explain.  I know I'm bad at explaining.  And please forgive my English.

Here is my node class

    class node
{
    int data;
    node next;
    node(int data)
    {
        this.data=data;
        this.next=null;
    }
}


texts:
I've often wanted an anonymous function that would do more than return the result of an expression.  So I developed one around the exec function that supports assignments and multiline lambdas but suspect a few things are missing.  Suggestions would be appreciated, please.

I've tried to keep the syntax similar to a normal lambda and also easy to debug by copying the text into a standard function.

Tested with CPython 3.6.5 and Pypy 3.5.3.  To give an idea of the current version, it is capable of evaluating these functions:

λ("""var:
     for i in range(var):
         print(i, end = ",")
         print(' ', end='')
         if i == var - 1:
             print(var)
     print(var)
     rtrn = [i for i in range(var, 0, -1)]
""")(5)

0, 1, 2, 3, 4, 5
5
[5, 4, 3, 2, 1]

λ("x: [x*i for i in range(x)]; print('Final:', rtrn[-1])")(3)

Output: 6
[0, 3, 6]

λ("x, y:: from math import cos, sin; rtrn = cos(x) + sin(y)")(3, 5)

-1.9489167712635838

def lambda_(code):
    """
    Anonymous function supporting multiple line and assignments.
    For one line the form is λ("parameters : code incl assignment")(*arguments)
      and the first exepression is assigned to rtrn which is returned
    For multiline, use triple quotes & the parameters must be on the first line,
      the : is followed directly by a line feed and then the code
    Input:
        code in the form "x, y,...: return_value_expression; other code"
    Output is assigned to variable rtrn
    """
    def build_lambda(*args):
        """
        All arguments are declared global as listcomps etc don't create closure
        when called using exec, so declare parameters & rtrn as globals
        Multiline will return None unless you assign rtrn a value.
        """
        val_idx, val_name = 0, []
        i, parameters = -1, []
        if ":" in code:
            for i, c in enumerate(code):  # loop until the : that ends parameters
                if c in ",:":
                    if val_name:
                        parameters.append(''.join(val_name))
                        val_name = []
                        val_idx += 1
                    if c == ":":
                        break
                elif c != " ":
                    val_name.append(c)

        # exec_code sets rtrn = None for multiline or sets rtrn = first expression for
        #    single line unless :: (used if first expression can't be evaluated)
        if code[i+1] != "\n":  # single line,
            if code[i+1] != ":":
                exec_code = ''.join(("rtrn = ", code[i+1:]))
            else:
                exec_code = ''.join(("rtrn = None; ", code[i+2:]))
        else:  # multiline
            # wont run if excess leading spaces so remove them
            lead = 0
            code_ = code[i+1:]
            while code_[lead+1] == " ":  # how many on 1st line?
                lead += 1
            for i in range(1, len(code_)):  # remove that on all lines
                if code_[i-1: i+1] == "\n ":
                    code_ = code_[: i] + code_[i+lead:]
            exec_code = "rtrn = None" + "\n" + code_  # executable code

        define_globals = ', '.join(["global rtrn"] + parameters)
        assign = [' = '.join((p, str(args[i]))) for i, p in enumerate(parameters)]
        assign = '; '.join(assign)
        cmd = '; '.join((define_globals, assign if assign else "pass", exec_code))
        if args and args[-1] == "print":
            print(cmd, "\n")
        exec(cmd)
        return rtrn

    return build_lambda

λ = lambda_  # rebind to linux ctrl+shift+u 03BB

With the added complexity it seems more reasonable to create a class splitting  code generation, execution and printing.  The code is posted in this question.


texts:
I made a function that takes an argument x and returns True if x is a prime number and False if x is a non-prime number.

I am a beginner and think the code can be improved. I had to add the else statement because for is_prime(2), I kept getting None instead of True. I think this was because when x is 2, list_n = range(2,2) prints [].

Are there ways I could change this so there is not a separate else statement?

def is_prime(x):
    list_n = range(2,x)

    if x <= 1:
        return False
    elif x-1>2:
        for n in range(len(list_n)):
            list_n[n] = x % list_n[n]
        for n in list_n:
            if n == 0:
                return False
        for n in list_n:
            if n > 0:
                return True
    else:
        return True


texts:
The situation is this: I have a bunch of servers which are synced so that they all have the same data. Unfortunately, a disaster happened and the servers are all out of sync. My task is to re-sync all of the servers so that they all have the same sets of data. That is, I need to ensure that each server has a copy of every data set.

The first line of input denotes the number of servers. Following that will be one line of input for each server with a space-separated list of data set ID's. i.e, x y z. Data set id's are positive integers.

I must output a list of instructions to most optimally re-sync the servers in the format of: < data set ID >< FROM >< TO >

#input = {
#1:[1, 3, 4],
#2:[1, 2, 3],
#3:[1, 3],
#4:[1, 4, 2]}

numCenters = int(raw_input('Number of data centers: '))

input = {}
print("Input data set information as: x y z")

# Grab dataset ID information from stdin
for x in range(1, numCenters+1):
        dataSet = raw_input("Data set %s: " % (x))
        input[x] = sorted(map(int, dataSet.split()))

#Map datasets (the numbers / dataset ID) to data centers (the individual lists) that they belong to

#New dictionary for the map
alldatasets = {}

for k,v in input.iteritems():
        for dataset in v: #
                if dataset not in alldatasets:
                        alldatasets[dataset] = [] # Make a dictionary with the key as the dataset ID,
                alldatasets[dataset].append(k) # and the value as a list of which datacenters have that value.

allsets = list(alldatasets.keys())

print("One Possible Correct Output:\n")
for Id,datacenter in input.iteritems():
        for sets in allsets: #go through every datacenter, and compare the datasets it has to a list of all datasets.
                if sets not in datacenter:
                        print("%s %s %s" % (sets, alldatasets[sets][0], Id))
print("done")

Input:

4
1 3 4
1 2 3
1 3
1 4 2

Output:

One possible correct output:

2 2 1
4 1 2
2 2 3
4 1 3
3 1 4
done

I am looking to improve the code that I have written. Either optimizing its run time, making it look better, or any other comments are welcome. I am moreso looking for optimization feedback, though.


texts: Finding the index of the character whose removal will make a palindrome

texts:
Before I get into describing by problem I'd like to point out I found this question under c++ tag. But the solution of that question is already implemented in my code.
I am solving a problem from hackerrank. My code for that problem is logically correct but in some of the cases time limit exceeds.

Problem Statement
Given a string S , of lowercase letters, determine the index of the character whose removal will make a S palindrome. If is already a palindrome or no such character exists, then print -1 . There will always be a valid solution, and any correct answer is acceptable. For example, if S = "bcbc", we can either remove 'b' at index 0 or 'c' at index 3.
Input Format:
The first line contains an integer T , denoting the number of test cases.
Each line i of the T subsequent lines describes a test case in the form of a single string, Si.
Constraints:
Length of the string can be 100005.
Output Format:
Print an integer denoting the zero-indexed position of the character that makes S not a palindrome; if S is already a palindrome or no such character exists, print -1 .

As a solution my code is as following:
import java.io.*;
import java.util.*;

public class Solution {

public static boolean isPalindrom(String s){
    int n = s.length();
    for (int i=0;i<(n / 2);++i) {
        if (s.charAt(i) != s.charAt(n - i - 1)) {
         return false;
        }
    }

    return true;
}

public static void main(String[] args) throws IOException{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    int t = Integer.parseInt(br.readLine());
    while(t-->0){
        int flag = 0;
        String sb = br.readLine().toString();
        if(isPalindrom(sb)){
            System.out.println("-1");
            flag = 1;
        }
        for(int i=0;i<sb.length()&&flag==0;i++){
            StringBuffer s = new StringBuffer(sb);
            s.deleteCharAt(i);
            if(isPalindrom(s.toString())){
                System.out.println(i);
                break;
            }
        }

    }
}}

I've used best palindrome checker algorithm as described here. and also used BufferedReader as described here. But time limit exceeds in some taste cases. How can I improve my code further?
Thanks in advance!


texts: Should I use an intermediate variable in a complex C# expression?

texts:
Can anyone please tell which one is the more effective way to write C# code, among the two options below?

Option A:

internal static string GetLast3Years()
{
    return (DateTime.Now.Year - 2).ToString() + "," + (DateTime.Now.Year - 1).ToString() + "," + DateTime.Now.Year.ToString();
}

Or option B:

internal static string GetLast3Years()
{
    int currentYear = DateTime.Now.Year;
    return (currentYear - 2).ToString() + "," + (currentYear - 1).ToString() + "," + currentYear.ToString();
}


texts: Shuffling sections of an ordered list based on tuple values

texts:
I have a list as follows and I  want to shuffle the elements that have the same frequency while keeping the elements with different frequencies in the correct positions. The code below works; however, it is not that nice. I was wondering if anyone had some suggestions e.g. using list comprehension.

pieces_needed = [('a',1),('b',1),('d',1),('c',2),('g',3),('f',5),('z',5)]
temp = []
new_pieces_needed = []
current_freq = 1
for i in pieces_needed:
   if i[1] == current_freq:
      temp.append(i)
   else:
      random.shuffle(temp)
      new_pieces_needed +=  temp
      temp = []
      temp.append(i)
      current_freq = i[1]

random.shuffle(temp)
new_pieces_needed +=  temp

print(new_pieces_needed)

Example output:

[('d',1),('b',1),('a',1),('c',2),('g',3),('z',5),('f',5)]


texts: Powershell remote script execution pattern

texts:
On a CredSSP enabled server is a .psm1 script file that gets executed remotely from a client technology.  The client passes in a couple execution parameters and the server script returns an object back to the client.
This works great but the pattern I've implemented feels clunky. Is there room for improvement?

Client code calling remote server script:

$firstStanza=@{
    a = "Mary had"
    b = "a little"
    c = "lamb"
}

$secondStanza=@{
    d = "its fleece"
    e = "was white"
    f = "as snow"
}

$scriptBlock = {
    Param([Parameter(Mandatory=$true)]$param1,[Parameter(Mandatory=$true)]$param2)
    Import-Module C:\CreateNewObject.psm1
    CombineBothStanzas -firstStanza $param1 -secondStanza $param2
}
$bothStanzasCombined = Invoke-Command -ComputerName serverName.internalDomain.com -ScriptBlock $scriptBlock -ArgumentList $firstStanza,$secondStanza
Write-Output $bothStanzasCombined

Contents of remote script on server c:\CreateNewObject.psm1:

function CombineBothStanzas {
    Param([Parameter(Mandatory=$true)]$firstStanza,[Parameter(Mandatory=$true)]$secondStanza)
    return ($firstStanza + $secondStanza).GetEnumerator() | sort -Property name
}

Remote server script operation returns this object to the client:

Name                           Value
----                           -----
a                              Mary had
b                              a little
c                              lamb
d                              its fleece
e                              was white
f                              as snow


texts: Simple converter: Is it better to use a function within a function?

texts:
Below is an example of a simple converter. In the first example temperature I have used a function within a function. In the second example milli I have used a more direct approach. Which would you consider is the better method to handling calculations in functions and why? Also feedback on my approach and examples of other methods is appreciated.

def temperature():
  while True:
    try:
      user_in = float(input('Number to convert:> '))
      t = user_in
      def cel_to_far(x):
        return 9 * x / 5 + 32
      result = 'is: {} degrees Fahrenheit'.format(cel_to_far(t))
      print('Input: {} degrees Celcius'.format(t), result)
      break
    except ValueError:
      print('Enter numbers only!')

def milli():
  while True:
    try:
      user_in = float(input('Number to convert:> '))
      n = 1 * user_in / 25.4
      print('Input: {} millimeters is: {} inches'.format(user_in, n))
      break
    except ValueError:
      print('Enter numbers only!')


texts: Army strength based on level and modifiers

texts:
Right so I was doing a quick project, and sought a quick way to finish one section of my Python code. I handed it in, but I'm well aware that it's bad code, but I was wondering if there was a good way to condense this code into fewer lines.

def nGen_army(level, strength, weakness):
    if weakness == 1:
        if level == 0:
            army = round(random.randint(1000,5000),4)
            return army
        if level == 1:
            army = round(random.randint(10000,25000),4)
            return army
        if level == 2:
            army = round(random.randint(50000,75000),4)
            return army
        if level == 3:
            army = round(random.randint(100000,200000),4)
            return army
        if level == 4:
            army = round(random.randint(200000,500000),4)
            return army
    if strength == 1:
        if level == 0:
            army = round(random.randint(10000,25000),4)
            return army
        if level == 1:
            army = round(random.randint(50000,100000),4)
            return army
        if level == 2:
            army = round(random.randint(100000,300000),4)
            return army
        if level == 3:
            army = round(random.randint(300000,800000),4)
            return army
        if level == 4:
            army = round(random.randint(800000,1100000),4)
            return army
    else:
        if level == 0:
            army = round(random.randint(5000,10000),4)
            return army
        if level == 1:
            army = round(random.randint(25000,50000),4)
            return army
        if level == 2:
            army = round(random.randint(75000,150000),4)
            return army
        if level == 3:
            army = round(random.randint(150000,250000),4)
            return army
        if level == 4:
            army = round(random.randint(300000,900000),4)
            return army


texts:
Noobie to Numba here, I'm trying to get faster code from existing function but the result is not faster. 10 times faster would be heaven, but I know nothing about optimization.
This is code about parsing gaps in DNA sequences pairwise alignment and doing statistics about it.
The code looks like this:

import re
import time
import numpy as np
from numba import autojit, int32, complex64
sstart = 10
send = 52
absoluteRoiStart = 19 #rank of the first nucleotide in the ROI
absoluteRoiStop = 27 #rank of the the first nucleotide after the ROI
#ROI is here  'TATCGA---CAG|TA-----TACTA-C|G--TTGAGAGAGAC-CCCA'
#between |    'T--CGACCAC--|-GATCGAG---ATC|GGCTT--------CTC--A'
source =      'TATCGA---CAGTA-----TACTA-CG--TTGAGAGAGAC-CCCA'
sequence =    'T--CGACCAC---GATCGAG---ATCGGCTT--------CTC--A'
realSource = 'AAGGTTCCAATATCGACAGTATACTACGTTGAGAGAGACCCCACATGACTGACTACGT'

tresholds = {
    "DEL" : {
        "other" : 2,
        "slippage": 2,
        "quantity" : 7
    },
    "INS" : {
         "other" : 3,
         "slippage": 3,
         "quantity" : 7
    },
    "MUT" : {
        "other" : 3,
        "slippage": 3,
        "quantity" : 7
    },
    "NA" : {
        "other" : 3,
        "slippage": 3,
        "quantity" : 7
    }
}

def getAllGaps(sequence1, sequence2):
    starts = []
    stops = []
    lengths = []
    types = []
    locations = []
    gap = '(\-)+'
    x = re.compile(gap)
    for m in x.finditer(sequence1):
        #Get Gap satrt, stop and length
        start,stop = m.span()
        #Test if Gap is slippage(compression or extension)
        if start > 1 and stop < len(sequence2):
            h = sequence2[start-1:stop+1].upper()
            i = sequence1[start-1:stop+1]
            repetitions = i.replace('-', h[0]).upper(), i.replace('-', h[-1]).upper()
            if h == repetitions[0] or h == repetitions[1]:
                slippage = True
            else:
                slippage = False
        else:
            slippage = False
        starts.append(start)
        stops.append(stop)
        lengths.append(stop-start)
        if slippage:
            types.append(2)
        else:
            types.append(1)
        locations += range(start, stop)
    d = [starts, stops, lengths, types]
    return {'locations': locations, 'bounds': d}

def getAlignmentData(source, sequence, sstart, tresholds):
    insertionData = getAllGaps(source, sequence)
    alignmentLength = len(source)
    oneArray = np.ones(alignmentLength)
    oneArray[insertionData['locations']] = 0
    absoluteIndex = oneArray.cumsum()-1+sstart
    relativeIndex = np.arange(alignmentLength)
    tf = (absoluteIndex >= absoluteRoiStart) & (absoluteIndex < absoluteRoiStop)
    absoluteBounds = absoluteIndex[tf]
    relativeBounds = relativeIndex[tf]
    relativeRoiStart = int(relativeBounds.min())
    relativeRoiStop = int(relativeBounds.max())
    events = np.array(insertionData['bounds'], dtype=np.int32)
    insertionStartingInRoi = events[:,(events[0] >= relativeRoiStart) & (events[1] <= relativeRoiStop)]
    print(insertionStartingInRoi)
    deletionData = getAllGaps(sequence, source)
    events = np.array(deletionData['bounds'], dtype=np.int32)
    deletionOverlappingRoiOrStartingInRoi = events[:,((events[0] <= relativeRoiStart) & (events[1] >= relativeRoiStart)) | ((events[0] >= relativeRoiStart) & (events[1] <= relativeRoiStop))]
    print(deletionOverlappingRoiOrStartingInRoi)

t0 = time.time()
getAlignmentData(source, sequence, sstart, tresholds)
t1 = time.time()
getAlignmentData(source, sequence, sstart, tresholds)
t2 = time.time()

print(str(t1-t0)+' to first try')
print(str(t2-t1)+' to second try')

When I add the @jit decorator on the two functions, I get slower code. Do I need to do something special, like signatures? Can Numba make this code faster or do I need to use Cython?


texts: Another way to find the nearest neighbor points in a 2D plane

texts:
I was inspired by another question to post another method of finding the two points in a plane that are closest to each other1.

This one is a line-sweep algorithm. It works roughly like this:

Sort the points based on their X coordinates.
Take two left-most points. They give us our first guess at the shortest distance (call it D).
Insert those two points into a set that's sorted based on Y coordinates. This collection forms a vertical "band" of points whose X coordinates are within D units of the X coordinate of the current point.
Consider the next point to the right of those currently in the "band" as the current point.
Trim the band to remove points more than D units away in the X dimension from the current point.
Find the points in the band that are vertically within D units of the Y coordinate of the current point.
Look through the points in that rectangle (maximum of 6) to see if any is closer than D units from the current point.
If so, record the points and distance.
Repeat from step 4 for remaining points.

Here's the code:

#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <cassert>

struct point {
    double x, y;

    // Used by the `set<point>` to keep the points in the band
    // sorted by Y coordinates.
    bool operator<(point const &other) const {
        return y < other.y;
    }

    friend std::ostream &operator<<(std::ostream &os, point const &p) {
        return os << "(" << p.x << ", " << p.y << ")";
    }
};

double dist(point const &a, point const &b) {
    return std::hypot(a.x - b.x, a.y - b.y);
}

// We're going to modify the input we receive, so we receive it by value.
// If we knew that the source was going to be modifiable, we could receive
// by non-const reference instead;
std::pair<point, point> min_dist(std::vector<point> points) {

    std::sort(points.begin(), points.end(),
        [](point const &a, point const &b) {
        return a.x < b.x;
    }
    );

    // First and last points from `point` that are currently in the "band".
    auto first = points.cbegin();
    auto last = first + 1;

    // The two closest points we've found so far:
    auto first_point = *first;
    auto second_point = *last;

    std::set<point> band{ *first, *last };

    double d = dist(*first, *last);

    while (++last != points.end()) {
        while (last->x - first->x > d) {
            band.erase(*first);
            ++first;
        }

        auto begin = band.lower_bound({ 0, last->y - d });
        auto end = band.upper_bound({ 0, last->y + d });

        assert(std::distance(begin, end) <= 6);

        for (auto p = begin; p != end; ++p) {
            d = std::min(d, dist(*p, *last));
            first_point = *p;
            second_point = *last;
        }

        band.insert(*last);
    }
    return std::make_pair(first_point, second_point);
}

int main() {
    std::vector<point> points{
        {1, 1},
        {17, 9},
        {23, 23},
        {3, 3},
        {100, 100},
        {200, 200},
        {24, 24},
        {300, 300}
    };

    auto r = min_dist(points);

    std::cout << "Closest points: " << r.first << ", " << r.second
            << ". Distance = "<< dist(r.first, r.second);
}

1. In this case, I've used Euclidian distance, but another metric such as Manhattan distance could be used as well.


texts: Try and except clauses for appending elements in lists

texts:
I have a list that can have up to three elements, and I want to append them to three list, because I get this list from another element within a loop. My final goal is to have a dataframe with the data of all elements. I have coded this:

affected_projects_1 = []
affected_projects_2 = []
affected_projects_3 = []

for issue in project:
    affected_projects = issue.affected_projects
    try:
        affected_projects_1.append(affected_projects[0])
    except IndexError:
        affected_projects_1.append('')
    except:
        raise Exception
    try:
        affected_projects_2.append(affected_projects[1])
    except IndexError:
        affected_projects_2.append('')
    except:
        raise Exception
    try:
         affected_projects_3.append(affected_projects[2])
    except IndexError:
        affected_projects_3.append('')
    except:
        raise Exception

 df = pd.DataFrame(zip(affected_projects_1, affected_projects_2, affected_projects_3))

This piece of code seems pretty verbose and almost repetitive (the only thing that changes is the number). How could I make it more compact? Is that even possible without losing readability or using antipatterns (i.e using globals variables). Thanks


texts:
I wrote a small routines to create a mirror for any binary tree. I am just sharing my necessary routines instead of full class. could you please let me know your comments on this. I just curious to find the complexity of this but I am new to algorithms.

void tree_sample::mirror_image()
{
    create_mirror_for_left_subtree(root->left);
    create_mirror_for_right_subtree(root->right);
    tree_node* temp = 0;
    if(root->left)
        temp = root->left;
    root->left = root->right;
    if(temp)
        root->right = temp;
    else
        root->right = NULL;
}

void tree_sample::create_mirror_for_left_subtree(tree_node *temp)
{
    while(temp!=NULL)
    {
        do_mirror_for_inidividual_node(temp);
        temp = temp->left;
    }
}

void tree_sample::create_mirror_for_right_subtree(tree_node *temp)
{
    while(temp!=NULL)
    {
        do_mirror_for_inidividual_node(temp);
        temp = temp->right;
    }
}

void tree_sample::do_mirror_for_inidividual_node(tree_node *temp)
{
    tree_node* temp2 = 0;
    if(temp->left)
        temp2 = temp->left;
    temp->left = temp->right;
    if(temp2)
        temp->right = temp2;
    else
        temp->right= 0;
}


texts:
I have these codes(.net framework 2.0):

    string commandText =
            "SELECT TOP(@maximumRows) * " +
            "FROM " +
            "( " +
                "SELECT *, ROW_NUMBER() OVER (ORDER BY " + sortExpression.Trim() + ") as rowNumber " +
                "FROM " +
                "( " +
                    "SELECT * FROM vw_RFQPartVendor " +
                    "WHERE Rec_date >= @requestDateFrom " +
                    "AND Rec_date <= @requestDateTo ";
    if (!string.IsNullOrEmpty(rfqNumber))
    {
        commandText += "AND Regno = @rfqNumber ";
    }
    if (!string.IsNullOrEmpty(partNumber))
    {
        commandText += "AND Partno = @partNumber ";
    }
    if (!string.IsNullOrEmpty(vendorCode))
    {
        commandText += "AND vendorCode = @vendorCode ";
    }
    commandText += ")as innerDerivedTable " +
")AS outerDerivedTable " +
"WHERE outerDerivedTable.rowNumber > @startRowIndex " +
"ORDER BY " + sortExpression.Trim();

The part WHERE Rec_date >= @requestDateFrom and Rec_date <= @requestDateTo is causing it to run slower, some noticeable seconds.

How can I optimize it to make it run faster?


texts:
I wanted to write an iterator that would split items up into groups, so i can bulk insert into mysql without crashing or overwhelming the server.

This is the implementation I came up with.
I am hoping that when yielding from the list its not creating a copy / clone of the list.
I need more experience with python internals to be able to debug / performance profile this method i wrote.

def iter_group(iterable, batch_size:int):
    iterable_type = type(iterable)
    length = len(iterable)
    start = batch_size*-1
    end = 0
    while(end < length):
        start += batch_size
        end += batch_size
        if iterable_type == list:
            yield (iterable[i] for i in range(start,min(length-1,end)))
        else:
            yield iterable[start:end]

#test data

items = range(0,10001)
for item_group in iter_group(items, 1000):
    for item in item_group:
        print(item,end=' ')