texts:
I'm really new to OpenCV. :) I have been working on this for almost an entire day. After hours of sleepless work I would like to know if I can further improve my code.
I have written some code to select only the black markings on the images. These black markings are child contours. Whilst my code is able to select some contours, it isn't accurate. You can see the code draws contours around the shadows along with black markings.
Code 1
At first I tried to use canny edge detection. But I was unable to overlay with the original image correctly.
import cv2
import numpy as np

image = cv2.imread('3.jpg')
image = cv2.resize(image, (500, 500))
image2 = image
cv2.waitKey(0)

# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Find Canny edges
edged = cv2.Canny(gray, 30, 200)
cv2.waitKey(0)

contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

cv2.imshow('Canny', edged)
cv2.waitKey(0)

# print("Number of Contours found = " + str(len(contours)))

cv2.drawContours(image2, contours, -1, (0, 255, 0), 3)

cv2.imshow('Contours', image2)
cv2.waitKey(0)
cv2.destroyAllWindows()

Code 2
I was able to improve on Code 1 to be far more accurate. You should be able to see that it now only selects half of the thumb, none of the other fingers and it doesn't select the indent on the background.
Additionally changing the background of the image also increases the accuracy of the result.
import cv2
import numpy as np

image = cv2.imread('3.jpg', 0)
image2 = cv2.imread('3.jpg')
image = cv2.resize(image, (500, 500))
image2 = cv2.resize(image2, (500, 500))
cv2.waitKey(0)

ret, thresh_basic = cv2.threshold(image, 100, 255, cv2.THRESH_BINARY)
cv2.imshow("Thresh basic", thresh_basic)

# Taking a matrix of size 5 as the kernel
kernel = np.ones((5, 5), np.uint8)

img_erosion = cv2.erode(thresh_basic, kernel, iterations=1)

#####################

ret, thresh_inv = cv2.threshold(img_erosion, 100, 255, cv2.THRESH_BINARY_INV)
cv2.imshow("INV", thresh_inv)
#####################

# Find Canny edges

edged = cv2.Canny(img_erosion, 30, 200)
cv2.waitKey(0)

contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

cv2.imshow('Canny', edged)
cv2.waitKey(0)

# print("Number of Contours found = " + str(len(contours)))
cv2.imshow('Original', image2)
cv2.drawContours(image2, contours, -1, (0, 255, 0), 3)

cv2.imshow('Contours', image2)
cv2.waitKey(0)
cv2.destroyAllWindows()

Can I improve my code further?


texts: Insert row into database using values from a html form submission

texts:
I have a comments page on my site and I was wondering if it is vulnerable to some sort of sql attack or something else. At the moment users can type what they want, they can even write a php script and it will upload to the database. Is this a problem and how can I fix it.
This is the script I use:
$name= $_POST['name'];
$email= $_POST['e_mailaddress'];

if(isset($_POST['comments']) AND $_POST['comments']!=''){
    $comments= $_POST['comments'];
    $comments_sent = 'true';

$dbcn = new connection();

$sql= "INSERT INTO contact (name, email, comments) VALUES (:name, :email, :comments);";

$query = $dbcn->dbconnect()->prepare($sql);

$results = $query->execute(array(
":name"=> $name,
":email"=> $email,
":comments"=> $comments
));
}


texts: Compute all permutations of a String (may have duplicate characters)

texts:
I was attempting to implement a java solution, the end result turned out to be slightly more verbose that I would have liked. Is it ok to use StringBuilder the way I have? I am more looking at improving it from a Data Structure and Algorithms standpoint rather than an OO standpoint although I do welcome remarks there as well. Looking forward to suggestions to improve.

Also, this might be unrelated but how to go about computing time and space complexity for something like this? I know permutations computing is n!, so is time complexity O(n.(n-1)!) since for each character I'm computing all permutations of the remaining ones and then inserting the current character in all possible positions. Space complexity seems like a set explosion to me.

A lot of the solutions posted on stackoverflow seem to be using String methods such as substring and charAt, would that be better than converting String to a charArray and going iteratively?

public class StringPermutations
{
    private final String toPermute;

    StringPermutations(String toPermute)
    {
        this.toPermute = toPermute;
    }

    public Set<String> findPermutations()
    {
        char[] chars = toPermute.toCharArray();
        if (chars.length == 1)
        {
            return Collections.singleton(String.valueOf(chars[0]));
        }

        int index = 0;

        // Idea is to take a single character of the string and insert the next character
        // at all possible positions (beginning or end). (a => ba,ab) Once we get a permutation of
        // 2 chars we can build a permutation of 3 chars by using similar logic.
        // Using a Set to ensure that it works even if the chars aren't unique.
        Set<String> permutations = new HashSet<>();
        permutations.add(String.valueOf(chars[index++]));
        while (index < chars.length)
        {
            permutations = iteratePerms(chars, index++, permutations);
        }
        return permutations;
    }

    private Set<String> iteratePerms(char[] chars, int index, Set<String> perms)
    {
        Set<String> finalPerm = new HashSet<>();
        for (String permutation : perms)
        {
            finalPerm.addAll(permute(chars[index], permutation));
        }
        return finalPerm;
    }

    private Set<String> permute(char toAdd, String current)
    {
        Set<String> perms = new HashSet<>();
        for (int i = 0; i < current.length() + 1; i++)
        {
            StringBuilder sb = new StringBuilder();

            int j = 0;
            for (j = 0; j < i; j++)
            {
                sb.append(current.charAt(j));
            }

            sb.append(toAdd);

            for (int k = j; k < current.length(); k++)
            {
                sb.append(current.charAt(k));
            }

            perms.add(sb.toString());
        }

        return perms;
    }

    public static void main(String[] args)
    {
        StringPermutations all = new StringPermutations("acab");
        Set<String> allPerms = all.findPermutations();
        System.out.println("The total no of permutations is:" + allPerms.size());
        for (String curPerm : allPerms)
        {
            System.out.println("cur perm:" + curPerm);
        }
    }
}


texts:
Can you think of a reason the following extension should not be used in production, or a better way of implementing it:

public extension Range {

    @warn_unused_result
    public func intersect(other: Range) -> Range {

        let ds = startIndex.distanceTo(other.startIndex)
        let de = startIndex.distanceTo(other.endIndex)

        let s = ds <= 0 ? startIndex : startIndex.advancedBy(ds, limit: endIndex)
        let e = de <= 0 ? startIndex : startIndex.advancedBy(de, limit: endIndex)

        return s..<e
    }
}

The method should pass the following assertions:

(5...7).intersect(9...9) == (8..<8) // ....|||.---..
(5...7).intersect(1...3) == (5..<5) // ....---.|||..

(5...7).intersect(8...9) == (8..<8) // ....|||---...
(5...7).intersect(1...4) == (5..<5) // ....---|||...

(5...7).intersect(7...9) == (7..<8) // ....||+--....
(5...7).intersect(1...5) == (5..<6) // ....--+||....

(5...7).intersect(6...9) == (6..<8) // ....|++-.....
(5...7).intersect(1...6) == (5..<7) // ....-++|.....

(5...7).intersect(6...6) == (6..<7) // ....|+|......
(5...7).intersect(4...8) == (5..<8) // ....-+++-....

Note the first four assertions with an empty intersection: the method is currently returning startIndex..<startIndex if the other range is on the "left", or endIndex..<endIndex if it is on the "right". Is this a reasonable behaviour?


texts:
I made this nice bit of code that I can insert into any of my projects requiring user input. It seems quite long for what it does and I would love some insight as to how I can do this more efficiently i.e. fewer lines of code.

I love to make my code elegant, but I don't see how to do this any better.

String x = (JOptionPane.showInputDialog(". Each parameter should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",");
int w = 0, a = 0, y = -1;
for(int i = 0; i < x.length(); i++)
{
    if(x.charAt(i) == ',')
    {
        w++;
    }
}
Double[] z = new Double[w];
for(int i = 0; i < x.length(); i++)
{
    if(x.charAt(i) == ',')
    {
        z[a] = Double.parseDouble(x.substring((y + 1), i));
        y = i;
        a++;
    }
}


texts:
This function checks these 6 fields for a user profile to determine if they have "completed" their profile. This just feels like it could be done better, but I can't figure how.

/**
 * Is the user's entire profile filled in?
 *
 * @return boolean
 */
public function isProfileComplete()
{
    $checkList = [
        $this->isAddressGiven(),
        $this->isGenderSelected(),
        null !== $this->getFirstName(),
        null !== $this->getLastName(),
        null !== $this->getJobTitle(),
        null !== $this->getAboutMe(),
    ];

    // If any one of the checks fails, profile is missing information
    foreach ($checkList as $checkItem) {
        if (!$checkItem) {
            return false;
        }
    }

    return true;
}


texts:
I have a module that builds swing tables based on an Object[][], then I have another module that queries an SQLite database and returns a ResultSet.

I have written a method that converts the ResultSet to an ArrayList<Object[]> first, then further into an Object[][]. The reason I do it this way is because you cannot get the row count from the ResultSet without iterating over it.

I'm wondering if there is a more efficient way to build my Object[][] from the ResultSet without having to iterate over the data twice.

Here is the method that performs the conversion:

public Object[][] executeQuery(String query) throws SQLException{
    ResultSet rs = getResultSet(query);
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int columnCount = rsMetaData.getColumnCount();
    ArrayList<Object[]> result = new ArrayList<Object[]>();
    Object[] header = new Object[columnCount];
    for (int i=1; i <= columnCount; ++i){
        Object label = rsMetaData.getColumnLabel(i);
        header[i-1] = label;
    }
    while (rs.next()){
        Object[] str = new Object[columnCount];
        for (int i=1; i <= columnCount; ++i){
            Object obj = rs.getObject(i);
            str[i-1] = obj;
        }
        result.add(str);
    }
    int resultLength = result.size();
    Object[][] finalResult = new Object[resultLength][columnCount];
    finalResult[0] = header;
    for(int i=1;i<resultLength;++i){
        Object[] row = result.get(i);
        finalResult[i] = row;
    }
    return finalResult;
}


texts:
I have multiple instances of an application (C# console apps) which needs to pick a set of records from a table and mark them (Update AllocatedTo with instance name), so that no other instances will pick those again. Below is my stored procedure.

CREATE PROCEDURE [wm_uc1].[GetAllocatedTickets]
@LoadGenName varchar(MAX)
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN TRANSACTION
            UPDATE [wm_uc1].[UK_HR_TicketProcessStatusMultiple] WITH (READCOMMITTEDLOCK) SET AllocatedTo = @LoadGenName
            WHERE LoadGenStatus = 'Pending' AND AllocatedTo = (SELECT MIN(AllocatedTo) FROM [UK_HR_TicketProcessStatusMultiple])
        COMMIT TRANSACTION
        SELECT * FROM [SE84GADB].[wm_uc1].[UK_HR_TicketProcessStatusMultiple] WHERE LoadGenStatus = 'Pending' AND AllocatedTo = @LoadGenName
    END TRY
    BEGIN CATCH
        ROLLBACK
    END CATCH
END

Note: AllocatedTo initially have a numeric value denoting the instance number. Once an instance picks it, AllocatedTo of that record is updated with the InstanceName. Each instance picks a set of records based on the minimum Instance number present in AllocatedTo column.

I have used lock so that no other instance picks the same record. Is this approach going to work or it needs some modification?

Please let me know for any clarification.


texts:
The task

is taken from leetcode

  TinyURL is a URL shortening service where you enter a URL such as
  https://leetcode.com/problems/design-tinyurl and it returns a short
  URL such as http://tinyurl.com/4e9iAk.

  Design the encode and decode methods for the TinyURL service. There is
  no restriction on how your encode/decode algorithm should work. You
  just need to ensure that a URL can be encoded to a tiny URL and the
  tiny URL can be decoded to the original URL.

My solution

const url = {};
const ALPHANUMERIC = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const PREFIX = 'http://tinyurl.com/';
/**
 * Encodes a URL to a shortened URL.
 *
 * @param {string} longUrl
 * @return {string}
 */
function encode(longUrl) {
  let id = createIdOfSize(6);
  while(url[id]) {
    id = createIdOfSize(6);
  }
  url[id] = longUrl;
  return PREFIX + id;
};

function createIdOfSize(n) {
  let i = n;
  let id = '';
  while(i-- > 0) {
    id += ALPHANUMERIC[(Math.random() * ALPHANUMERIC.length) | 0];
  }
  return id;
};
/**
 * Decodes a shortened URL to its original URL.
 *
 * @param {string} shortUrl
 * @return {string}
 */
function decode(shortUrl) {
  return url[shortUrl.split(PREFIX)[1]];
};

/**
 * Your functions will be called as such:
 * decode(encode(url));
 */


texts:
I have been working on a toggle script, but I find myself repeating my code.  Is there a way of combining it all?

jQuery(document).ready(function($) {
    var topContainer = $("#alles");
    var topButton = $(".abutton");
    topButton.click(function() {
        topContainer.slideToggle(1200, 'easeInOutQuart');
        $(".hideable").slideToggle(1200, 'easeInOutQuart');
    });

    var topContainer2 = $("#voorbeelden");
    var topButton2 = $(".bbutton");
    topButton2.click(function() {
        topContainer2.slideToggle(1200, 'easeInOutQuart');
        $(".hideable").slideToggle(1200, 'easeInOutQuart');
    });

    var topContainer3 = $("#contact");
    var topButton3 = $(".cbutton");
    topButton3.click(function() {
        topContainer3.slideToggle(1200, 'easeInOutQuart');
         $(".hideable").slideToggle(1200, 'easeInOutQuart');
    });
});
.container {
    display:block;
    width:500px;
    margin:0 auto;
}

.hideable {
 width: 500px;
 margin: 0 auto;
}

#alles {
    float:left;
    width:500px;
    height:500px;
    background:#ff4000;
}

#voorbeelden {
    float:left;
    width:500px;
    height:100px;
    border-top:1px solid #ddd;
    background:#cc6600;
}

#contact {
    float:left;
    width:500px;
    height:100px;
    border-top:1px solid #ddd;
    background:#bb3300;
}

.toggleable {
    display:none;
}

stuff

more stuff

a

     stuff

b

                    stuff

c

                    stuff


texts:
I am learning clojure and decided to start out by trying to write a solution to a fairly simple algorithm, reservoir sampling.  As I stated, I am learning clojure specifically and problem solving in a functional language in general.  Can someone please take a look at my code and critique it on it's "clojureness".  Am I using the right idiomatic conventions, is there a way that performs better (and why), formatting, anything really.

(defn sample-seq [size data]
  (loop [sample (transient (vec (take size data)))
         idx size
         data (drop size data)]
    (if (empty? data)
      (persistent! sample)
      (let [rand-num (rand-int idx)
            new-sample (if (< rand-num size)
                         (assoc! sample rand-num (first data))
                         sample)]
        (recur new-sample (inc idx) (rest data))))))
(println (sample-seq 4 [2.0, 4.0, 7.0, 6.0, 3.0, 8.0, 12.0, 9.0, 4.0, 1.0]))


texts:
I have a function that returns a ChromeDriver instance and logs browser information only once in a session:

from selenium import webdriver
def init_chromedriver(path, timeout=30, _l=[]):
    driver = webdriver.Chrome(executable_path=path)
    driver.set_page_load_timeout(timeout)
    if not _l:
        _l.append(None)
        logger = logging.getLogger('driver')
        for k, v in driver.capabilities.items():
            logger.log(logging.INFO, f"{k}: {v}")
    return driver

Is it a good practice or should I use another method?


texts:
I was surprised to learn that there are not many C++ Caesar ciphers on Code Review (3 others as of this question). And none that work in this fashion.

Here's the code:

// Caesar cipher

#include <iostream>

const char chars[] = {"abcdefghijklmnopqrstuvwxyz"};

// Find position in array
int findPosition(char x){
    int i;

    for(i = 0; i <= 25; i++){
        if(x == chars[i]){
            break;
        }
    }

    return i;

}

// Change char to next in array, loop back if at end
char nextChar(char x){
    if(findPosition(x) == 25){
        return chars[0];
    }

    return chars[findPosition(x) + 1];
}

// Rotate char desired amount
char rotChar(char x, int rotNum){
    for(int i = 1; i <= rotNum; i++){
        x = nextChar(x);
    }

    return x;
}

int main(){
    std::string str;
    std::getline(std::cin, str);

    std::cout << '\n';

    for(int i = 0; i <= 25; i++){
        std::cout << "ROT" << i << " - ";

        for(int k = 0; str[k] != '\0'; k++){
            std::cout << rotChar(str[k], i);
        }

        std::cout << '\n';
    }

    return 0;
}

This is a very simple Caesar cipher. It currently ignores anything uppercase or non-alphabetic.

Here's an example output:

ROT0 - helloworld
ROT1 - ifmmpxpsme
ROT2 - jgnnqyqtnf
ROT3 - khoorzruog
ROT4 - lippsasvph
ROT5 - mjqqtbtwqi
ROT6 - nkrrucuxrj
ROT7 - olssvdvysk
ROT8 - pmttwewztl
ROT9 - qnuuxfxaum
ROT10 - rovvygybvn
ROT11 - spwwzhzcwo
ROT12 - tqxxaiadxp
ROT13 - uryybjbeyq
ROT14 - vszzckcfzr
ROT15 - wtaadldgas
ROT16 - xubbemehbt
ROT17 - yvccfnficu
ROT18 - zwddgogjdv
ROT19 - axeehphkew
ROT20 - byffiqilfx
ROT21 - czggjrjmgy
ROT22 - dahhksknhz
ROT23 - ebiiltloia
ROT24 - fcjjmumpjb
ROT25 - gdkknvnqkc

How can this code be improved?


texts:
I have the following working code

import numpy as np
r = np.loadtxt('CoordUnwrapped/ParticleCoordU.5000',skiprows=9,usecols = (4,5,6))
rcom = np.loadtxt('hexaCOM/COMA/COMA.5000',skiprows=10,usecols = (4,5,6))
N = 50

Sx1= []
Sx2 = []
Sx3 = []
for i in range(0,N):
    S_data_1 = (r[i,0]-rcom[0,0])**2)
    S_data_2 = (r[i+N,0]-rcom[1,0])**2)
    S_data_3 = (r[i+2*N,0]-rcom[2,0])**2)
    Sx1.append(S_data_1)
    Sx2.append(S_data_2)
    Sx3.append(S_data_3)

data = np.array([Sx1,Sx2,Sx3])

x = np.average(data, axis=0)

The problem that I'm facing is that I am looking to obtain 400 Sx vectors and with this format it is not really feasible. Just to be clear this is a snapshot of what I am looking to get at the end:

N = 50

Sx1= []
Sx2 = []
Sx3 = []
.
.
.
Sx400 = []

for i in range(0,N):
    S_data_1 = (r[i,0]-rcom[0,0])**2)
    S_data_2 = (r[i+N,0]-rcom[1,0])**2)
    S_data_3 = (r[i+2*N,0]-rcom[2,0])**2)
    .
    .
    .
    S_data_400 = (r[i+399*N,0]-rcom[399,0]**2)
    Sx1.append(S_data_1)
    Sx2.append(S_data_2)
    Sx3.append(S_data_3)

data = np.array([Sx1,Sx2,Sx3,...,Sx400])

x = np.average(data, axis=0)

As you can see this approach is too time consuming and not efficient at all. Any suggestions would be great. Thank you!


texts: Manipulate urls with regular expressions instead of the slip approach

texts:
Basically I have an url which looks like this structurally speaking:

http://www.my-site.com/topic1/topic2/topic3/topic4/topic5

and I want to do 2 things to it:

1. check the structure and validate it
2. replace both topic3 and topic4 with a new parameters called topic6

This is my solution for now but I am interested to build something more optimize.

if ((url.match(/\//g) || []).length === 7) {
    const arr = url.split('/');
    const topic5 = arr.pop();
    arr.pop();
    arr.pop();
    arr.push('topic6', topic5);
    return arr.join('/');
}

So as you can see, for the fact that I am not very good at regular expressions I have used another approach which doesn't look that good. I basically check for the number of / in the string, if tey are 7 it means that the structure of the url is good and that on this type of url I should apply the next steps. After that I grab the last param of the url and also remove it and next after that I remove the last 2 parameters and add the new one instead along with the topic5.

In case you you have a better approach, please let me know. I think that it can be done by writing less number of lines of code but as I said, I am not very familiar with regular expressions.


texts: Converting an integer into the written form

texts:
For my homework assignment I have to create a class which converts an integer between 0 and 9999 into the written form. For example, 713 would be written as "seven hundred thirteen."

I wrote a few variations and I think I found the best approach. However, I was wondering if anyone had a moment to comment on my approach. Maybe point out subtle things I might not be taking advantage of.  Things like that.

I'll list just the important excerpts from the .cpp and .h files.

The following are all static members of the Numbers class:

const char* Numbers::lessThan20[] = {
  "zero",     "one",      "two",      "three",   "four",    "five",
  "six",      "seven",    "eight",    "nine",    "ten",     "eleven",
  "twelve",   "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
  "eighteen", "nineteen"
};
const char* Numbers::over19[] = {
  "",       "",      "twenty", "thirty", "fourty", "fifty", "sixty", "seventy",
  "eighty", "ninety"
};
const char* Numbers::hundred  = "hundred";
const char* Numbers::thousand = "thousand";

And this is my function to convert the number into a string:

std::string Numbers::print() const
{
  std::string text;
  int whole, remainder;

  remainder = this->number; // <- number is a member variable of the Numbers class

  whole = remainder / 1000;
  remainder %= 1000;

  if (whole > 0)
    text = text + lessThan20[whole] + " " + thousand + " ";

  whole = remainder / 100;
  remainder %= 100;

  if (whole > 0)
    text = text + lessThan20[whole] + " " + hundred + " ";

  if (remainder > 19)
  {
    whole = remainder / 10;
    remainder %= 10;
    text = text + over19[whole];
    if (remainder > 0)
      text = text + "-" + lessThan20[remainder];

  }
  else if (remainder > 0)
    text = text + lessThan20[remainder];

  return text;
}


texts: Scraper to deal with some complicated site with ads

texts:
I've written a script in Python in combination with Selenium to scrape data from a slightly complicated web page. When the web page is made to open, it comes up with an ad sitting on the data making the browser break unless it is kicked out or the scraper waits a certain time for the ad to disappear.

I have made the scraper remove it successfully and reach the data as i wanted to. Another problem was to click on the next page button which I've been able to do effectively as well. Now, it is working perfectly along with writing the scraped data in a CSV file. There are around 100 pages the website has traversed. Although it's a very small script to get reviewed, I suppose any clue to make it better might be useful for future reference.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
import csv

driver = webdriver.Chrome()
wait = WebDriverWait(driver,10)

driver.get("https://www.inc.com/inc5000/list/2017")

try:
    wait.until(EC.element_to_be_clickable((By.XPATH, "//span[.='SKIP']"))).click()
except TimeoutException: pass

outfile = open("inc.csv","w",newline='')
writer = csv.writer(outfile)
writer.writerow(["Rank","Company","Growth","Revenue","Industry"])

while True:
    for item in driver.find_elements_by_css_selector("#data-container .row"):
        rank = item.find_elements_by_css_selector(".rank")[0].text
        company = item.find_elements_by_css_selector(".company a")[0].text
        growth =item.find_elements_by_css_selector(".growth")[0].text
        revenue = item.find_elements_by_css_selector(".revenue")[0].text
        industry = item.find_elements_by_css_selector(".industry")[0].text
        writer.writerow([rank,company,growth,revenue,industry])
        print(rank,company,growth,revenue,industry)
    try:
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#arrow-r .fa-caret-right"))).click()
    except:break

driver.quit()


texts:
I have three observables:

var itemsManipulationStarted =
                Observable.FromEvent<ManipulationStartedEventArgs>(Items, "ManipulationStarted");

var pageManipulationDelta = Observable.FromEvent<ManipulationDeltaEventArgs>(this, "ManipulationDelta");

var pageManipulationCompleted =
                Observable.FromEvent<ManipulationCompletedEventArgs>(this, "ManipulationCompleted");

They are always called in that sequense: itemsManipulationStarted -> pageManipulationDelta -> pageManipulationCompleted

After every call to any observable I need to make some actions:

itemsManipulationStarted.Subscribe(e => Items.IsHitTestVisible = false);

pageManipulationDelta.SkipUntil(itemsManipulationStarted)
                     .Subscribe(e => e.EventArgs.Complete());

pageManipulationCompleted.SkipUntil(pageManipulationDelta)
                         .Subscribe(e => Items.IsHitTestVisible = true);

Is it clear or is there another way to write some "fluent" subscribing?


texts:
I'm currently using an Open Source FTP library in all my projects as I've never managed to code a decent FTP Helper Library based on the C# 4.0 API.

What do you think about this approach? I'm not quite versed in TDD but ideally I'd like to make this class as testable as possible.

public void DownloadFile(string host, string file, string user, string pass, string path)
{
    if (!String.IsNullOrWhiteSpace(host) && !String.IsNullOrWhiteSpace(file))
    {
        Uri addr = new Uri(host + file);

        using (WebClient client = new WebClient())
        {
            if (!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(pass))
            {
                client.Credentials = new NetworkCredential(user, pass);
            }

            if (!String.IsNullOrWhiteSpace(path))
            {
                client.DownloadFile(addr, path);
            }
        }
    }
}


texts:
A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

class Solution:
# @param num, a list of integer
# @return an integer
def findPeakElement(self, num):
    if len(num)==0: return None
    if len(num)==1: return 0
    return self.findPeakHelper(num,0,len(num)-1)
def findPeakHelper(self,num,start,end):
    mid = (start+end)/2
    if mid>start and mid < end:
        if(num[mid-1]<num[mid] and num[mid]>num[mid+1]):
            return mid
        if(num[mid-1]>num[mid]):
            return self.findPeakHelper(num,start,mid)
        else:
            return self.findPeakHelper(num,mid,end)
    else:
        if num[mid]>num[mid+1]:
            return mid
        else:return mid+1


texts: Decompose any number to its prime factors raised to their respective powers

texts:
A simple code which takes the given number as input and gives all of its prime factors raised to their respective powers...works well upto 106 after that it slows down greatly for some numbers..but works smoothly if the numbers don't have many prime factors

Here's the code:

x=int(input("Enter number:"))
c=[]    #load the exponential powers here
b=[]    #load the primes here
i,k,f=0,0,2
l=100
def primes(i,n):            #returns all primes between i and n
    primes = []
    for possiblePrime in range(i,n+1):
        isPrime = True
        for num in range(2, int(possiblePrime ** 0.5) + 1):
            if possiblePrime % num == 0:
                isPrime = False
                break
        if isPrime:
            primes.append(possiblePrime)
    return(primes)

while x!=1:
    try:
        while x%b[k]==0:            #extract every prime from the number and store their resp exp powers
            i+=1                    #counts the power of the prime stored in b[k]
            x=x//b[k]               #Removes the prime number from the given number
        k+=1
        c.append(i)
        i=0
    except IndexError:              #if list of primes are not enough...add more of them
            b=b+primes(f,l)
            l+=10000

print("Prime Numbers:    ",[b[i] for i in range(len(c)) if c[i]!=0])   #prints the primes
c=[c[i] for i in range(len(c)) if c[i]!=0]
print("Respective Powers: ",c)                                          #prints their respective powers

Sample Output: (I just took a random number)

  Enter number: 23412
  Prime Numbers: [2, 3, 1951]
  Respective Powers: [2, 1, 1]

This means  23412 = 22 × 31 × 19511

Also, all optimizations and improvements or suggestions are welcome.


texts:
Below is my app's start/stop procedure, start/stop code is handled by a single-threaded ThreadPoolExecutor, so I'm guaranteed there's only one thread can be active at the same time.
I'm asking about isRunning variable. Is making the variable volatile enough?
The variable will be accessed (read/modify) from different threads (but only one at the same time!)
public final class Work {

    private static final ThreadPoolExecutor processor = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1),
            new ThreadPoolExecutor.DiscardPolicy());
    private static final Runnable startQuery = Work::startProcedure,
            stopQuery = Work::stopProcedure;

    private static boolean isRunning = false;

    private Work() {}

    private static void startProcedure() {
        isRunning = true;
        //<some code>
    }

    private static void stopProcedure() {
        //<some code>
        isRunning = false;
    }

    //------Public API

    public static void start() {
        processor.execute(startQuery);
    }

    public static void stop() {
        processor.execute(stopQuery);
    }

}


texts:
From https://stackoverflow.com/a/257382/6949852
I learned how to check whether a member function exists, then I re-write it to standardize the codes:

Now the codes become:

#include <type_traits>
#include <iostream>

struct A  //has hello
{
  void hello() {}
};

struct B {}; //no hello

template<typename T>
struct has_hello
{
private:
  using yes = char;
  using no = long;
  template<typename C>
  static yes has(decltype(&C::hello));
  template<typename C>
  static no has(...);
public:
  enum name : bool {value = std::is_same<decltype(has<T>(nullptr)), yes>::value};
};

int main()
{
  std::cout << static_cast<std::underlying_type<has_hello<A>::name>::type>(has_hello<A>::value) << std::endl;
  std::cout << static_cast<std::underlying_type<has_hello<B>::name>::type>(has_hello<B>::value) << std::endl;
}

Compared to original codes:

0 -> nullptr
enum -> enum name : type
sizeof -> is_same
typeof -> decltype


texts: Recursively find all objects of type System.Web.UI.Pair in an object array

texts:
I have an object array that contains various types of objects (primitives, strings, other object arrays) at arbitrary levels of nesting.  I need to pull all objects of type System.Web.UI.Pair from this array and am having a heck of a time writing the method.  This is especially difficult because the Pair class itself can contain other Pairs or enumerable of Pairs.

A picture is worth a thousand words:

(Original URL: http://postimage.org/image/i7fuad3b9/)

Here's the method I came up with, but it feels inelegant and incomplete.  Any improvements, especially ones that can leverage LINQ are welcome.

   public static IEnumerable<Pair> Flatten(this object root, List<Pair> list)
    {
        if (root == null)
        {
            return list;
        }
        if (root is Pair)
        {
            var pair = root as Pair;
            list.Add(pair);
            if (pair.First is IEnumerable)
            {
                Flatten((root as Pair).First, list);
            }
            else if (pair.First is Pair)
            {
                list.Add(pair.First as Pair);
            }
            if (pair.Second is IEnumerable)
            {
                Flatten((root as Pair).Second, list);
            }
            else if (pair.Second is Pair)
            {
                list.Add(pair.Second as Pair);
            }
        }
        if (root.GetType().IsArray || root is IEnumerable)
        {
            foreach (object o in (IEnumerable) root)
            {
                Flatten(o, list);
            }
        }
        return list;
    }


texts: NullGuard for throwing more informative exceptions

texts:
This small utility class is my solution for a more convenient way for checking against null. I also wanted to have more informative NullReferenceExceptions but I didn't want to pollute my code with null checks everywhere.
static class NullGuard
{
    public static T Check<T>(Expression<Func<T>> expr) where T : class
    {
        T value = expr.Compile()();
        if (value == null)
        {
            var message = CreateMessage(expr.Body);
            throw new NullReferenceException(message);
        }
        return value;
    }

    private static string CreateMessage(Expression expr)
    {
        return CreateMessage(expr as MemberExpression) ?? CreateMessage(expr as MethodCallExpression);
    }

    private static string CreateMessage(MemberExpression expr)
    {
        if (expr == null)
        {
            return null;
        }

        string instanceName = null;

        var constantExpression = expr.Expression as ConstantExpression;
        if(constantExpression != null)
        {
            instanceName = "this";
        }

        var memberExpression = expr.Expression as MemberExpression;
        if (memberExpression != null)
        {
            instanceName = memberExpression.Member.Name;
        }

        return CreateMessage(expr.Member.Name, expr.Member.MemberType.ToString(), instanceName);
    }

    private static string CreateMessage(MethodCallExpression expr)
    {
        string instanceName = null;
        var newExpression = expr.Object as NewExpression;
        if (newExpression != null)
        {
            instanceName = "new " + newExpression.Constructor.DeclaringType.Name;
        }

        var constantExpression = expr.Object as ConstantExpression;
        if (constantExpression != null)
        {
            instanceName = "this";
        }

        var memberExpression = expr.Object as MemberExpression;
        if (memberExpression != null)
        {
            instanceName = memberExpression.Member.Name;
        }
        return expr == null ? null : CreateMessage(expr.Method.Name, expr.Method.MemberType.ToString(), instanceName);
    }

    private static string CreateMessage(string memberName, string memberType, string declaringType)
    {
        var message = string.Format(
            "{0}.{1} (Instance.{2})",
            declaringType,
            memberName,
            memberType);
        return message;
    }
}

Its usage should be just on single methods or properties that must not be null but if they are, I want to know exactly where the null occurred:
class Foo
{
    public string Bar { get; set; }
    public string Baz() { return null; }
}

void Main()
{
    string abc = null;
    var foo = new Foo();

    //NullGuard.Check(() => abc);
    //NullGuard.Check(() => foo.Bar);
    //NullGuard.Check(() => foo.Baz());
    //NullGuard.Check(() => new Foo().Baz());
    NullGuard.Check(() => qux());
}

string qux() { return null; }

Result:

foo.Bar (Instance.Method)
foo.Baz (Instance.Property)
this.qux (Instance.Property)


texts:
At first I calculate the total of each data then give each data of data a percentage base on total. The percentage is calculated by adding its percentage and sum of all percentage before it. I then calculate a new value by multiplying percentage and total. I finally sort them from largest to smallest.

How can I reduce the number of .each loops?

var data= [
    {
        "data": [
            {
                "value": "5700",
                "color": "#1ca2d5",
                "label": "Shortlisted"
            },
            {
                "value": "2570",
                "color": "#ed5d67",
                "label": "Interviewed"
            },
            {
                "value": "1054",
                "color": "#66BB6A",
                "label": "Finallisted"
            }
        ],
        "under": "Top"
    },
{
    "data": [
        {
            "value": "2847",
            "color": "#1ca2d5",
            "label": "Shortlisted"
        },
        {
            "value": "3541",
            "color": "#ed5d67",
            "label": "Interviewed"
        },
        {
            "value": "1486",
            "color": "#66BB6A",
            "label": "Finallisted"
        }
    ],
    "under": "Mid"
},
{
    "data": [
        {
            "value": "16900",
            "color": "#1ca2d5",
            "label": "Shortlisted"
        },
        {
            "value": "12900",
            "color": "#ed5d67",
            "label": "Interviewed"
        },
        {
            "value": "5780",
            "color": "#66BB6A",
            "label": "Finallisted"
        }
    ],
    "under": "Dhsanullah University of Science and Technology"
},
{
    "data": [
        {
            "value": "5700",
            "color": "#1ca2d5",
            "label": "Shortlisted"
        },
        {
            "value": "2570",
            "color": "#ed5d67",
            "label": "Interviewed"
        },
        {
            "value": "1054",
            "color": "#66BB6A",
            "label": "Finallisted"
        }
    ],
    "under": "TTop"
},
    {
        "data": [
           {
               "value": "5700",
               "color": "#1ca2d5",
               "label": "Shortlisted"
           },
           {
               "value": "2570",
               "color": "#ed5d67",
               "label": "Interviewed"
           },
           {
               "value": "1054",
               "color": "#66BB6A",
               "label": "Finallisted"
           }
        ],
        "under": "Tcop"
    }
];

var tempData=[];
$.each(data, function (i, d) {
            var total = 0;
            $.each(d.data, function (j, obj) {
                total += parseInt(obj.value);
            });
            d["total"] = total.toString();
        });

        $.each(data, function (i, d) {
            var percentage = 0;
            $.each(d.data, function (j, obj) {
                obj["original"] = obj.value;
                var per = (parseInt(obj.value) * 100) / parseInt(d.total);
                percentage += per;
                obj["percentage"] = per;
                obj.value = (parseInt(d.total) * percentage) / 100;
                obj["under"] = d.under;
            });

        });
        $.each(data, function (i, d) {
            d.data.sort(function (a, b) { return b.value - a.value; });
            $.each(d.data, function (j, obj) {
                tempData.push(obj);
            });
        });


texts: Building a list of dates between two dates

texts:
My solution to this feels 'icky' and I've got calendar math falling out of my ears after working on similar problems for a week so I can't think straight about this.

Is there a better way to code this?

import datetime
from dateutil.relativedelta import relativedelta

def date_count(start, end, day_of_month=1):
    """
    Return a list of datetime.date objects that lie in-between start and end.

    The first element of the returned list will always be start and the last
    element in the returned list will always be:
        datetime.date(end.year, end.month, day_of_month)

    If start.day is equal to day_of_month the second element will be:
        start + 1 month

    If start.day is after day_of_month then the second element will be:
        the day_of_month in the next month

    If start.day is before day_of_month then the second element will be:
        datetime.date(start.year, start.month, day_of_month)

    >>> start = datetime.date(2012, 1, 15)
    >>> end = datetime.date(2012, 4, 1)
    >>> date_count(start, end, day_of_month=1) #doctest: +NORMALIZE_WHITESPACE
    [datetime.date(2012, 1, 15), datetime.date(2012, 2, 1),
    datetime.date(2012, 3, 1), datetime.date(2012, 4, 1)]

    Notice that it's not a full month between the first two elements in the
    list.

    If you have a start day before day_of_month:
    >>> start = datetime.date(2012, 1, 10)
    >>> end = datetime.date(2012, 4, 1)
    >>> date_count(start, end, day_of_month=15) #doctest: +NORMALIZE_WHITESPACE
    [datetime.date(2012, 1, 10), datetime.date(2012, 1, 15),
    datetime.date(2012, 2, 15), datetime.date(2012, 3, 15),
    datetime.date(2012, 4, 15)]

    Notice that it's not a full month between the first two elements in the
    list and that the last day is rounded to
    datetime.date(end.year, end.month, day_of_month)
    """
    last_element = datetime.date(end.year, end.month, day_of_month)

    if start.day == day_of_month:
        second_element = start + relativedelta(start, months=+1)
    elif start.day > day_of_month:
        _ = datetime.date(start.year, start.month, day_of_month)
        second_element = _ + relativedelta(_, months=+1)
    else:
        second_element = datetime.date(start.year, start.month, day_of_month)

    dates = [start, second_element]

    if last_element <= second_element:
        return dates

    while dates[-1] < last_element:
        next_date = dates[-1] + relativedelta(dates[-1], months=+1)
        next_date = datetime.date(next_date.year, next_date.month, day_of_month)
        dates.append(next_date)
    dates.pop()

    dates.append(last_element)

    return dates


texts: A/B testing using chi-square to calculate the significance in an elegant way

texts:
The definition of ABtest

Goal:

For input data, each pair row is a group such as 0 and 1, 2 and 3. I want to test whether each group is significant using chi-square.

If result is significant and any value in group is more than or equals 5 , it returns p-value, else it returns 'not significant'.
If any value in group is less than 5, it returns 'sample size too small'.

My question is:

My code seems so long and not so elegant and want to be more simple.

Notice: please don't use column grp as raw input to rewrite like groupby method because the raw data is not named a1 ca1, b1 cb1 . But I make sure each pair row (e.g. 0 and 1, 2 and 3) is a group.

Code:

import numpy as np
from scipy.stats import chi2_contingency
from itertools import chain, repeat

def abtest(df,tot,convert):
    df = df.copy()
    df['nonconvert'] = df[tot] - df[convert]
    grp = np.split(df.index.values,df.index.size//2)
    rst = []
    for g in grp:
        obs = df.loc[g][[convert,'nonconvert']].values
        if (obs>=5).all():
             _, p, _, _=chi2_contingency(obs)
             if p<0.05:
                rst.append(p)
             else:
                rst.append('not significant')
        else:
            rst.append('sample size too small')
    rate = tot + '_' + convert + '_'+'test'
    df[rate] = list(chain.from_iterable(zip(*repeat(rst, 2))))
    del df['nonconvert']
    return df

df = abtest(df=df,tot='tot',convert='read')
df = abtest(df=df,tot='tot',convert='lgn')
df = abtest(df=df,tot='lgn',convert='read')

Input:

   grp    tot  lgn  read
0   a1   6300  360    30
1  ca1   2300   60     7
2   b1  26300  148     6
3  cb1  10501   15     3
4   c1  74600   36     2
5  cc1  26000    6     1

Output:

   grp    tot  lgn  read          tot_read_test     tot_lgn_test  \
0   a1   6300  360    30        not significant      4.68208e-09
1  ca1   2300   60     7        not significant      4.68208e-09
2   b1  26300  148     6  sample size too small      7.01275e-08
3  cb1  10501   15     3  sample size too small      7.01275e-08
4   c1  74600   36     2  sample size too small  not significant
5  cc1  26000    6     1  sample size too small  not significant

           lgn_read_test
0        not significant
1        not significant
2  sample size too small
3  sample size too small
4  sample size too small
5  sample size too small


texts: Validating user-provided control points for a Bézier curve

texts:
I have made some code which will validate user input for getting 4 control points for a bezier curve. It works fine however I was just wondering If I could make this code any more compact or efficient?

p = [] #empty points array

#gets 4 control points from user input
def get_points():
    #loops through 4 times to get 4 control points
    points = ["Start Point(P0)", "Control Point 1(P1)", "Control Point 2(P2)", "End Point(P3)"]
    for i in range(4):
        while True:
            #user input
            p_input = input("Enter X,Y Coordinates for "+ points[i]+":")
            #splits the string into x and y coordinates
            p_components = p_input.split(',')
            #checks to see if user hasnt entered two coordinates
            if len(p_components) != 2:
                print("Missing coordinate please try again.")
                p_input = input("Enter X,Y Coordinates for "+ points[i]+":")
                p_components = p_input.split(',')
            #checks to see if the values can not be converted into floats
            try:
                x = float(p_components[0])
                y = float(p_components[1])
            except ValueError:
                print("Invalid coordinates", p_components, "please try again.")
            else:
                #makes sure user is not entering coordinates that will not appear on the screen.
                if(x > 1020 or x < 10) or (y > 760 or y < 10):
                    print("Invalid coordinates, please try again.")
                else:
                    #appends the x and y coordinates as a 2 dimensional array
                    p.append([float(p_components[0]), float(p_components[1])])
                    break


texts: Finding the most common section from the visible cells in a collection view

texts:
My goal is to determine, of all of the currently visible cells in a collection view, which section has the most visible cells.

Start by getting the index paths for the visible cells:

let visible = collectionView.indexPathsForVisibleItems // [IndexPath]

Originally I used an NSCountedSet followed by mapping and sorting.

let counted = NSCountedSet(array: visible.map { $0.section })
let section = counted.allObjects.map { ($0, counted.count(for: $0)) }.sorted { $0.1 > $1.1 }.first?.0 as? Int

This works but I don't like NSCountedSet because it deals with Any.

I then replaced the use of NSCountedSet with reduce by reducing the visible array into a dictionary and then using a similar map and sort.

let counted = visible.reduce([Int: Int]()) { (result, path) -> [Int: Int] in
    var updated = result
    updated[path.section, default: 0] += 1
    return updated
}
let section = counted.keys.map { ($0, counted[$0]!) }.sorted { $0.1 > $1.1 }.first?.0

This works as well but I'm hoping there are ways to improve this.

Two main questions:

Can the reduce closure be improved? Is there a better way to return the updated dictionary where the keys are section and the values are the count?
Once I have the dictionary of sections and counts, is there a better way to find the section with the highest count? Is there something better than mapping to a tuple, sorting those tuples, and finally grabbing the first one?

BTW - If there is a tie for highest count, I don't care which of those sections is returned.


texts:
I want to send an email just once per day.  There is one button and any user can click that button.  The email must not be sent twice.  When the first user clicks the button, the email is sent.  If some other user clicks the button, the email will not be sent again.

This is how I implemented, and it's working.  There are some cases, once a month, when 2 email are sent, but I don't know why.

I am sure that there is more elegant way to resolve this problem.  Please share with me your ideas.

protected void Send(string email, String allRecipients, String subject, String body)
{
    //Be sure that email is send just once:
    //Lock an object, and if its already locked just continue,
    if (Monitor.TryEnter(syncLock))
    {
        try
        {
            //Send email only if is not send already.
            //Check in DB if is send.
            //IsSend function return true if email is send already, else false.
            if (!IsSent())
            {
                SendEmails(email, allRecipients, subject, body);
            }
        }
        finally
        {
            Monitor.Exit(syncLock);
        }
    }
}

Function that sends email:

public static void SendEmails(string email, String allRecipients, String subject, String body)
{
    //Flag if email is sent or not:
    Boolean isEmailSend = false;

    SmtpClient client = new SmtpClient();
    //Message:
    MailMessage message = new MailMessage(email, allRecipients, subject, body);
    try
    {
        isEmailSend = true;
        client.Send(message);

    }
    catch (SmtpException e)
    {
        isEmailSend = false;
        throw new SmtpException(e.ToString());
    }
    catch (TimeoutException e)
    {
        //Problem: Not sure if is email send or not:
        isEmailSend = false;
        throw new TimeoutException("TIME OUT:" + e.ToString());
    }
    catch (Exception e)
    {
        //Problem: Not sure if is email send or not:
        isEmailSend = false;
        throw new Exception(e.ToString());
    }
    finally
    {
        if (isEmailSend)
        {
            //Update DB.
            //Set that email is send.
            //This update in DB that email for current day is send already.
            SetAsSend();
        }
    }
}

IsSent function

    //Check if meeting is sent today.
    public static bool IsSent()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
        bool isSent = false;

        const string CHECK_IF_SEND = "SELECT TOP 1 IsSent FROM MessageTable m WHERE m.date =@todayDate ";

        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(CHECK_IF_SEND, conn);
        command.Parameters.Add("@todayDate", DbType.Date).Value = DateTime.Today;

        try
        {
            conn.Open();
            Object result = command.ExecuteScalar();
            if (result != null)
            {
                isSent = (bool)result;
            }
        }
        finally
        {
            conn.Close();
            conn.Dispose();
        }
        return isSent;
    }


texts: How to better indent multiline strings with many string formatting args?

texts:
I have a function, that is used in flask, for logging application errors:

    def log_exception(self, exc_info):
        self.logger.error('''
Time:                 %s
Path:                 %s
HTTP Method:          %s
POST_ARGS:            %s
GET_ARGS:             %s
Client IP Address:    %s
User Agent:           %s
User Platform:        %s
User Browser:         %s
User Browser Version: %s
Username:             %s
Email:                %s''' % (
               datetime.now(),
               request.path,
               request.method,
               request.form,
               request.args,
               request.remote_addr,
               request.user_agent.string,
               request.user_agent.platform,
               request.user_agent.browser,
               request.user_agent.version,
               current_user,
               getattr(current_user, 'email', 'no email'),
        ), exc_info=exc_info)

As you can see the indentation is quite ugly and the long list of formatting args makes it even worse.

Using textwrap.dedent helped the situation, but the formatting args is still problematic:

def log_exception(self, exc_info):
    self.logger.error(
        dedent('''Time:                 %s
                  Path:                 %s
                  HTTP Method:          %s
                  POST_ARGS:            %s
                  GET_ARGS:             %s
                  Client IP Address:    %s
                  User Agent:           %s
                  User Platform:        %s
                  User Browser:         %s
                  User Browser Version: %s
                  Username:             %s
                  Email:                %s''') % (datetime.now(),
                                                  request.path,
                                                  request.method,
                                                  request.form,
                                                  request.args,
                                                  request.remote_addr,
                                                  request.user_agent.string,
                                                  request.user_agent.platform,
                                                  request.user_agent.browser,
                                                  request.user_agent.version,
                                                  current_user,
                                                  getattr(current_user, 'email', 'no email')),
          exc_info=exc_info
    )

Is this the best I can do?


texts:
I made a simple mp3 player that plays, pauses and stops a given song, shows the time elapsed, and has a volume control.  I read the documentation and can't figure out the difference between the pause and stop methods, although I have configured them to work as I want (i.e., pause lets you resume from where you left off while stop resets the track).

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var player:AVAudioPlayer = AVAudioPlayer()
    var musicPlaying = false
    var timer:NSTimer!

    @IBOutlet weak var currentTime: UILabel!
    @IBOutlet weak var sliderValue: UISlider!

    override func viewDidLoad() {
        super.viewDidLoad()
        let audioPath = NSBundle.mainBundle().pathForResource("bach", ofType: "mp3")!
        do {
            try player = AVAudioPlayer(contentsOfURL: NSURL(string: audioPath)!)
        } catch let error as NSError {
            print(error)
        }
    }

    @IBAction func play(sender: AnyObject) {
        if musicPlaying {
            player.pause()
            musicPlaying = false
        } else {
            player.play()
            musicPlaying = true
            timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateTime", userInfo: nil, repeats: true)
        }
    }

    @IBAction func stop(sender: AnyObject) {
        player.stop()
        musicPlaying = false
        player.currentTime = 0
    }

    func updateTime() {
        let timePlayed = player.currentTime
        let minutes = Int(timePlayed / 60)
        let seconds = Int(timePlayed % 60)
        currentTime.text = NSString(format:"%02d:%02d", minutes, seconds) as String
    }

    @IBAction func sliderChanged(sender: AnyObject) {
        player.volume = sliderValue.value
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}


texts: Ruby on rails action code could be shorter

texts:
So I have this code that i use for addition of funds to a certain item.

def addFund
    fund=params[:fund]

    if(fund.to_i>0)
      @fund=fund
      if(@item.fund+fund.to_f>@item.price) #the fund added should be less than price-current fudn
        respond_to do |format|

         format.html { redirect_to @item, error: 'Fund amount should not exceed price difference' }
         format.json {render :json =>{:status =>0,
          :error=>"Fund amount cannot be greater than price difference  "}}
        end
        else
          #Finally do the addition
          @item.fund=@item.fund+fund.to_f
          @item.save
         respond_to do |format|

         format.html { redirect_to @item, success: 'Fund  added' }
         format.json {render :json =>{:status =>1,
          :error=>"Done"}}
        end
      end
    else
       respond_to do |format|
         format.html { redirect_to @item, error: 'No money specified.' }
         format.json {render :json =>{:status =>0,
          :error=>"Money not specified"}}
        end
    end

  end

So this is how it works:

First we check if the fund(POST ParameteR) is non zero fund.to_i>0 and respond accordingly giving an error message if it isn't

@item.fund = the current funding the item has

@item.price =  the price of item

fund = the fund to be added(POST)

fund must be less than @item.price-@item.fund  since there is no point in accepting funds greater than the price, the item can already be bought

Then  finally if all this works, then we add the funds to the item and show him a message.

So that's pretty much it. I am thinking there has to be a way of clubbing the responses and replying at one time. I have no idea how respond_to actually works. Ruby has blocks that you won't find in java or C++ or PHP


texts: Sorting an array of jobs by various criteria

texts:
Below is my current code for sorting an array, "$jobs_list".

It's not very DRY and it's fugly. And there are several more similar case statements still to go in. How could I write it so my brain doesn't twitch to look at it?

switch ($sort) {
    case 'number':
        usort($jobs_list, function($a, $b){
            return ( (int) $a->number > (int) $b->number );
        });
        break;
    case 'client':
        usort($jobs_list, function($a, $b){
            return strcmp($a->client_contact_last_name, $b->client_contact_last_name);
        });
        break;
    case 'name':
        usort($jobs_list, function($a, $b){
            return strcmp($a->name, $b->name);
        });
        break;
    case 'status':
        usort($jobs_list, function($a, $b){
            return ( (int) $a->status > (int) $b->status );
        });
        break;
    case 'revenue':
        usort($jobs_list, function($a, $b){
            return ( (float) $a->base_revenue > (float) $b->base_revenue );
        });
        break;
    case 'profit':
        usort($jobs_list, function($a, $b){
            return ( (float) $a->profit > (float) $b->profit );
        });
        break;
    case 'margin':
        usort($jobs_list, function($a, $b){
            return ( (float) $a->margin > (float) $b->margin );
        });
        break;

    default:
        # do nothing...
}


texts: The code is used to add the digits in a digital clock to each other. I duplicated code and could use some help DRYing it out

texts:
I'm using Codefights to improve my skills. This challenge is to change the number submitted as total minutes into the digital read out on a clock i.e. hh:mm and then add all the numbers to together. So h + h + m + m.

My code works and I've passed all the tests, but it duplicates the same process for variables I've named number and float. What are some ways I can clean this up? At the bottom of the code I put the tests with the correct answers commented out next to them.

def lateRide(n)
  n = n.to_f
  n = n/60
  float = n % 1
  number = n - float
  number = number.to_i

  float = float * 60
  float = float.round.to_i

  if number > 9
    tens = number/10
    ones = number-(tens*10)
  else
    tens = 0
    ones = number
  end

  if float > 9
    ftens = float/10
    fones = float-(ftens*10)
  else
    ftens = 0
    fones = float
  end
  tens + ones + ftens + fones
end

puts lateRide(240) #4
puts lateRide(808) #14
puts lateRide(1439) #19
puts lateRide(0) #0
puts lateRide(23) #5
puts lateRide(8) #8


texts: Chromium based browser and Firefox omnibox: paste/type search keywords to go straight to google.com search results

texts:
Functions and features: paste/type search keywords to go straight to google.com search results pages - explicitly google.com NO google.TLD

chrome.webRequest.onBeforeRequest.addListener(
function (details) {
var requestURL = details.url;
var re = new RegExp('^(http(?:s)?):\/\/www\.google\.(?:(?!com\/)[a-z]+\.?[a-
z]+)?/', 'gi');
return {
  redirectUrl: requestURL.replace(re, '$1://www.google.com/')
};
},
{urls: ['<all_urls>']},
['blocking']
);

Extension metadata

{
  "name": "__MSG_appName__",
  "description": "__MSG_appDescription__",
  "version": "1.0.0.0",
  "manifest_version": 2,
  "default_locale": "en",
  "icons": {
    "128": "icon.png"
  },
  "homepage_url": "https://",
  "background": {
    "scripts": [
      "omnibox-ncr.js"
    ]
  },
  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "*://www.google.*/*"
  ]
}

Concerns

Performance and efficiency
Functionality
Does it effectively keep searches at google.com NOT google.TLD (without setting your google.TLD
cookie)?


texts: Method to close a lot of closeable objects

texts:
I wrote a method that closes 3 closeable types:

java.sql.Connection
java.sql.PreparedStatement
java.sql.ResultSet

   public static void closeAll(final Connection connection,
                            final PreparedStatement statement,
                            final ResultSet rs)
         throws SQLException
   {
      try
      {
         if (rs != null)
         {
            rs.close();
         }
      }
      finally
      {
         try
         {
            if (statement != null)
            {
               statement.close();
            }
         }
         finally
         {
            if (connection != null)
            {
               connection.close();
            }
         }
      }
   }

Is there a way to simplify it in Java 6?

In Java 7 I can use an AutoCloseable interface:

   public static void closeAll(final AutoCloseable ... closeables)
   {
      if (closeables != null && closeables.length > 0)
      {
         for (final AutoCloseable closeable: closeables)
         {
            try
            {
               closeable.close();
            }
            catch (final Exception ex)
            {
               // log it
            }
         }
      }
   }

Is this a better solution?


texts: Keep asking the user [after performing an action] until they wish to stop

texts:
I have a form that requires the user to select photos to be included in their portfolio before they can proceed to use the app for the first time.

I don't want to spend the rest of my life implementing a custom file browser, so I've decided to just use the FolderBrowserDialog to allow them to select a folder containing photos. I've also decided to let them browse as many times as they need in case they have photos scattered in other locations.

I can't think of a better way to write this, but it seems like there would be a better way. I'd appreciate any thoughts/suggestions on how to improve this piece or advice on a better way to write it:

    private void Main_Shown(object sender, EventArgs e)
    {
        /* Let them select photos to be included in the portfolio
         * and move them to the permanent Photo Collection folder,
         * and display them on the form.
         */

        bool selectingPhotos = true;

        while (selectingPhotos) {
            using (FolderBrowserDialog folderPicker = new FolderBrowserDialog())
            {
                folderPicker.Description = "Please browse to, and select the folder containing the files you'd like to add.";

                if (folderPicker.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    // Add files to list for processing later.

                    // Ask if they want to add more files from another directory.
                    if (MessageBox.Show("Do you want to select more photos from another location?", "Confirmation", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        selectingPhotos = true;
                    }
                    else
                    {
                        selectingPhotos = false;
                    }
                }
                else
                {
                    selectingPhotos = false;
                }
            }
        }
    }


texts: Generating Unique Subsets using Bitmasking

texts:
Given an array arr[] of integers of size N that might contain duplicates, the task is to find all possible unique subsets.
Link to the judge: LINK
Note: Each subset should be sorted.
Example 1:
Input: N = 3, arr[] = {2,1,2}
Output:(),(1),(1 2),(1 2 2),(2),(2 2)
Explanation:
All possible subsets = (),(2),(1),(1,2),(2),(2,2),(2,1),(2,1,2)
After Sorting each subset = (),(2),(1),(1,2),(2),(2,2),(1,2),(1,2,2)
Unique Susbsets in Lexicographical order = (),(1),(1,2),(1,2,2),(2),(2,2)

Example 2:
Input: N = 4, arr[] = {1,2,3,3}
Output: (),(1),(1 2),(1 2 3)
(1 2 3 3),(1 3),(1 3 3),(2),(2 3)
(2 3 3),(3),(3 3)

My correct and working code:
class Solution:

    def checkSetBits(self,num,arr):
        pos = 0
        res = []

        while num != 0:
            if num & 1 == 1:
                res.append(arr[pos])
            pos += 1
            num = num >> 1
        return res

    def AllSubsets(self, arr,n):
        arr = sorted(arr)
        ans = []
        N = 2**len(arr)

        for i in range(N):
            item = self.checkSetBits(i,arr)
            ans.append(item)

        # removing duplicate lists
        ans = sorted(ans)
        i = len(ans)-1

        while i > -1:
            if ans[i] == ans[i-1]:
                ans.pop(i)
            i -= 1

        return ans

My doubt :
The required time complexity is \$O(2^N)\$ however according to me, my code's time complexity is \$O(2^N\log{N})\$ as the for loop runs \$2^N\$ times and inside that we are checking all the \$\log{N}\$ bits. Can I reduce the time complexity to \$2^N\$? or is it not possible to reduce the time complexity while solving the problem using bitmasking?


texts: Python 2 Stack and LinkedList implementation

texts:
I'm currently implementing data structures and algorithms I studed in my college course. This is my implementation of a singly linked list and a stack. I would appreciate some feedback in terms of the code quality.

My LinkedList:

from random import randint

class Node:

    def __init__(self, x):
        self.current = x
        self.next = None

class LinkedList:

    def __init__(self, x):
        self.head = Node(x)

    def insert(self, x):
        new_entry = Node(x)
        new_entry.next = self.head
        self.head = new_entry

    def search(self, x):
        node = self.head

        while node.current is not x:
            if node.next is None:
                break
            node = node.next

        if node.current is x:
            return x
        else:
            return None

    def contains(self, x):
        retrieved = self.search(x)
        return retrieved is x

    def delete(self, x):
        try:
            node = self.head

            while node.next.current is not x:
                node = node.next

            if node.next.current is x:
                node.next = node.next.next
        except AttributeError:
            print str(x) + " is not in the linked list"

    def traverse(self):
        node = self.head
        text = ""  # type: str

        while node is not None:
            text += str(node.current) + "->"
            node = node.next

        return text

My stack:

class Stack:

    def __init__(self):
        self.data = []

    def push(self, e):
        self.data.append(e)

    def pop(self):
        return self.data.pop()

    def prnt(self):
        print self.data

def is_integer(val):
    try:
        int(val)
        return True
    except ValueError:
        return False

def is_binary_operator(val):
    return val is '+' or val is '-' or val is '*' or val is '/'

def postfixEval(stack, expression):
    symbols = expression.split()

    for symbol in symbols:

        if is_integer(symbol):
            s = int(symbol)
            stack.push(s)
        elif is_binary_operator(symbol):
            s2 = stack.pop()
            s1 = stack.pop()

            if symbol is '+':
                a = s1 + s2
            elif symbol is '-':
                a = s1 - s2
            elif symbol is '*':
                a = s1 * s2
            elif symbol is '/':
                a = s1 / s2

            stack.push(a)

    return stack.pop()


texts: Followup: How do I optimize this Java cube root function for BigInteger?

texts:
Followup to How do I optimize this Java cube root function for BigInteger?
So I've tried several implementations of this algorithm. The version using only BigInteger sometimes results in a never-ending cycle of candidates:
public static final BigInteger _3=BigInteger.valueOf(3);

public static BigInteger cbrt(BigInteger num)
{
 BigInteger root=BigInteger.ZERO.setBit(num.bitLength()/3),temp;
 do {
  temp=root;
  root=temp.add(temp).add(num.divide(temp.multiply(temp))).divide(_3);
 } while(!root.equals(temp));
 return root;
}

This hangs the program for certain numbers (5 and 26 are prime examples).
Next I tried using BigDecimal to give me more accurate division, but I was afraid that converting back and forth between BigInteger and BigDecimal might be slowing it down:
public static final BigDecimal _3=BigDecimal.valueOf(3);
public static final int UP=BigDecimal.ROUND_HALF_UP;

public static BigInteger cbrt(BigInteger num)
{
 BigDecimal numD=new BigDecimal(num),temp;
 BigInteger root=BigInteger.ZERO.setBit(num.bitLength()/3);
 do {
  temp=new BigDecimal(root);
  root=temp.add(temp).add(numD.divide(temp.multiply(temp),UP)).divide(_3,UP).toBigInteger();
 } while(!root=temp.toBigInteger());
 return root;
}

On a suggestion from the comments, I tried modifying the first function above with the algorithm ending with the root less than or equal to the temp. But that returns the wrong root for some numbers:
public static final BigInteger _3=BigInteger.valueOf(3);

public static BigInteger cbrt(BigInteger num)
{
 BigInteger root=BigInteger.ZERO.setBit(num.bitLength()/3),temp;
 do {
  temp=root;
  root=temp.add(temp).add(num.divide(temp.multiply(temp))).divide(_3);
 } while(root.compareTo(temp)>0);
 return root;
}

Try 1367631. The return value is 113, not 111.
Then there's my solution: multiple temporary values:
public static final BigInteger _3=BigInteger.valueOf(3);

public static BigInteger cbrt(BigInteger n)
{
 BigInteger root=BigInteger.ZERO.setBit(n.bitLength()/3),t1,t2,t3;
 t1=t2=t3=BigInteger.ZERO;
 do {
  t3=t2;t2=t1;t1=root;
  root=t1.add(t1).add(n.divide(t1.multiply(t1))).divide(_3);
 } while(!root.equals(t1.add(t2).add(t3).divide(_3)));
 return root;
}

I'm trying to decide between the BigDecimal version and the multiple-temp version. Any suggestions how I can make either algorithm better?
Edit: Followup can be found here: https://codereview.stackexchange.com/questions/56862


texts:
Cross post from stackoverflow, as suggested.

I have an ordereddict, and I need to store it in CSV file.
Input:

dic = collections.OrderedDict([('k1', 'v1'),
                               ('k2', 'v2'),
                               ('k3', [ [('k3a',21), ('k3b',22)],
                                        [('k3a',23), ('k3b',24)] ]),
                               ('k4', [1,2,3,4])])

mapping = {'k3': ['k3a', 'k3b']}

Desired output:

k1,k2,k3a,k3b,k4
v1,v2,21,22,1
v1,v2,23,24,2
v1,v2,,,3
v1,v2,,,4

That is, substitute the top level keys in the mapping dictionary with the sub-keys in the OrderedDict, and add blank fields when no data is available.

My working code so far is:

import csv
import collections

max_len = 0
result = []
for k,v in dic.items():
    if isinstance(v, list) and len(v) > max_len:
        max_len = len(v)

for i in range(max_len):
    tmp = collections.OrderedDict()
    for k, v in dic.items():
        if not isinstance(v, list):
            tmp.update({k:v})
        else:
            if k in mapping and i < len(v):
                if isinstance(v[i], list):
                    for tup in v[i]:
                        tmp.update({tup[0]:tup[1]})
            elif k in mapping and i >= len(v):
                for mk in mapping[k]:
                    tmp.update({mk:''})
            else:
                try:
                    tmp.update({k:v[i]})
                except IndexError:
                    tmp.update({k:''})
    result.append(tmp)

with open("out.csv", "w", newline='') as csvfile:
    writer = csv.DictWriter(csvfile, result[0].keys())
    writer.writeheader()
    writer.writerows(result)

Is there a cleaner/easier way to achieve the desired result?


texts: Python solution to Code Jam's 'Rounding Error'

texts:
The "Rounding Error" problem of Round 1B of Google Code Jam 2018 is as follows:

  Problem

  To finally settle the age-old question of which programming language is the best, you are asking a total of N people to tell you their favorite language. This is an open-ended question: each person is free to name any language, and there are infinitely many languages in the world.

  Some people have already responded, and you have gathered this information as a list of counts. For example, 1 2 means that you have asked 3 people so far, and one picked a particular language, and the other two picked some other language.

  You plan to publish the results in a table listing each language and the percentage of people who picked it. You will round each percentage to the nearest integer, rounding up any percentage with a decimal part equal to or greater than 0.5. So, for example, 12.5% would round up to 13%, 99.5% would round up to 100%, and 12.4999% would round down to 12%.

  In surveys like this, sometimes the rounded percentages do not add up to exactly 100. After you are done surveying the remaining people, what is the largest value that the rounded percentages could possibly add up to?

  Input

  The first line of the input gives the number of test cases, T. T test cases follow; each consists of two lines. The first line consists of two integers N and L: the total number of people in the survey, and the total number of different languages represented among the people who have already responded. The second line consists of L integers Ci; the ith of these is the number of people who said that the ith of the represented languages was their favorite.

  Output

  For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the largest value that the percentages could possibly add up to, as described above.

  Limits

  1 ≤ T ≤ 100.
  1 ≤ L < N.
  1 ≤ Ci, for all i.
  The sum of all Ci values < N.
  Time limit: 10 seconds per test set.
  Memory limit: 1GB.

This is my Python solution.  However, I get the 'Time Limit Exceeded' result even for the smallest test case. How can I speed up this solution?

from functools import reduce

def main():
    def gen_sums(total, freq, remaining):
        """Generate percentages' sums"""
        if not remaining:
            yield reduce(lambda x, y: x + (y*100+total//2)//total, freq, 0)
        else:
            seen = set()

            for i in range(len(freq)):
                if not freq[i] in seen:
                    yield from gen_sums(total,
                                        freq[:i] + [freq[i]+1] + freq[i+1:],
                                        remaining-1)
                    seen.add(freq[i])

            yield from gen_sums(total, freq+[1], remaining-1)

    T = int(input())

    for i in range(1, T+1):
        total_people, num_languages = map(int, input().split())
        languages_frequency = [int(x) for x in input().split()]

        if not 100 % total_people:
            print('Case #{}: {}'.format(i, 100))
            continue

        not_responded = total_people - sum(languages_frequency)

        max_percentage = max(gen_sums(total_people, languages_frequency,
                                      not_responded))

        print('Case #{}: {}'.format(i, max_percentage))

main()


texts:
I've got the following task:

  Keeping in mind Horner's Scheme, write an application that converts a given number x in n-number system to m-number system where m, n <= 10. x is a natural number or zero, x <= unsigned(-1)

My code is as follows:

#include <iostream>

int toDecimal (int, int);
int fromDecimal (int, int);
int convert(int, int, int);

int main()
{
    int base, number, desiredBase;
    std::cin >> number >> base >> desiredBase;
    std::cout << convert(number, base, desiredBase) << std::endl;
}

int toDecimal (int base, int number)
{
    if (number / 10 == 0) {
        return number;
    }
    return (number % 10) + (base * toDecimal (base, number / 10));
}

int fromDecimal (int base, int number)
{
    if (number / base == 0) {
        return number;
    }
    return (number % base) + (10 * fromDecimal (base, number / base));
}

int convert(int number, int base, int desiredBase)
{
    int p = toDecimal(base, number);
    return fromDecimal(desiredBase, p);
}

What can I improve? What can be done better?


texts: Python Etiquette for Functions in Multiple Files

texts:
Here's the context: My code is meant to automate testing of OCR (Image to Text programs) for a science project which could easily be read and understood my others. The code includes sets of functions which serve different purposes. Basically, there are functions which deal with the drawing and saving of pages (drawtext(), createpage(), etc.), functions which run various OCR on an image (tesseractocr(), etc.) and a function which computes the difference between two strings (levenshtein()).

Having all these functions in main.py results, in my opinion, in a cluttered piece of code. Is it better generally to:

Keep all those functions in main.py so that the entire code is in one file.
Put all these functions in one functions.py file
Put each set of functions in a file, resulting in a levenshtein.py, ocr.py, and pagemaker.py in addition to the main.py.

Honestly, I feel that either 2 or 3 is the choice to make, I'm just not sure. Additionally, what level of abstraction would you usually want in a main.py file? Should the file look like

import ocr, levenshtein, pagemaker
import "a few other things"
define vars, etc

for page in pages:
    correct = pagemaker.drawpage(input1,input2,(input3,input4),etc) #also saves image
    tesseract_out = ocr.tesseract("img.png")
    tesseract_dist = levenshtein.levenshtein(correct, tesseract_out)
    print(f"Tesseract Distance: {tesseract_dist}")
    #etc for other ocr

Or is that too abstract?
Also, is command-line argument parsing (which I didn't include above) generally in the main.py file or should you simply make a file called parseocrargs.py and run

pages, color, etc = parseocrargs.argparse(aruments grabbed earlier)

I guess the main question(s) are: Should a standalone (doesn't interact with other functions) but lengthy/ugly function go in a separate file than the other functions? Should almost all functions not be in main.py? If not, how many should be? Should main.py be extremely abstracted? If not, how abstracted should it be?


texts:
I have been going through algorithms and data structures and recently came across string matching algorithms.  I have not yet wrapped my head around the significance KMP algorithm so I came up with the function below.  Is it really efficient or is there a better approach?

bool simplePatternMatch(const std::string &text, const std::string &pattern){
    //return true if pattern occurs otherwise false
    auto pat_it = pattern.begin();
    std::string::const_iterator it = text.begin();
    for(; it != text.end(); it++){
        if(*it == *pat_it){
            auto internal_it = it + 1;
            pat_it++;
            for(; internal_it != text.end();internal_it++){
                if( *internal_it == *pat_it)
                    pat_it++;
                else{
                    //a partial match occured so begin again to look for a match
                    pat_it = pattern.begin();
                    break;
                }
                if(pat_it == pattern.end())
                    return true;

            }

        }
    }
    //if we reach here there was no match
    return false;
}


texts:
I want to check that a some type has some methods:

using Arg_t2 = int;
using Arg_t3 = int;

template<class T>
struct ValidType{
   using Ret_t1 = T;
   using Arg_t1 = int;
   // ...
   Ret_t1 method1(Arg_t1,Arg_t2,Arg_t3);
   //...
};

Therefor I wrote a type-trait:

#include <type_traits>

template<class T,class _ = void> struct is_my_valid : ::std::false_type {};
template<class T> struct is_my_valid<T,::std::enable_if_t<
  ::std::is_same<typename T::Ret_t1,decltype(::std::declval<T>().method1(::std::declval<typename T::Arg_t1>(),::std::declval<Arg_t2>(),::std::declval<Arg_t3>()))>::value
  // && ...
> > : ::std::true_type {};

We can test this with:

static_assert(is_my_valid<ValidType<int>>::value,"");

What are my options to make the definition of is_my_valid this look prettier?

Edit:
I basicly want to describe an Interface with type traits. I want to do this, because the interface includes types, that depend on template parameters.

I also like that an type does not have to be implemented using the ValidType in anyway to be valid.


texts: Algorithm to park cars with minimal moves

texts:
I'm working on a car move problem. Suppose we have origin parking position for each car, [-1,1,2,3,7,6,4,5] (which means first position is empty, car with ID 1 parked at 2nd position, car with ID 2 parked at 3rd position), we want to find the minimal move to re-park car as specific desired positions. For example specific desired position [4,6,5,1,7,3,2,-1] means car with ID 4 parked at first position, car with ID 6 parked as 2nd position, etc. -1 means empty parking lot to utilize.

Here is my code, my major idea is to find a parking chain (cycle), and move the chain together, for example, in my above example,

Find a chain (cycle): car 1 move to position of car 3, car 3 move to position of car 6, car 6 move to position of car 1, etc.
Leverage empty slot to move the chain, in above example, I move car 6 to empty slot, then move car 3 to car 6 position, then move car 1 to car 3 position, finally move car 6 back from empty slot to car 1 position.

Have two questions on my code,

I use a dictionary car_new_position to facilitate look-up for car ID and new position, is it good or any smarter ideas to not using the dictionary and achieve the same algorithm time complexity?
I treat empty slot the same as car (with ID -1) in the algorithm, not sure if I treat this way correctly, or I should treat empty slot in some different way?

from collections import defaultdict

def carMove(original_positions, new_positions):

    car_new_position = defaultdict(int) # build a dictionary to map car to new position
    for i in range(len(new_positions)):
        car_new_position[new_positions[i]]=i
    result=[]
    flags=[False]*len(original_positions)
    for i in range(len(original_positions)):
        if not flags[i]:
            move_chain=set()
            move_chain.add(i)
            flags[i] = True
            new_pos = car_new_position[original_positions[i]]
            while new_pos not in move_chain:
                move_chain.add(new_pos)
                flags[new_pos] = True
                new_pos = car_new_position[original_positions[new_pos]]
            result.append(move_chain)

    print result

if __name__ == "__main__":
    carMove([-1,1,2,3,7,6,4,5], [4,6,5,1,7,3,2,-1])

Output,

[set([0, 2, 6, 7]), set([1, 3, 5]), set([4])]


texts:
I have a code that adds a user to the database, getting the username from the dialog.My fragment implements the interface with the onInputSend method, which is called by the dialog when the user clicks the desired button.
Here is the code that adds the user to the database. I want to hear criticism of my code.

UsersActivity

   public void onInputSend(@NonNull InputTextAlertDialog dialog, @NotNull String input) {
    userActionManager.isEmptyUser(input)
            .doOnSubscribe(disposable -> disposables.add(disposable))
            .subscribe(empty -> insertUser(dialog, input, empty));
}

private void insertUser(InputTextAlertDialog dialog, String userName, boolean isEmpty) {
    if (isEmpty) {
        if (!userName.trim().isEmpty()) {
            userActionManager.insertUser(new User(userName));
            dialog.cancel();
        } else {
            dialog.setErrorMessage(getString(R.string.user_not_have_name));
        }
    } else {
        dialog.setErrorMessage(getString(R.string.user_already_exists));
    }
}

InputTextAlertDialog

class InputTextAlertDialog(context: Context) : BaseAlertDialog(context) {

    var onInputOkListener: OnInputOkListener? = null
    private var input: EditText? = null
    private var error: TextView? = null

    var colorError: Int = Color.RED
        set(colorError: Int) {
            field = colorError
            error!!.setTextColor(colorError)
        }

    init {
        error = view.findViewById(R.id.error_text)
        input = view.findViewById(R.id.input)
        error!!.setTextColor(colorError)
    }

    fun setErrorMessage(errorMessage: String?) {
        error!!.text = errorMessage
        input!!.backgroundTintList = ColorStateList.valueOf(colorError);
    }

    override fun initOkClickListener() {
        ok.setOnClickListener { v: View? ->
            ok()
        }
    }

    override fun ok() {
        onInputOkListener?.onInputSend(this, input!!.text.toString())
    }

    override fun getLayout(): Int {
        return R.layout.input_text_layout
    }

    interface OnInputOkListener {
        fun onInputSend(dialog: InputTextAlertDialog, input: String)
    }
}

BaseAlertDialog

public abstract class BaseAlertDialog {
    AlertDialog alertDialog;

    protected Button cancel;
    protected Button ok;

    protected View view;
    private AlertDialog.Builder builder;

    protected Context context;

    BaseAlertDialog(Context context) {
        this.context = context;
        initDialog(context);
        initViews(view);
        initCancelClickListener();
        initOkClickListener();
    }

    private void initDialog(Context context) {
        if (getLayout() != 0) {
            view = LayoutInflater.from(context).inflate(getLayout(), null);
        } else {
            throw new RuntimeException("In getLayout () you should return the layout id");
        }
        builder = new AlertDialog.Builder(context);
        builder.setView(view);
        alertDialog = builder.create();
    }

    private void initViews(View view) {
        cancel = view.findViewById(R.id.cancel);
        ok = view.findViewById(R.id.ok);
    }

    private void initCancelClickListener() {
        cancel.setOnClickListener(v -> {
            alertDialog.cancel();
        });
    }

    protected void initOkClickListener() {
        if (ok != null) {
            ok.setOnClickListener(v -> {
                ok();
                alertDialog.cancel();
            });
        }
    }

    public void cancel(){
        alertDialog.cancel();
    }

    public void show(){
        alertDialog.show();
    }

    abstract void ok();

    abstract int getLayout();

}


texts:
iOS: prettify random color for debugging

I used to use random color to debug, from colors I like

extension CALayer{
      func debug(){
             let colors = [UIColor.blue, UIColor.magenta, UIColor.red,
                      UIColor.green, UIColor.brown, UIColor.purple,
                      UIColor.cyan]
             if let color = colors.randomElement().cgColor{
                     borderColor = color
              }
       }
 }

The effect case:

The colors are not of regularity. Not very pretty.

I want to prettify it. Do some color alignment. The same color for the same UI hierarchy.

achieve something like this.

In order to not make colors repeat, and to show more colors in a page. I use ring buffer.

In order to do some color alignment, the same color for the same UI hierarchy，I use call stack trace. Use the call function as the key for its color.

Here is the code:

// the color ring buffer
struct ColorCluster {
    static var shared = ColorCluster()

    let colors = [UIColor.blue, UIColor.magenta, UIColor.red,
                  UIColor.green, UIColor.brown, UIColor.purple,
                  UIColor.cyan]

    var colorRegister = [String: Int]()
    var count = -1

    mutating func get(_ k: String) -> CGColor{
        var index = 0
        if let idx = colorRegister[k]{
            index = idx
        }
        else{
            count += 1
            if count >= colors.count{
                count = 0
            }
            index = count
            colorRegister[k] = count
        }
        return colors[index].cgColor
    }
}

extension CALayer{

    func debug(){
        // call stack trace, remove methods of the system
        let libs: Set<String> = ["UIKitCore", "QuartzCore", "CoreFoundation"]
        var methods = [String]()
        Out: for symbol in Thread.callStackSymbols{
            for lib in libs {
                if symbol.contains(lib){
                    break Out
                }
            }
            methods.append(symbol)
        }
        var edgeColor = UIColor.black.cgColor   // color place holder
        if let name = methods.last{
            edgeColor = ColorCluster.shared.get(name)
        }
        borderColor = edgeColor
        borderWidth = 1
    }
}

Usage:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       let cell = tableView.dequeue(for: PracticeDetailCell.self, ip: indexPath)
        cell.layer.debug()
        return cell
}

more code on github


texts:
I wrote code to draw a circle segment, such that the segment angle will be facing the mouse.

My code:

#include <SFML/Graphics.hpp>
#include <math.h>

const float PI{ 3.14159265359f };

//convert degress to radians
float degToRad(float deg)
{
    return
        deg * PI / 180;
}

void drawCircleSegment(sf::RenderWindow & gameWindow)
{
    gameWindow.clear();
    sf::VertexArray arr(sf::LinesStrip);

    float segmentAngle{degToRad(45)};
    float radius{100};
    sf::Vector2f radiusPos{ gameWindow.getView().getCenter() };

    unsigned circlePoints{20};
    float angle{ 0 };

    arr.append(radiusPos);

    do
    {
        sf::Vector2f mRelP //get relative mouse position
        {
            sf::Mouse::getPosition(gameWindow).x - radiusPos.x,
            sf::Mouse::getPosition(gameWindow).y - radiusPos.y
        };

        float mouseAngle{ atan2(mRelP.y, mRelP.x) }; //get angle between relative mouse position and circle center

        sf::Vector2f p
        {
            cos(angle + (mouseAngle - segmentAngle / 2)) * radius, //position = cos(angle + lookAngle) * rad
            sin(angle + (mouseAngle - segmentAngle / 2)) * radius  //position = sin(angle + lookAngle) * rad
        };

        p += radiusPos;
        arr.append(p);

        angle += segmentAngle / circlePoints;

    } while (angle < segmentAngle);

    arr.append(radiusPos);

    gameWindow.draw(arr);
    gameWindow.display();
}

int main()
{
    sf::RenderWindow gameWindow(sf::VideoMode(800, 600), "circle");
    gameWindow.setFramerateLimit(60);

    while (gameWindow.isOpen())
    {
        sf::Event event;
        while (gameWindow.pollEvent(event))
            if (event.type == sf::Event::Closed)
                gameWindow.close();

        drawCircleSegment(gameWindow);
    }
}

What do you think about it?


texts: Interleave two lists, preserving the order of elements in their original list

texts:
I need to write an OCaml program that return all possible zip of two lists together while preserving the order of the element in each list. For example, if we zip the lists [1;2] and [3;4], we get [[1;2;3;4];[1;3;4;2];[3;1;2;4];[1;3;2;4];[3;1;4;2];[3;4;1;2]].

My naïve approach is to append each element in the first list one by one into the second list while making sure that the order of elements in the first list is preserved when inserted into the second list. Please show me the simple recursive structure.

Here are my codes :

let rec insert item list =
  match list with
  |[]-> [[item]]
  |x::xs-> (item::list)::(List.map (fun y-> x::y) (insert item xs))

let breakIntoTwo  list item=
  let rec helper acc ll itemm=
    match ll with
    |[]->(acc,[])
    |x::xs -> if x= itemm then (acc,ll)
        else helper (acc@[x]) xs itemm
  in helper [] list item

let rec insertl item list nextItem=
  match breakIntoTwo list nextItem with
  |(a,b) -> List.map (fun y -> y@b) (insert item a)

let rec insertll item listoflists nextItem=
  match listoflists with
  |[]-> []
  |x::xs-> (insertl item x nextItem) @ (insertll item xs nextItem)

let rec zip list1 list2=
  match list1 with
  |[]-> [list2]
  |[a]-> insert a list2
  |x::xs::xss -> insertll x (zip (xs::xss) list2) xs


texts:
I carefully used smart pointer to avoid memory leaks and dangling pointers, but someone says my code has memory leaks. Is it true? If so, how can I fix it?

#include <iostream>
#include <initializer_list>
#include <memory>

using namespace std;
using Ptr2D = unique_ptr<unique_ptr<int[]>[]>;
using IniList = initializer_list<int>;

void printImage(const Ptr2D& image, const IniList& il)
{
    for (auto& i : il)
    {
        for (auto& j : il)
        {
            cout << image[i][j] << ',';
        }

        cout << '\n';
    }
}

template<size_t SIZE>
void rotateImage(Ptr2D& image, const IniList& il)
{
    Ptr2D temp(new unique_ptr<int[]>[SIZE]);

    for (auto& i : il)
    {
        unique_ptr<int[]> subTemp(new int[SIZE]);

        for (auto& j : il)
        {
            subTemp[j] = 0;
        }

        temp[i] = move(subTemp);
    }

    for (auto& i : il)
    {
        for (auto& j : il)
        {
            temp[i][j] = image[SIZE - j - 1][i];
        }
    }

    for (auto& i : il)
    {
        for (auto& j : il)
        {
            image[i][j] = move(temp[i][j]);
        }
    }
}

int main()
{
    const size_t SIZE = 5;

    Ptr2D image(new unique_ptr<int[]>[SIZE]);

    IniList il = { 0, 1, 2, 3, 4 };

    for (auto& i : il)
    {
        unique_ptr<int[]> temp(new int[SIZE]);

        for (auto& j : il)
        {
            temp[j] = j + il.size() * i;
        }

        image[i] = move(temp);
    }

    cout << "******* original image ******\n";

    printImage(image, il);

    rotateImage<SIZE>(image, il);

    cout << "******* rotated image ******\n";

    printImage(image, il);
}


texts: Golang and Gin framework: best practices to connect to Postgresql

texts:
I come from this question.

Project

A very simple project with Gin framework with an endpoint to return a list of users based on their score.

Structure

liveops-tool
-- user
---- model
------ user.go
---- service
------ userService.go
---- dao
------ directory.go (interface)
------ userDirectory.go (mock the db)
------ userPostgresDirectory.go
-- main.go

main.go

r.GET("/competition/users", func(c *gin.Context) {
    numUsers, err := strconv.Atoi(c.DefaultQuery("numusers", "6"))
    minScore, err := strconv.Atoi(c.DefaultQuery("minscore", "0"))
    maxScore, err := strconv.Atoi(c.DefaultQuery("maxscore", "2000"))
    fmt.Printf("numUsers: %d , minScore: %d , maxScore: %d \n", numUsers, minScore, maxScore)

    if err == nil {
        var userDirectoryService = userService.NewService(userDirectory.UserPostgrestDirectory{})
        var res = userDirectoryService.GenerateUserListByScore(numUsers, minScore, maxScore)
        c.JSON(http.StatusOK, gin.H{"users": res})
    } else {
        c.JSON(http.StatusBadRequest, gin.H{"users": "no valid"})
    }

})

userService.go

package user

import (
    dao "liveops-tool/user/dao"
    models "liveops-tool/user/models"
)

type UserService struct {
    dir dao.Directory
}

func NewService(dir dao.Directory) *UserService {
    var service = &UserService{
        dir: dir,
    }
    return service
}

// GenerateUserListByScore returns a list of users for a tournament
func (u UserService) GenerateUserListByScore(numUsers, minScore, maxScore int) []models.User {
    return u.dir.SearchUsers(numUsers, minScore, maxScore)
}

userPostgresDirectory.go

package user

import (
    "database/sql"
    "fmt"
    models "liveops-tool/user/models"
    "strings"

    _ "github.com/lib/pq"
)

const (
    host     = "localhost"
    port     = 5432
    user     = "postgres"
    password = "XXXX"
    dbname   = "XXXX"
)

type UserPostgrestDirectory struct {
}

func (u UserPostgrestDirectory) getConnection() *sql.DB {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+"password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
    db, err := sql.Open("postgres", psqlInfo)
    checkErr(err)

    return db
}

func (u UserPostgrestDirectory) SearchUsers(numUsers, minScore, maxScore int) []models.User {
    db := u.getConnection()
    defer db.Close()
    err := db.Ping()
    checkErr(err)

    fmt.Println("Successfully connected!")

    rows, err := db.Query("SELECT * FROM users WHERE total_score >= $1 AND total_score <= $2 LIMIT $3", minScore, maxScore, numUsers)
    if err != nil {
        panic(err)
    }

    var users = []models.User{}
    for rows.Next() {
        var id int
        var name string
        var country string
        var total_score int
        err = rows.Scan(&name, &id, &country, &total_score)
        checkErr(err)
        fmt.Println("id | name | country | total_score ")
        fmt.Printf("%3v | %8v | %6v | %6v\n", id, name, country, total_score)
        user := models.User{
            ID:         id,
            Name:       strings.TrimSpace(name),
            Country:    strings.TrimSpace(country),
            TotalScore: total_score,
        }

        users = append(users, user)
    }
    return users
}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

Questions

Is it possible to retrieve the connection directly open or apply some singleton pattern to avoid creating a connection every time that the method SearchUsers is called? I even tried to pass the connection on the UserPostgrestDirectory constructor from main.go but I always get the error "database is closed".

Any other feedback about the code is well received.