texts: "Rasterbation" function to split an image into a grid

texts:
I want to create a function that splits an image into many separate blocks that when put together look like the image as a whole, often called a Rasterbator. Given the number of tiles for height and length I want and the image to Rasterbate I want the function to draw the split up image with a little padding in between.

I have created the function successfully but with a high length/height it takes a long time to create that many DOM elements sure to the nester loop, for example 100 x 100 is 10,000 divs being created and having math applied to their backgrounds.

http://jsfiddle.net/n4a7cr9z/

var img = new Image();
var width;
var height;
var length = 30;
var ylength = 20;
img.onload = function() {
width = this.width;
  height = this.height;
    for (var j = 0; j < length; j++){
    for (var i = 0; i < length; i++){
        var left = (-1 * width/length * i).toString() +"px";
        var top = (-1 * height/ylength * j).toString() +"px";
        var element = jQuery('<div/>', {
            id: i + ""+j,
            class: "splitImg",
            css: {
            "width" : Math.floor(width/length),
            "height":Math.floor(height/ylength),
          "background-position": left  + " " +  top,
          "background-image" : 'url(' + img.src + ')'
            }
            })
            element.appendTo('#wrapper');
        $("#wrapper").width(width + (length *2))
    }
    }
}
img.src = 'http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg';

I was thinking maybe creating rows or columns in batches somehow since they'll all share the same background position on either the X or Y level, like first row will all have a Y offset of 0, but I'm not sure how or if that will help.


texts: Reduce boilerplate with RepositoryPattern

texts:
I'm refactoring a WPF application that uses Repository pattern to access the web services, I've got a tons of repository wrote as

public class DiagnosticsRepository : DefaultRepositoryBase, IDiagnosticsRepository
{
    public Task<IList<MasterDiagnosticType>> GetMasterDiagnosticTypes(string username)
    {
        var client = GetServiceStackClient();

        var request = new MasterDiagnosticTypesRequest
        {
            UserName = username
        };

        return client.PostAsync(request);
    }

    public Task<IList<MasterDiagnostic>> GetMasterDiagnosticsFromType(int type)
    {
        var client = GetServiceStackClient();

        var request = new MasterDiagnosticRequest()
        { MasterType = type };

        return client.PostAsync(request);
    }

    public Task<DiagnosticoDataResponse> GetMasterDiagnostic(string storedProcedure)
    {
        var client = GetServiceStackClient();

        var request = new DiagnosticoDataRequest()

        {
            StoredProcedureName = storedProcedure,
            Data = DateTime.Today
        };

        return client.PostAsync(request);
    }
}

How can I review it so that I can avoid the repetition? the only part that changes is the request


texts: Invoking API calls with parameters specified using JSON

texts:
I have an instance of a Java class that I need to call some functions on, using the API exposed by another party. For each call, I need to both check for thrown exceptions, and check the value of the returned boolean. If the boolean is false, I need to read the errorMsg object to see what went wrong. In either error case, I need to throw an exception with a relevant method. Each method takes a different number of String arguments

I think there's a cleaner way to do this using reflection, but I can't figure out how to handle the different numbers of arguments. And there may be a totally different solution I've overlooked. Open to all suggestions. Any thoughts?

Here are two examples so you can see what I'm dealing with:

ClassProvidedWithExposedAPI s;

private void setHttp(JsonObject jo) throws Exception {
    boolean success = true;
    String errorString = null;
    ArrayList<Message> errorMsg = new ArrayList<Message>();
    try {
        JsonObject http = jo.getAsJsonObject("http");
        if (http != null && !http.isJsonNull()) {
            success = s.setHttp(getJsonElementAsString(http, Http.ENABLED_ELEMENT),
                    getJsonElementAsString(http, Http.HTTP_PORT_ELEMENT),
                    getJsonElementAsString(http, Http.HTTPS_PORT_ELEMENT),
                    getJsonElementAsString(http, Http.TIMEOUT_ELEMENT),
                    getJsonElementAsString(http, Http.HTTP_REDIRECT_ELEMENT), errorMsg);
        }

    } catch (Exception e) {
        errorString = e.toString();
    } finally {
        if (!success) {
            if (errorString == null) {
                errorString = errorMsg.toString();
            }
            throw new Exception("Exception in setHttp: " + errorString);
        }
    }
}

private void setSsh(JsonObject jo) throws Exception {
    boolean success = true;
    String errorString = null;
    ArrayList<Message> errorMsg = new ArrayList<Message>();
    try {
        JsonObject ssh = jo.getAsJsonObject("ssh");
        if (ssh != null && !ssh.isJsonNull()) {
            success = s.setSsh(getJsonElementAsString(ssh, Ssh.ENABLED_ELEMENT),
                    getJsonElementAsString(ssh, Ssh.SSH_PORT_ELEMENT),
                    getJsonElementAsString(ssh, Ssh.TIMEOUT_ELEMENT), errorMsg);
        }
    } catch (Exception e) {
        errorString = e.toString();
    } finally {
        if (!success) {
            if (errorString == null) {
                errorString = errorMsg.toString();
            }
            throw new Exception("Exception in setSsh: " + errorString);
        }
    }
}


texts: Concat a collection's sub arrays and merge their parent

texts:
I have an array like this:

var arr = [
    {
        revision: 19,
        text: 'hello',
        details: [
            {
                id: 5
            }
        ]
    },
    {
        revision: 19,
        text: 'hello',
        details: [
            {
                id: 6
            }
        ]
    },
    {
        revision: 17,
        text: 'world',
        details: [
            {
                id: 7
            }
        ]
    }
];

And I'd like to concat its details arrays if the revision is the same (the text values are the same if they got the same revision value):

var expected = [
    {
        revision: 19,
        text: 'hello',
        details: [
            {
                id: 5
            },
            {
                id: 6
            }
        ]
    },
    {
        revision: 17,
        text: 'world',
        details: [
            {
                id: 7
            }
        ]
    }
];

Here is what I came up with:

constructArray(groupByRevisionNb(arr));

function groupByRevisionNb(arr) {
    return _.groupBy(arr, 'revision');
}

function constructArray(obj) {
    return _.map(obj, function (arr) {
        return concatRevisions(arr);
    });
}

function concatRevisions(arr) {
    return _.reduce(arr, function (obj1, obj2) {
        if (_.isEmpty(obj1)) {
            obj1 = _.clone(obj2);
        } else {
            obj1.details = obj1.details.concat(obj2.details);
        }
        return obj1;
    }, {});
}

But I'm not 100% satisfied with it. What could be improved?

I'm not using ES6.


texts: How to handle overfitting in Random Forest

texts:
I have a random forest model I built to predict if NFL teams will score more combined points than the line Vegas has set. The features I use are Total - the total number of combined points Vegas thinks both teams will score, over_percentage - the percentage of public bets on the over, and under_percentage - the percentage of public bets on the under. The over means people are betting that both team's combined scores will be greater than the number Vegas sets and under means the combined score will go under the Vegas number. When I run my model I'm getting a confusion_matrix like this

and an accuracy_score of 76%. However, the predictions do not perform well. Right now I have it giving me the probability the classification will be 0. I'm wondering if there are parameters I can tune or solutions to prevent my model from overfitting. I have over 30K games in the training data set so I don't think lack of data is causing the issue.
Here is the code:
import pandas as pd
import numpy as np
import json
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.preprocessing import StandardScaler

training_data = pd.read_csv(
    '/Users/aus10/NFL/Data/Betting_Data/Training_Data_Betting.csv')
test_data = pd.read_csv(
    '/Users/aus10/NFL/Data/Betting_Data/Test_Data_Betting.csv')

df_model = training_data.copy()
df_model = df_model.dropna()

X = df_model.loc[:, ["Total", "Over_Percentage",
                     "Under_Percentage"]]  # independent columns
y = df_model["Over_Under"]  # target column

results = []

model = RandomForestClassifier(n_estimators=1000, random_state=100)

model.fit(X, y)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=100)

y_train_pred = model.predict(X_train)
y_test_pred = model.predict(X_test)

model.fit(X_train, y_train)

y_pred = model.predict(X_test)

print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
print(round(accuracy_score(y_test, y_pred), 2))

index = 0
count = 0

while count < len(test_data):
    team = test_data.loc[index].at['Team']
    total = test_data.loc[index].at['Total']
    over_perc = test_data.loc[index].at['Over_Percentage']
    under_perc = test_data.loc[index].at['Under_Percentage']

    Xnew = [[total, over_perc, under_perc]]
    # make a prediction
    ynew = model.predict_proba(Xnew)
    # show the inputs and predicted outputs
    results.append(
        {
            'Team': team,
            'Over': ynew[0][0]
        })
    index += 1
    count += 1

sorted_results = sorted(results, key=lambda k: k['Over'], reverse=True)

df = pd.DataFrame(sorted_results, columns=[
    'Team', 'Over'])
writer = pd.ExcelWriter('/Users/aus10/NFL/Data/ML_Results/Over_Probability.xlsx',  # pylint: disable=abstract-class-instantiated
                        engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
df.style.set_properties(**{'text-align': 'center'})
pd.set_option('display.max_colwidth', 100)
pd.set_option('display.width', 1000)
writer.save()

And here are links the the google docs with the test and training data.
Test Data
https://docs.google.com/spreadsheets/d/1IWZ6UPDd8ZZXsON_3kQCVynb2XDu4l1zza2lDL5vBbA/edit?usp=sharing
Training Data
https://docs.google.com/spreadsheets/d/1Z36dIrin7Xtup6qbAKfQycWD4cChX4g7nneaAzL1UdQ/edit?usp=sharing


texts:
I have a problem to solve. My algorithm is assigning Players to Positions. On the start I have a list of about 16 positions and 4 players. The problem is to assing every player to it's closest positions so the overall distance is as low as possible.

I've already done this:

List players = ...
List positions = ...
Set posPerms = positions.permutations().collect { it.subList(0, playmakers.size()) } as Set
List assignation = posPerms.min { List perm ->
    int v = 0
    perm.eachWithIndex { Position pos, int index ->
        v += pos.distance(players[index])
    }
    v
}
[players, assignation].transpose().collectEntries { it }

I get what I want, but the performance is a problem. positions.permutations() generates massive lists. Is there any more optimal way to do this?


texts:
A very bare-bones timer class created using the std::chrono library. I would like to know if any optimisations are possible and just to clarity, I am using MSVC (this code will not compile with certain compilers).

Timer.h:

#pragma once

#include <chrono>

class Timer
{
private:
    std::chrono::time_point<std::chrono::steady_clock> m_StartTime;

public:
    void Start();
    float GetDuration();
};

Timer.cpp:

#include "Timer.h"

void Timer::Start()
{
    m_StartTime = std::chrono::high_resolution_clock::now();
}

float Timer::GetDuration()
{
    std::chrono::duration<float> duration = std::chrono::high_resolution_clock::now() - m_StartTime;
    return duration.count();
}


texts: Basic function to convert Country name to ISO code using Pycountry

texts:
I am working on a dataset which contains a column with common country names.

Task: To convert country name into standard ISO names

I have written a basic function which converts country names into country codes using pycountry library.

import pandas as pd
import pycountry
df = pd.DataFrame({"Country":["China","US","Iceland"])

def do_fuzzy_search(country):
    try:
        result = pycountry.countries.search_fuzzy(country)
        return result[0].alpha_3
    except:
        return np.nan

df["country_code"] = df["Country"].apply(lambda country: do_fuzzy_search(country))

But I am facing issues.Its taking too long. My dataset has 17003 rows,which is not even that large a number.

Firstly, suggestions on the code to improve its performance would be welcome.

Secondly, I would like to know if there is completely different way to do this faster.


texts: Am I handling "spot the missing DLL" right?

texts:
I have a .net 4.5 desktop script which has dependencies on some third party libraries (dll's). These libraries are used in my MainWindowViewModel. I need to check that these dll's are present before their absence allow the program to break (which is basically at the starting point of the code). This is how I am handling it at the moment: wrapping the code which fires up the MainWindowViewModel's constructor inside a try/catch. Is this the right way to do this?

In my App.xaml.cs

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        MainWindow window = new MainWindow();

        //Create the ViewModel to which the main window binds.
        try
        {
            var viewModel = new MainWindowViewModel();
            // When the ViewModel asks to be closed,
            // close the window.
            EventHandler handler = null;
            handler = delegate
            {
                viewModel.RequestClose -= handler;
                window.Close();
            };
            viewModel.RequestClose += handler;

            window.DataContext = viewModel;
            window.Show();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            window.Close();
        }
    }

If the dll is missing, running the program causes a message box to pop up (as you see in the code), and tells the user:

  Could not load file or assembly 'xxx.net.xxxx, version = x.x.xx.x,
  culture ... or one of the dependencies. The system cannot find the
  file specified.

I would like to have a better message rather than the whole exception body in the message box. Maybe some dedicated method could return the dll name, version, etc. separately rather than me trying to clip it out of the exception.


texts: Upload an image to a folder through a form

texts:
I am using this code to upload an image. Please review it and give your feedback regarding performance, security, and quality. This also works in PDO project.

<!DOCTYPE html>

<meta charset="UTF-8">

<form action="" method="post" enctype="multipart/form-data">

Upload File

Filename1:
<input type="file" name="photo" id="fileSelect">

<input type="submit" name="submit" value="Upload">
</form>

<?php
include 'home.php';
if(isset($_FILES["photo"]["error"])){
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "
";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];

// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");

// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
}
else
{
echo "Error: There was a problem uploading your file - please try again.";
}
}

} else{
echo "Error: Invalid parameters - please contact your server administrator.";
}
?>


texts: Spotify API data to vk.com user's status

texts:
Just a simple script that puts a user's currently playing track(on Spotify) to his account's status on vk.com. And printing info about the track in the console.

import requests
import os
import json

URL_TRACK = 'https://api.spotify.com/v1/me/player/currently-playing'
URL_STATUS = "https://api.vk.com/method/status.set"
VK_TOKEN = os.environ.get('VK_TOKEN')
SP_TOKEN = os.environ.get('SP_TOKEN')

def set_status():
    params = {
              'user_id': 8573490,
              'v': 5.92,
              'access_token': VK_TOKEN,
              'text': current_track()
    }

    status = requests.get(url=URL_STATUS, params=params)

def track_data():
    headers = {
               'Accept': 'application/json',
               'Content-Type': 'application/json',
               'Authorization': f'Bearer {SP_TOKEN}',
    }

    return requests.get(url=URL_TRACK, headers=headers)

def track_is_playing():
    return track_data().status_code == 200

def current_track():
    data = track_data().json()
    artist_path = data["item"]['artists'][0]['name']
    track_path = data["item"]['name']

    return(f'{artist_path} - {track_path}')

def run_script():
    if track_is_playing():
        set_status()
        print(current_track())
    else:
        print('Not playing')

if __name__ == "__main__":
    run_script()


texts:
I want to collect my users' data as an array:

h = {}
a = [["user_3", 765], ["user_1", 2], ["user_1", 1], ["user_2", 124],["user_1", 3], ["user_2", 223], ["user_2", 334]]
# Expected output :: {"user_3"=>[765], "user_1"=>[2, 1, 3], "user_2"=>[124, 223, 334]}
a.each do |x|
  if h.keys.include?(x.first)
    h[x.first] = (h[x.first] << x.last)
  else
    h[x.first] = [x.last]
  end
end

Everything is working fine in my Ruby script, but is there any better way to achieve my result?


texts:
Below is LRU Cache class implementation.

# Design and implement a data structure for Least Recently Used (LRU) cache.
# It should support the following operations: get and put.
#
# get(key) - Get the value (will always be positive) of the key if the key exists in the cache,
# otherwise return -1.
# put(key, value) - Set or insert the value if the key is not already present.
# When the cache reached its capacity,

I've left out a lot of the details, but most of the methods you can just delegate to the internal ordered dict self.store.

https://leetcode.com/problems/lru-cache/description/

Could you do both operations in O(1) time complexity?

class LRUCache(object):

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity
        self.dic = {}
        self.history_dic = {}
        self.key_dic = {}
        self.current = 0
        self.count = 0
    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        if not key in self.dic:return -1
        self.update_history(key)
        return self.dic[key]

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: void
        """
        self.update_history(key)
        if key in self.dic:
            self.dic[key] = value
            return
        if len(self.dic)==self.capacity:
            i = self.current
            while not self.history_dic[i]:
                i += 1
            self.dic.pop(self.history_dic[i])
            self.key_dic.pop(self.history_dic[i])
            self.current = i+1
        self.dic[key] = value

    def update_history(self,key):
        if key in self.key_dic:
            self.history_dic[self.key_dic[key]] = None
        self.history_dic[self.count] = key
        self.key_dic[key] = self.count
        self.count += 1

# Time:  O(1), per operation.
# Space: O(k), k is the capacity of cache.

# put(key, value) - Set or insert the value if the key is not already present.
# When the cache reached its capacity,
# it should invalidate the least recently used item before inserting a new item.
#
# Follow up:
# Could you do both operations in O(1) time complexity?
#
# Example:
#
# LRUCache cache = new LRUCache( 2 /* capacity */ );
#
# cache.put(1, 1);
# cache.put(2, 2);
# cache.get(1);       // returns 1
# cache.put(3, 3);    // evicts key 2
# cache.get(2);       // returns -1 (not found)
# cache.put(4, 4);    // evicts key 1
# cache.get(1);       // returns -1 (not found)
# cache.get(3);       // returns 3


texts:
I have a website written in PHP but the whole script is old so today I started upgrading from Mysql to Mysqli.

So here's my register page. I still have to add account confirmation and send mail part but that part can wait for now.

/* PUBLIC */
$IP = $_SERVER['REMOTE_ADDR'];

/* PRIVATE */
if(isset($_POST['submit']))
{
    $email= $_POST['email'];
    $email_safe = $mysqli->real_escape_string($email);
    $password = $_POST['password'];
    $password_safe = $mysqli->real_escape_string($password);
    $password1 = $_POST['password1'];
    $password1_safe = $mysqli->real_escape_string($password1);
    @$referrer = $_POST['referrer'];
    $referrer_safe = $mysqli->real_escape_string($referrer);

    if ($password_safe  == $password1_safe){
    if(strlen($password) < 8){
    die('Password must be at least 8 characters');
    } else {
    $result = $mysqli->query("SELECT email FROM user WHERE email='$email_safe'");
    if ($result->num_rows > 0) {
    die ("Duplicated email. Please use other email.");
    } else {
    $result = $mysqli->query("SELECT reg_ip FROM user WHERE reg_ip='$IP'");
    if ($result->num_rows > 0) {
    die ("Duplicated IP.");
    } else {
    $sql = "INSERT INTO user (email,passwd,ref) VALUES ('$email_safe','$password_safe','$referrer_safe')";
    if(!$result = $mysqli->query($sql)){
    die('There was an error running the query [' . $mysqli->error . ']');
    } else {
    echo"Registering....";
    }
    }
    }
    }
    } else {
    die ("Password didn't match. Please go back and fix this error.");
    }
} else {
    HTML FORM
    }

Well ? How it's looking ? It is secure ? ( I mean any open gate :) )

Thanks :)
P.S : The code works 100%.


texts: Creating a count inversion array of an unsorted array of unique integers

texts:
Given an array:

arr = [2,3,1,4]

I could write a count inversion array such that counting all numbers n2 after a certain number n1 in arr such that n1 > n2 and write it like this

[1 1 0 0]

Similarly, the inversion array of:

[2, 1, 4, 3]

would be:

[1, 0, 1, 0]

For:

[20]
[1, 2, 3, 4, 5, 6]
[87, 78, 16, 94]

Output would be:

0
0 0 0 0 0 0
2 1 0 0

Constraints:

\$1 \le N \le 10^4\$
\$1 \le i \le 10^6\$

The code that I wrote works for most cases but takes >10sec for an extra large number of test cases.

from copy import copy

def merge(arr, left_lo, left_hi, right_lo, right_hi, dct):
    startL = left_lo
    startR = right_lo
    N = left_hi-left_lo + 1 + right_hi - right_lo + 1
    aux = [0] * N
    res = []
    for i in xrange(N):

        if startL > left_hi:
            aux[i] = arr[startR]
            startR += 1
        elif startR > right_hi:
            aux[i] = arr[startL]
            startL += 1
        elif arr[startL] <= arr[startR]:
            aux[i] = arr[startL]
            startL += 1
            # print aux
        else:
            aux[i] = arr[startR]
            res.append(startL)
            startR += 1
            # print aux

    for index in res:
        for x in xrange(index, left_hi+1):
            dct[arr[x]] += 1

    for i in xrange(left_lo, right_hi+1):
        arr[i] = aux[i - left_lo]
    return

def merge_sort(arr, lo, hi, dct):
    mid = (lo+hi)/2
    if lo<=mid<hi:
        merge_sort(arr, lo, mid, dct)
        merge_sort(arr, mid+1, hi, dct)
        merge(arr, lo, mid, mid+1, hi, dct)
    return

def count_inversion(arr, N):
    lo = 0
    hi = N-1
    dct = {i:0 for i in arr}
    arr2 = copy(arr)
    merge_sort(arr, lo, hi, dct)
    return ' '.join([str(dct[num]) for num in arr2])

count_inversion calls merge_sort and that's where the total number of LEFT > RIGHT inversions are incremented. All numbers are stored in a dictionary with counts such that whenever L > R occurs all numbers in the left array starting from L to end of Left array are incremented by 1.

Now I understand there could be a way to optimize this snippet:

for index in res:
            for x in xrange(index, left_hi+1):
                dct[arr[x]] += 1


texts:
I was assigned this homework assignment to complete. The question originates from CodeStepByStep. Below is the prompt for the question:

  Write a function stutter that takes an array of Strings as a parameter
  and that replaces every String with two of that String. For example,
  if an array stores the values ["how", "are", "you?"] before the
  function is called, it should store the values ["how", "how", "are",
  "are", "you?", "you?"] after the function finishes executing.

Below is my implementation:

function stutter(arr) {
    if(arr.length == 0) { return []; }
    if(arr.length == 1) {
        arr.push(arr[0]);
        return arr;
    }
    let size = arr.length;
    for(let i = 0; i < size + 2; i += 2) {
        arr.splice(i + 1, 0, arr[i]);
    }
    //If last two elements are not the same
    if(arr[arr.length - 2] != arr[arr.length - 1] && arr.length != 1) {
        arr.push(arr[arr.length - 1]);
    }
    return arr;
}

It would be really helpful if I could get some feedback on how my code is written. I am fairly new to JavaScript, and I don't know some of the functions that could have made this a lot easier. Feedback on code efficiency and the implementation itself is warmly invited!


texts:
I have implemented changes from a question I asked on this widget here:

Android widget code

I've added and changed a few things, so I would love some more coding advice!

public class SacWidgetService extends Service {
    private static final String TAG = "SAC WIDGET SERVICE";
    AQuery aq;
    private String roseXML = "sac-full.xml";
    private String roseUrl;
    private AppWidgetManager appWidgetManager;
    private int[] allWidgetIds;
    private File ext;
    private File file;

    @Override
    public void onStart(Intent intent, int startId) {

        aq = new AQuery(this);
        // Create some random data
        appWidgetManager = AppWidgetManager.getInstance(this
                    .getApplicationContext());

        allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);

        // get external directory and put the file in there.
        ext = Environment.getExternalStorageDirectory();
        file = new File(ext, "avalancheconditionsreport/sac/dangerrose.png");

        // parse xml and get the rose
        xml_ajax();

        stopSelf();

        super.onStart(intent, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void xml_ajax() {
        aq.ajax(roseXML, XmlDom.class, this, "sacCb");
    }

    public void sacCb(String url, XmlDom xml, AjaxStatus status) {
        XmlDom r = xml.tag("reportrose");
        roseUrl = r.tag("img").attr("src").trim();

        File ext = Environment.getExternalStorageDirectory();
        File target = new File(ext,
                "avalancheconditionsreport/sac/dangerrose.png");

        aq.download(roseUrl, target, new AjaxCallback<File>() {
            public void callback(String url, File file, AjaxStatus status) {
                String s = status.getMessage();
                int i = status.getCode();
                String e = s + " | Status Code: " + i;

                if (file != null) {
                    getInfo();
                } else {
                    Log.e("ACR SAC Widget Error", e);
                }
            }

        });
    }

    private Bitmap getRose() {
        Bitmap bitmap = null;
        try {
            FileInputStream input = new FileInputStream(file);
            bitmap = BitmapFactory.decodeStream(input);
            try {
                input.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.e(TAG, e.getMessage());
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        // Toast.makeText(this, "Sierra Avalanche Center Danger Rose",
        // Toast.LENGTH_LONG).show();
        return bitmap;

    }

    private void getInfo() {
        // TODO Auto-generated method stub
        Date dlm = new Date(file.lastModified());
        String lm = dlm.toLocaleString();

        for (int appWidgetId : allWidgetIds) {
            RemoteViews views = new RemoteViews(this.getApplicationContext()
                    .getPackageName(), R.layout.sac_widget_layout);

            Intent clickIntent = new Intent(this.getApplicationContext(),
                    SACActivity.class);
            PendingIntent clickapp = PendingIntent.getActivity(
                        this.getApplicationContext(), 0, clickIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);

            views.setOnClickPendingIntent(R.id.ivdangerrose, clickapp);
            views.setTextViewText(R.id.tvupdated, "Updated: " + lm);
            views.setImageViewBitmap(R.id.ivdangerrose, getRose());
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
}


texts: ASP.NET MVC models that can be validated without using attributes

texts:
The model looks like this, with no attributes:

public class PersonalModel : Validatable
{
    public string Name { get; set; }
    public string Email { get; set; }

    public override void Validate(dynamic item)
    {
        if (this.ValidatesPresenceOf(item.Name, "Name is required"))
        {
            if (((String)item.Name).Length > 5)
            {
                Errors.Add("name is too long less than 5 chars please!");
            }
        }
    }
}

and the action looks like this:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult PersonalInfo(PersonalModel model)
    {
        if (model.IsValid(model))
        {
            this.FlashInfo("Your Personal info was successfully received");
            return RedirectToAction("ThankYou");
        }
        else
        {
            ModelState.AddModelError(string.Empty, String.Join("; ", model.Errors.ToArray())) ;
            return View(model);
        }
    }

This is the baseclass Validatable:

public class Validatable : DynamicObject
{
    //Hooks
    public virtual void Validate(dynamic item) { }

    //Temporary holder for error messages
    public IList<string> Errors = new List<string>();

    public bool IsValid(dynamic item)
    {
        Errors.Clear();
        Validate(item);
        return Errors.Count == 0;
    }

    //validation methods
    public virtual bool ValidatesPresenceOf(object value, string message = "Required")
    {
        if (value == null || String.IsNullOrEmpty(value.ToString()))
        {
            Errors.Add(message);
            return false;
        }
        return true;
    }
}


texts:
I attempted to write a read-only dictionary, containing primes:

#inspired by http://ceasarjames.wordpress.com/2011/07/10/the-quadratic-sieve/
class PrimeDict(dict):
    def __init__(self):
        super(PrimeDict,self).__setitem__(2,2)
        self.previous_max = 2

    def __setitem__(self, key, value):
        return self.__getitem__(key) #it's a read-only dict

    def __delitem__(self, key):
        return self.__getitem__(key) #it's a read-only dict

    def __find_primes(self,n):
        if n < self.previous_max: return
        sieve = range(self.previous_max,n)
        for x in self.keys():
            i = x * ((self.previous_max - 1)//x + 1)
            while i < n:
                sieve[i - self.previous_max] = 0
                i += x
        index = self.previous_max
        while index <= n ** 0.5:
            if sieve[index-self.previous_max]:
                i = index ** 2
                while i < n:
                    sieve[i-self.previous_max] = 0
                    i += index
            index += 1
        self.previous_max = n
        for x in sieve:
            if x:
                super(PrimeDict,self).__setitem__(x,x)

    def __getitem__(self,key):
        key = int(key)
        if key>= self.previous_max:
            self.__find_primes((key+1))
        try:
            return super(PrimeDict,self).__getitem__(key)
        except:
            return False

https://gist.github.com/aausch/6709819

Is there any way for me to make this class definition cleaner and/or shorter?


texts:
I have written this small function in Javascript for changing the padding on an element in HTML. It works well, however, I wonder if there is a better way to write it without so many if statements?

  window.addEventListener("resize", navPadding);

  function navPadding() {
    let width = window.innerWidth;

    if(width < 1200){
      navDesktop.style.padding = "unset"
    } else

    if(width > 1200 && width < 1300){
      navDesktop.style.padding = "0 19% 0 5.5%"
    } else

    if(width > 1300 && width < 1400){
      navDesktop.style.padding = "0 19% 0 8.5%"
    } else

    if(width > 1400 && width < 1500){
      navDesktop.style.padding = "0 19% 0 11.5%"
    } else

    if(width > 1500 && width < 1600){
      navDesktop.style.padding = "0 19% 0 14%"
    } else

    if(width > 1600 && width < 1700){
      navDesktop.style.padding = "0 19% 0 16%"
    } else

    if(width > 1700 && width < 1800){
      navDesktop.style.padding = "0 19% 0 18%"
    } else

    if(width > 1800 && width < 1900){
      navDesktop.style.padding = "0 19% 0 19%"
    } else

    if(width > 1900 && width < 2000){
      navDesktop.style.padding = "0 20% 0 21%"
    };
  };

  navPadding();


texts:
It's using four sections of code block, I just want it to be reduced to one contiguous set that does either a or b with the two sections not a copy/pasted approach as done here:

  public function process_bulk_action() {

    //Detect when a bulk action is being triggered...
     if ( 'delete' === $this->current_action()){

      // In our file that handles the request, verify the nonce.
      $nonce = esc_attr( $_REQUEST['_wpnonce'] );

      if ( ! wp_verify_nonce( $nonce, 'sp_delete_customer' ) ) {
        die( 'Go get a life script kiddies' );
      }
      else {
        self::delete_customer( absint( $_GET['customer'] ) );
        wp_redirect( esc_url( add_query_arg() ) );
        exit;
      }

}
    //Detect when a Reset is being triggered...
     if ( 'reset' === $this->current_action()){

      // In our file that handles the request, verify the nonce.
      $nonce = esc_attr( $_REQUEST['_wpnonce'] );

      if ( ! wp_verify_nonce( $nonce, 'sp_reset_payouts' ) ) {
        die( 'Go get a life script kiddies' );
      }
      else {
        self::reset_record( absint ( $_GET['customer']));
        wp_redirect( esc_url( add_query_arg() ) );
        exit;
      }
}

    // // If the delete bulk action is triggered
    if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-delete' )
         || ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-delete' )
    ) {

      $delete_ids = esc_sql( $_POST['my_CheckBoxes'] );

      // loop over the array of record IDs and delete them
      foreach ( $delete_ids as $id ) {
        self::delete_customer( $id );
      }
      wp_redirect( esc_url( add_query_arg() ) );
      exit;
    }

    //If the delete bulk action is triggered
    if ( ( isset( $_POST['action'] ) && $_POST['action'] == 'bulk-reset' )
         || ( isset( $_POST['action2'] ) && $_POST['action2'] == 'bulk-reset' )
    ) {

      $reset_ids = esc_sql( $_POST['my_CheckBoxes'] );

      // loop over the array of record IDs and delete them
      foreach ( $reset_ids as $id ) {
        self::reset_record( $id );

      }

      wp_redirect( esc_url( add_query_arg() ) );
      exit;
    }

  }

}


texts: Unit test Web API controller that uses a static helper class which uses app config setting

texts:
I have a situation where I have a static class that reads my application configuration file for some configuration value. When unit testing Web API controllers that make use of this static class I am getting an error about the confgiration setting being null.

I could have duplicated the value of the key in my app config for the unit test project but that seemed dirty.

Instead I have tried to abstract the dependency on app settings via a configuration interface and inject the interface using Unity. This all seems to work but I've no idea if I have done this correctly (code below).

NB: I am using FakeItEasy for mocking in unit tests.

So my question is simple - is this the correct way?

Interface for accessing App config

public interface IConfigurationReader
{
    string GetAppSetting(string key);
}

public class ConfigurationReader : IConfigurationReader
{
    public string GetAppSetting(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }
}

Add init method to static class

private static IConfigurationReader _config;

public static void Init(IConfigurationReader config)
{
    _config = config;
}

Register & resolve in Unity Register Types method

unityContainer.RegisterType<IConfigurationReader, ConfigurationReader>("Config");
HeaderHelper.Init(unityContainer.Resolve<IConfigurationReader>("Config"));

In my unit test project fake interface and call static init

_config = A.Fake<IConfigurationReader>();
HeaderHelper.Init(_config);

In my unit test fake call to GetAppSetting

A.CallTo(() => _config.GetAppSetting("AES")).Returns(AesKey);


texts:
I'm working on a project for large-scale text-processing, which is a first implementation of the basic idea of CSMR. CSMR is an algorithm that measures the similarity between documents by calculating their cosine in the vector space in parallel manner, using MapReduce model.

Here is my implementation on GitHub.

Some review on the code, the algorithm, corrections and maybe proposals for changes would be gratefully appreciated. Below are the 3 most important classes:

Mapper

public class CSMRMapper extends Mapper<Text,VectorWritable,IntWritable,
        DocumentWritable >{

    @Override
    public void map(Text key, VectorWritable value, Context context)
            throws IOException, InterruptedException{
            DocumentWritable p = new DocumentWritable(new Text(key.toString())
                    ,new VectorWritable(value.get()));
            context.write(new IntWritable(1),p);

    }
}

Reducer (Pair Generator)

public class CSMRReducer extends Reducer<IntWritable, DocumentWritable ,Text,
        VectorArrayWritable> {

    private ArrayList<DocumentWritable> al;
    private VectorWritable[] val;
    private VectorArrayWritable vaw;

    @Override
    public void reduce(IntWritable key, Iterable<DocumentWritable> values,
            Context context) throws IOException, InterruptedException{
        al = new ArrayList();
        vaw = new VectorArrayWritable();

        /* Storing each key-value pair (document) in a java.util.ArrayList */
        for (DocumentWritable v : values){
            al.add(new DocumentWritable(v.getKey(),v.getValue()));
        }

        /* Generating all the possible combinations of documents */
        if (al.size()>0){
            for (int i=0;i<al.size();++i){
                for (int j=i+1;j<al.size();++j){
                    val = new VectorWritable[2];

                    /* Generating the key for the current document pair with
                        the format "doci_name@docj_name" */
                    String k = al.get(i).getKey().toString()+
                            "@"+al.get(j).getKey().toString();

                    //First Document (doci)
                    val[0] = new VectorWritable(al.get(i).getValue().get());
                    //Second Document (docj)
                    val[1] = new VectorWritable(al.get(j).getValue().get());
                    vaw.set(val);

                    context.write(new Text(k), vaw);
                }
            }
        }
    }

}

The Final Reducer (Cosine Calculator)

public class CosineSimilarityReducer
    extends Reducer<Text, VectorArrayWritable, Text, DoubleWritable>{

    @Override
    public void reduce(Text key, Iterable<VectorArrayWritable> value, Context context)
    throws IOException, InterruptedException{

        CosineDistanceMeasure cdm = new CosineDistanceMeasure();
        VectorWritable docX,docY;
        double cosine;
        for (VectorArrayWritable v : value){
            docX = (VectorWritable)v.get()[0];
            docY = (VectorWritable)v.get()[1];
            cosine = cdm.distance(docX.get(), docY.get());
            context.write(key, new DoubleWritable(cosine));
        }

    }
}


texts: Formatting HTML for use in a locally hosted iframe

texts:
This formats HTML for use in a locally hosted iframe so that you can manipulate the content in the iframe freely, without running into cross domain issues. It uses Goutte to retrieve the HTML. I'd like to improve the code, whether it's to fit a certain design pattern or just more efficient. I don't feel like it's as clean as it could be.

<?php
class HTMLFixerClass {
    public $client;
    public $crawler;
    public $url;
    public $originalHTML;
    public $validHTML;

    public function __construct($url) {
        $this->url = $url;
        $this->client = new GoutteClient();
        $this->crawler = $this->client->request('GET', $url);
        if ($this->crawler->filter('html')->count()) {
            $this->originalHTML = $this->crawler->filter('html')->html();
            $this->validHTML = $this->correct_directories($this->originalHTML);
        }
    }

    public function get_html() {
        if ($this->validHTML !== '') {
            return "<!DOCTYPE HTML>\n<html>\n" . $this->validHTML . "\n</html>";
        } else {
            return 'Invalid URL';
        }
    }

    public function correct_directories($html) {
        $temp_url = $this->url;
        preg_match_all('/<.*?\.{2}\/.*?>/', $html, $matches);
        $initial_matches = $matches;
        if ($matches) {

            //foreach match in the entire doc
            for ($i = 0; $i < count($matches[0]); $i++) {

                //foreach match in each match ex ../../
                preg_match_all('/[\.]{2}[\/]/', $matches[0][$i], $sub_matches);
                $replacement_string = '';
                for ($j = 0; $j < count($sub_matches[0]); $j++) {
                    $replacement_string .= '../';

                    //reduces base url by one directory foreach ../ found in
                    if ($j == 0) {
                        preg_match_all('/.*(?=\/.*\/)/', $temp_url, $replacement_url);
                    } elseif ($j > 0) {
                        preg_match_all('/.*(?=.*\/)/', $replacement_url[0][0], $replacement_url);
                    }

                }

                //in the end $replacement_url[0] should be the desired url for appending to css or script in order to become absolute link
                $matches[0][$i] = str_replace($replacement_string, $replacement_url[0][0] . '/', $matches[0][$i]);
            }
            for ($k = 0; $k < count($matches[0]); $k++) {
                $html = str_replace($initial_matches[0][$k], $matches[0][$k], $html);
            }
            return $html;
        } else {
            var_dump($matches);
        }
    }
}


texts:
I'm trying to make a lex (flex) grammar that kicks out tokens while always being aware of the current line number.

As an exercise, I made a simple grammar that accepts raw strings '...' with no escape sequences and prints out the line range after a string is completed.

Here's the grammar

%{

#include <stdio.h>

int linum = 1;

int token_line_count(const char *text)
{
    int count = 0;
    const char *it = text;
    if (it == NULL) { return 0; }

    while (*it) {
        if (*it == '\n') {
            ++count;
        }
        ++it;
    }
    return count;
}

%}

%option noyywrap

%%

'[^']*' {
    int begin_linum = linum;
    int linum_len = token_line_count(yytext);
    int end_linum = linum + linum_len;

    printf("found string from line %d to %d\n", begin_linum, end_linum);

    linum += linum_len;
}

\n {
    ++linum;
}

. {
    /* do nothing */
}

%%

int main()
{
    yylex();
    return 0;
}

and here's an example source file to be parsed:

hello

garbage

other stuff

'first raw string one line long on line 7'

'second raw string is 2 lines long. from line 9
to line 10'

Here's an example of the grammar in action, parsing the file above (correctly).

% ./rawstr < examplerawstr.txt
found string from line 7 to 7
found string from line 9 to 10

And, for completeness, here's the makefile used to create the executable.

CFLAGS := -O2 -Wall -pedantic -std=c99

rawstr: rawstr.o
    $(CC) -o $@ $^

clean:
    $(RM) rawstr.c rawstr.o rawstr

It doesn't use the ability to "name" regexes in the preamble... and I'm a little concerned that a single matched string can be of arbitrary length ... is there a way to split a string up into "beginning", "quoted char", and "end" tokens and have them "add or remove" contexts?


texts: Project Euler #3 - checking only up to sqrt(input)

texts:
I know it's possible for the largest factor of a number to be greater than the sqrt (e.g., for 14, 7 is the largest). Why then does almost every solution for the problem check only up to the square root? Also, I have a nagging feeling that boolean[] is not the best data structure to use here, since in this case the number is much smaller than the size of the array. What alternative data structure would be recommended in this case?

public static int largestPrime(long n)
{
    int limit=(int)Math.sqrt(n)+1;
    boolean [] numbers = new boolean[limit];
    Arrays.fill(numbers,true);
    int largestPrimeFactor=1;
    for(int count=2;count<limit;count++)
    {
        if(numbers[count]==true)
        {
            for(int i=2;i*count<limit;i++)
                numbers[count*i]=false;
            if(n%count==0)
                largestPrimeFactor=count;
        }

    }
    return largestPrimeFactor;
}

Edit: Hmm, looks like it's incorrect to only check for primes up to the square root of the input (at least without checking if the complementary factor is prime).

This is what I originally wanted to implement, but the number was too large to create a boolean array of that size.

public static int largestPrime(int n)
{
    int largestPrime = 2;
    // Worse case scenario: largest prime n is divisible by is itself
    int limit = n;
    // Create an boolean array of index up to n
    boolean[] numbers = new boolean[limit + 1];
    Arrays.fill(numbers, true);

    for (int count = 2; count <= limit; count++)
    {
        // if count is a prime number
        if (numbers[count])
        {
            // set all multiples of count to false
            for (int i = 2; i * count <= limit; i++)
                numbers[count * i] = false;
            // Check if the input number is divisible by count
            if (n % count == 0)
            {
                // The largest possible prime is the complementary factor
                limit = n / count;
                largestPrime = count;
            }
        }
    }
    return largestPrime;
}

I guess my second question is, is there a better alternative to a boolean array, and if not, what to change in the program so that it works with large numbers?


texts: Retrieve value from item wrapped in a Future[Option[Item]]

texts:
I have a function like this

def findById(id: UUID): Future[Option[Item]]

case class Item(subject: String)

Now I want to retrieve the subject if the item exists else I want the subject to be empty string.

val subject: Future[String] = repository
  .findById(someId)
  .map(_.map(i => i.subject))
  .map(_.getOrElse(""))

subject.foreach(doSomething)

Am I doing it right or is there a better way in Scala without frameworks like Scalaz.


texts:
I am writing a piece of code for some students and I came up with the following implementation of Floyd's algorithm for finding cycles in linked lists.
I was wondering if there are ways I can improve what I have so far such that the result is

more C++ idiomatic
does not contain dumb mistakes associated with the generic code

template <typename T>
struct Node {
    T val;
    Node* next;
    Node() = default;
    Node(T x)
        : val(x)
        , next(nullptr)
    {
    }
};

template <typename T>
Node<T>* detect_cycle_constant_time(Node<T>* head)
{
    Node<T> *n1, *n2;
    n1 = n2 = head;

    while (n1 && n2) {
        n1 = n1->next;
        n2 = n2->next;
        if (n2)
            n2 = n2->next;
        else
            break;

        if (n1 == n2)
            break;
    }

    // second phase of Floyds's algorithm
    if (n1 == n2) {
        n2 = head;
        while (n1 != n2) {
            n1 = n1->next;
            n2 = n2->next;
        }
        return n1;
    }
    return nullptr;
}


texts: First attempt at a pure JavaScript slider

texts:
I'm working on this pure JS slider. It's quite a basic one, but it's what I need. I would like your feedback on it and any improvements/features that I'm missing.

HTML

Slide 1

Slide 2

Slide 3

Slide 4

Slide 5

    <button class="controls" id="previous">&lt;</button>
    <button class="controls" id="next">&gt;</button>

JS

var currentSlide = 0;
var slides = document.querySelectorAll("#slides .slide");
var controls = document.querySelectorAll(".controls");
var next = document.getElementById("next");
var previous = document.getElementById("previous");

for (var i = 0; i < controls.length; i++) {
    controls[i].style.display = "inline-block";
}

function goToSlide(n) {
    slides[currentSlide].className = "slide";
    currentSlide = (n + slides.length) % slides.length;
    slides[currentSlide].className = "slide showing";
}

function nextSlide() {
    goToSlide(currentSlide + 1);
}

function previousSlide() {
    goToSlide(currentSlide - 1);
}

next.onclick = function() {
    nextSlide();
};
previous.onclick = function() {
    previousSlide();
};

CSS

/*
Essential - Core
*/
#slides {
    position: relative;
    height: 300px;
    padding: 0px;
    margin: 0px;
    list-style-type: none;
}

.slide {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    opacity: 0;
    z-index: 1;
    -webkit-transition: opacity 1s;
    -moz-transition: opacity 1s;
    -o-transition: opacity 1s;
    transition: opacity 1s;
}

.showing {
    opacity: 1;
    z-index: 2;
}

/*
Non-essential - Styles
*/

.slide {
    font-size: 40px;
    padding: 40px;
    box-sizing: border-box;
    background: #333;
    color: #fff;
}

.slide:nth-of-type(1) {
    background: red;
}

.slide:nth-of-type(2) {
    background: orange;
}

.slide:nth-of-type(3) {
    background: green;
}

.slide:nth-of-type(4) {
    background: blue;
}

.slide:nth-of-type(5) {
    background: purple;
}

.controls {
    color: #fff;
    font-size: 40px;
    cursor: pointer;
}

.controls:hover {
    color: #333;
}

.container {
    position: relative;
}

.container button:nth-of-type(1) {
    position: absolute;
    left: 0;
    top: 50%;
    z-index: 10;
}

.container button:nth-of-type(2) {
    position: absolute;
    right: 0;
    top: 50%;
    z-index: 10;
}

The slider must be responsive. However, I didn't add any "responsiveness" code to it, because I believe that can be handled by CSS. Am I wrong?

Here's the JSFiddle


texts:
I have two files, namely:

File1:

CL1 AA  XX  YY  ZZ  SS \n
CL2 3_b AA

File2:

AA  string1
AA  string2
3_b string3

My expected output is:

CL1 AA  string1
CL1 AA  string2
CL2 3_b string3
CL2 AA  string1
CL2 AA  string2

For this I wrote a following code:

import numpy as np
print("Reading Files...")
header = open('File1', 'r')
cl = header.readlines()
infile = np.genfromtxt('File2', dtype='str', skip_header=1)
new_array = []

for j in range(len(infile)):
    for row in cl:
        element = row.split("\t")
        ele_size = len(element)
        for i in range(0, ele_size):
            if np.core.defchararray.equal(infile[j,0], element[i]):
                clust = element[0]
                match1 = infile[j,0]
                match2 = infile[j,1]
                combo = "\t".join([clust, match1, match2])
                new_array.append(combo)

np.savetxt('output.txt',new_array, fmt='%s', delimiter='\t')

This generates the output I desire. But since the file has some  700000 lines in file2 and some 65000 clusters, it takes a huge time to iterate. Can anyone suggest an efficient way to parse it?

Is it possible to keep first file as a list and the second file as a dictionary, and then iterate over key values?


texts: Refactor code to solve the 'Line is too long' error in rubocop

texts:
Method.create(domain_id: domain.id, type_notification: type, message: title, url: url, owner_id: self.user.id)

How can I reduce this line to 80 ?


texts: Update pass-through query from a form (an alternative to stored procedures)

texts:
I've adapted a script from the book Microsoft Access Developer's Guide to SQL Server that I use to update a pass-through query via a form.

  One way to pass parameters to a pass-through query is to modify the
  QueryDef object's SQL property in code before running it,
  concatenating the parameter values you want to send.

I've chosen this method, rather than using stored procedures, because I do not have adequate privileges (create function) for creating stored procedures in the Oracle database.

I'm familiar with scripting, but I don't pretend to be an expert coder.

I figure I might as well get some input from those who know what they're doing, learn from you, and get off on the right foot. I've heard that non-experts who attempt to program in Access often end-up with these barely working, horribly designed applications that bring dread into the hearts of developers.

Obviously, I'd prefer to avoid that. Here's what I've got:

'SPT stands for SQL Pass-through (query). My pass-through query is called sptROAD_INSP

Private Sub cmdSubmit_Click()
    AssembleSptROAD_INSP Me.txtStartYear, Me.txtEndYear
End Sub

Option Compare Database
Option Explicit

Public Sub AssembleSptROAD_INSP( _
    intStartYear As Integer, _
    intEndYear As Integer)

    Dim strSQL As String
    Dim strSPTName As String

    strSPTName = "sptROAD_INSP"

    strSQL = "select " _
                    & "b.insp_id, " _
                    & "b.road_id, " _
                    & "b.insp_date, " _
                    & "b.Condition " _
            & "from " _
                    & "user1.road_insp b " _
            & "where " _
                    & "b.insp_date = ( select max(insp_date) from user1.road_insp a " _
                                      & "where a.road_id = b.road_id " _
                                          & "and extract(year from insp_date) between " _
                                          & intStartYear & " and " & intEndYear & ");"

    Call ModifyPassThrough(strQdfName:=strSPTName, strSQL:=strSQL)

    DoCmd.Close acQuery, "sptROAD_INSP"
    DoCmd.OpenQuery strSPTName
End Sub

Public Sub ModifyPassThrough( _
  ByVal strQdfName As String, _
  ByVal strSQL As String, _
  Optional varConnect As Variant, _
  Optional fRetRecords As Boolean = True)

    ' Modifies pass-through query properties
    ' Inputs:
    '   strQdfName  Name of the query
    '   strSQL      New SQL string
    '   varConnect  Optional connection string
    '   fRetRecords Optional returns records--
    '               defaults to True (Yes)

    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    Dim strConnect As String

    Set db = CurrentDb
    Set qdf = db.QueryDefs(strQdfName)
    If IsMissing(varConnect) Then
        strConnect = qdf.Connect
    Else
        strConnect = CStr(varConnect)
    End If
    qdf.Connect = strConnect
    qdf.ReturnsRecords = fRetRecords
    qdf.SQL = strSQL
End Sub

What can I do to make this as sustainable and robust as possible?


texts:
After a few pages reading Learning Python Hard Way, I've decided to try to make a simple cm-to-inch calculator. I am very excited about this achievement, and I want someone to check my code. It works well, but i just need someone to  confirm everything is written well.

# cm to inch calculator
inch = 2.54 #centimeters
centimeters = int(input("Enter a number of centimeters"))
print "Entered number of %s centimeters is equal to %s inches" % (centimeters , centimeters / inch)


texts: Filtering large lists and returning values that match a test

texts:
I have been working on a quiz that I came across within a job application. I am not applying for the job, but I wanted to have a go at the problem.

  An input file contains integers, both positive and negative (there
  might be some duplicates). Each line on the file has one integer.

  Compute the number of y values within the range -10000 ≤ y ≤ 10000
  such that there are distinct numbers a, b in the file where a + b = y.

  You can download the file from
  http://s3.amazonaws.com/spacebalcony/cases.tar.bz2 (57MB). There
  are two test cases there for you to verify your program. Check the
  README file for the answers.

I came up with a solution using itertools but it is very slow.

from itertools import combinations, imap

with open('test1.txt', 'rU') as f:
    integers = sorted(list(set([int(item) for item in f])))

def check_item(x):
    item_total = sum(x)
    if all([item_total >= -10000, item_total <= 10000]):
        return True
    return False

print sum(imap(check_item, combinations(integers, 2)))

Does anyone have any suggestions to speed up the code?

For example, I have tried removing the largest and smallest numbers that could never be brought down within the range:

while (integers[0] + integers[-1]) < -10000:
    integers = integers[1:]

while (integers[0] + integers[-1]) > 10000:
    integers = integers[:-1]

This did not make much of a difference


texts: function access variable in module.exports file in nodeJs

texts:
I would like to find the best way to access function variables that are being used as parameters in other functions in another module. The parsefile.js is a Node.js script that is exported as package module and two functions. getfirst and getsecond need to access the variables that are passed from index.js like 'a', 'b' from  parsefile('a', 'b', 'c'). Other than using global, do we have another way to do it?
// index.js from some application
const parsefile = require('./parsefile')
parsefile('a', 'b', 'c')

//parsefile.js exports about package module
function getfirst() {
  if (global.f && global.s) {
    return `i have totally 2 arguments: ${global.f}///${global.s}`
  }
  return `first arguments is ${global.f}`
}

function getsecond() {
  return `second arguments is ${global.s}`
}

module.exports = (...args) => {
  global.f = args[0];
  global.s = args[1];
  Promise.all([getfirst(), getsecond()]).then(([first, second]) => {
    console.log(`return from getfirst: ${first}`);
    console.log(`return from getsecond: ${second}`);
  });
}


texts:
Imagine a website that publishes the number of daily commuters in only a graphical form each day using a bar chart.  I want to determine the number by reading the bar chart after saving the graphic as an image (the image stuff is not important here).  The way I want to read the bar chart is by going to a pixel number (the #of commuters axis) and asking the question, "Is the pixel 'on' or 'off'?"  (On means that the bar is present and off means that this guess too high)  Note: that there is a lower bound of 0 and, technically, an infinite upper bound.  But, in reality, 10000 may be the realistic upper bound.  Also note, No Change from yesterday is a frequent finding.

Given a starting number from yesterday to guess, what's the most efficient way to find the number?  Does my function provide the most efficient method?  Efficient means fewest number of queries to ask if a pixel is on or off.  There will be multiple bars to measure and keeping track of the iteration number might add unwanted complexity if it's not truly needed.

My algorithm follows as a function.  Any advice is most welcome.
(brought to CR from SE, https://stackoverflow.com/questions/13782587/edge-finding-binary-search )

def EdgeFind(BlackOrWhite,oldtrial,high,low):
# BlackOrWhite is a 0 or 1 depending on if the bar is present or not.  A 1 indicates that you are below or equal to the true number.  A 0 indicates that you are above the true number
# the initial values for oldtrial, high, and low all equal yesterday's value

 factorIncrease = 4 #5
 finished = 0

 if BlackOrWhite == 1 and oldtrial==high:
    newtrial = oldtrial+factorIncrease*(high-low)+1
    high = newtrial
    low = oldtrial
 elif BlackOrWhite == 1 and high-oldtrial==1:
    finished = 1
    newtrial = oldtrial
 elif BlackOrWhite == 1:
    newtrial = oldtrial+(high-oldtrial)/2
    low = oldtrial

 if BlackOrWhite == 0 and oldtrial==low:
    newtrial = (oldtrial)/2
    high = oldtrial
    low = newtrial
 elif BlackOrWhite == 0 and oldtrial-low==1:
    finished = 1
    newtrial = oldtrial-1
 elif BlackOrWhite == 0:
    newtrial = oldtrial-(oldtrial-low+1)/2
    high = oldtrial

 if (oldtrial==1) and low!=1:
    finished = 1

 return finished,newtrial,high,low


texts: Game prototype with methods to manage players

texts:
I don't really ever write JS like this in my real workflow, but I was just trying to answer a question for someone - that was then deleted.

I wrote the following and I'd like to know if this is close to smart / or how I can improve on these patterns. I'm interested in prototypes but also functional approaches. I am pretty familiar with es2015 - so if you please, that isn't the kinda of thing I'm trying to learn in this case - so please stick with 'var' etc.

jsFiddle

"use strict";

console.clear(); // just to keep things clean in the console... not for production

function Game(newGameTitle) {
  this.title = newGameTitle;
  this.players = [];
  this.createPlayer = createPlayer;
  this.findPlayer = findPlayer;
  this.listPlayers = listPlayers;
  console.log('Game "', newGameTitle, '" created.');
}

function createPlayer(newPlayerName) { // assigned on line 8
  console.log('player', newPlayerName, 'created.');
  // get this player into the array somehow...
  var newPlayerObject = {
    name: newPlayerName,
    level: 1, // reasonable default?
  };
  // you could use a constructor here like I did with game to create a prototype or something too
  // then you can have Player.methods to 'level up' etc. - but the point should be made... you'd use the new keyword here in that case
  this.players.push(newPlayerObject);
  // 'this' is going to refer to the object that eventually 'calls' this... so the 'game' hopScotch
  // same goes for all it's uses
  console.log(this); // show the changes to the game
  return this; // in case you want to chain? not sure...
}

function findPlayer(playerName) { // assigned on line 9
  console.log('found', playerName);
  function isPlayer(targetName) {
    return targetName = name;
  }
  return this.players.find(isPlayer);
}

function listPlayers() { // assigned on line 10
  console.log('Player list:');
  this.players.forEach( function(currentPlayer, currentIndexInArray, fullArray /*if needed*/) {
    console.log(currentIndexInArray, currentPlayer);
  });
  return this;
  // I guess this doesn't have any side-effects - but what if I wanted to chain it?
}

// create 'game'
var hopScotch = new Game('Hopscotch');
console.log(hopScotch);

// add some players
hopScotch.createPlayer('@sheriffderek');
hopScotch.createPlayer('@ivy');
hopScotch.createPlayer('@valentineRose');

// try some methods
hopScotch.findPlayer('@sheriffderek');
hopScotch.listPlayers();

// checking chaining
hopScotch.createPlayer('@h2whoah').findPlayer('@h2whoah');
hopScotch.listPlayers().findPlayer('@ivy');


texts: A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++

texts:
This is a follow-up question for A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++. After digging into the thing that detecting the argument type of a function, I found that it is possible to simplify the T1 parameter in last implementation with boost::callable_traits::args_t syntax in Boost.CallableTraits library. As the result, recursive_count_if template function can be used exactly as the following code.
std::vector<std::vector<std::string>> v = {{"hello"}, {"world"}};
auto size5 = [](std::string s) { return s.size() == 5; };
auto n = recursive_count_if(v, size5);

The implementation of recursive_count_if function with automatic type deducing:
#include <boost/callable_traits.hpp>
//  recursive_count_if implementation
template<class T1, class T2> requires (is_iterable<T1> && std::same_as<std::tuple<std::iter_value_t<T1>>, boost::callable_traits::args_t<T2>>)
auto recursive_count_if(const T1& input, const T2 predicate)
{
    return std::count_if(input.begin(), input.end(), predicate);
}

//  transform_reduce version
template<class T1, class T2> requires (is_iterable<T1> && !std::same_as<std::tuple<std::iter_value_t<T1>>, boost::callable_traits::args_t<T2>>)
auto recursive_count_if(const T1& input, const T2 predicate)
{
    return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto& element) {
        return recursive_count_if(element, predicate);
        });
}

The used is_iterable concept:
template<typename T>
concept is_iterable = requires(T x)
{
    *std::begin(x);
    std::end(x);
};

The constraints of usage
Because the type in the input lambda function plays the role of termination condition, you can not use auto keyword as generic lambdas here. If the lambda function like [](auto element) { } is passed in, compiling errors will pop up. If you want to use generic lambdas, maybe you can choose the previous version recursive_count_if function due to the termination condition is separated.
A Godbolt link is here.
All suggestions are welcome.
The summary information:

Which question it is a follow-up to?
A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++ and
A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++

What changes has been made in the code since last question?
This version of recursive_count_if template function is boost-dependent, and the type of termination condition can be deduced automatically from input lambda parameter.

Why a new review is being asked for?
In my opinion, the requires-clause of recursive_count_if template function is a little complex and it's boost-dependent. If there is any simpler way to do this, please let me know.


texts: Scripts to get label name from ACQ container and modify ACQ label name

texts:
I have some side projects by using a private module I have. My main goals are to match the list if they started with the pre-defined prefix, then put them into a list. From that filtered list, I extract two elements each time and modify their label name. I am trying to clean up my code to make it more concise and user-friendly, also to make sure asking some questions before actually modify the file label. Ideally, I want to have a way to list down the file's label that is going to edit before actually editing them, if that is possible.

for k, v in sessList.items():
    # get the acquisitions in one session
    acqList = module.get_session_acqs(session_id = k, sort = {'timestamp': 'asc'} )
    conversion(acqList)

import itertools
import numpy as np
from pytz import utc
from datetime import *
from dateutil import *
from datetime import timedelta
from itertools import *
from math import *

def conversion(acqList):

  prefix = ['MCS','FT', 'FS', 'GNo', 'Rs', 'WHw', 'Cy']
  newList = []

#to check if there is any of the items contains the prefix
  for e in acqList:
    for pf in prefix:
      if(e.label.startswith(pf)):
        newList.append(e)

  data = np.arange(len(newList))

  def pairwise(iterable):
    return zip(*[iter(iterable)]*2)

  for v, w in pairwise(data):

    labelA = newList[v].label
    labelB = newList[w].label

#checking when the labelA or labelB has MCS then change the name
    if 'MCS' in labelA:
      newLabel = labelB + '_mc'

      acqID = newList[v].id
#here is when the modify happens from my module
      module.modify_acq(acquisition_id = acqID, label = newLabel )

    elif 'MCS' in labelB:
      newLabel = labelA + '_mc'

      acqID = newList[w].id
#here is when the modify happens from my module
      module.modify_acq(acquisition_id = acqID, label = newLabel )


texts:
Is there a way to simplify the code below?  I want to simplify it, but I don't know if it is possible.

In the table below, I insert data which will end up in a MySQL table.

HTML

        Dată / Interval orar
        Denumire
        Moderatori
        Detalii

        <input name="DataInterval1" type="text" id="DataInterval1">
        <input name="Denumire1" type="text" id="Denumire1">
        <input name="Moderatori1" type="text" id="Moderatori1">
        <input name="Detalii1" type="text" id="Detalii1">

        <input name="DataInterval2" type="text" id="DataInterval2">
        <input name="Denumire2" type="text" id="Denumire2">
        <input name="Moderatori2" type="text" id="Moderatori2">
        <input name="Detalii2" type="text" id="Detalii2">

    ...

        <input name="DataIntervaln" type="text" id="DataIntervaln">
        <input name="Denumiren" type="text" id="Denumiren">
        <input name="Moderatorin" type="text" id="Moderatorin">
        <input name="Detaliin" type="text" id="Detaliin">

Part of the PHP code that I want to simplify:

$DataInterval1=$_POST['DataInterval1'];
$Denumire1=$_POST['Denumire1'];
$Moderatori1=$_POST['Moderatori1'];
$Detalii1=$_POST['Detalii1'];
$DataInterval2=$_POST['DataInterval2'];
$Denumire2=$_POST['Denumire2'];
$Moderatori2=$_POST['Moderatori2'];
$Detalii2=$_POST['Detalii2'];
...
$DataIntervaln=$_POST['DataIntervaln'];
$Denumiren=$_POST['Denumiren'];
$Moderatorin=$_POST['Moderatorin'];
$Detaliin=$_POST['Detaliin'];

// Insert data into mysql
$sql="INSERT INTO tabel (DataInterval, Denumire, Moderatori, Detalii)VALUES
('".$DataInterval1."', '".$Denumire1."', '".$Moderatori1."', '".$Detalii1."'),
('".$DataInterval2."', '".$Denumire2."', '".$Moderatori2."', '".$Detalii2."'),
...
('".$DataIntervaln."', '".$Denumiren."', '".$Moderatorin."', '".$Detaliin."')";
$result=mysql_query($sql);


texts:
I have done bubble sort algorithm on a vector that is filled with randomly generated values. Bubble sort is actually done with odd-even transition method:
#include <iostream>
#include <algorithm>
#include <vector>
#include <random>
#include <thread>
#include <mutex>

void fill_with_random(std::vector<int> &vec)
{
    constexpr int lower_bound = 1;
    constexpr int upper_bound = 100;

    std::random_device rnd_device;
    std::mt19937 mersenne_engine(rnd_device());

    std::uniform_int_distribution<int> distribution(lower_bound, upper_bound);

    auto generator = std::bind(distribution, mersenne_engine);
    std::generate(vec.begin(), vec.end(), generator);
}

bool is_odd(int number)
{
    return number % 2 != 0;
}

int main(int argc, char *argv[])
{
    constexpr size_t vector_size = 10;

    std::mutex mutex;

    std::vector<int> vec(vector_size);
    fill_with_random(vec);

    std::cout << "Normal vector: ";
    for (auto item : vec)
    {
        std::cout << item << " ";
    }
    std::cout << std::endl;

    for (size_t i = 0; i < vector_size; i++)
    {
        std::vector<std::thread> threads;
        if (is_odd(i))
        {
            for (size_t j = 1; j < vector_size / 2 + vector_size % 2; j++)
            {
                size_t second = 2 * j;
                size_t first = second - 1;

                threads.emplace_back(
                    [&vec, first, second, &mutex]()
                    {
                        if (vec[first] > vec[second])
                        {
                            std::lock_guard<std::mutex> lock(mutex);
                            std::iter_swap(vec.begin() + first, vec.begin() + second);
                        }
                    }
                );
            }
        }
        else
        {
            for (size_t j = 0; j < vector_size / 2; j++)
            {
                size_t first = 2 * j;
                size_t second = first + 1;

                threads.emplace_back(
                    [&vec, first, second, &mutex]()
                    {
                        if (vec[first] > vec[second])
                        {
                            std::lock_guard<std::mutex> lock(mutex);
                            std::iter_swap(vec.begin() + first, vec.begin() + second);
                        }
                    }
                );
            }
        }

        for (auto& thread : threads)
        {
            thread.join();
        }
    }

    std::cout << "Sorted vector: ";
    for (auto item : vec)
    {
        std::cout << item << " ";
    }
    std::cout << std::endl;

    return 0;
}

Next to a style review, please check functionality of the algorithm itself.


texts: Implementing an algorithm that walks the DOM without recursion

texts:
Here's a simple algorithm that walks the DOM given a node:

function walkDOM(n) {
    do {
        console.log(n);
        if (n.hasChildNodes()) {
            walkDOM(n.firstChild)
        }
    } while (n = n.nextSibling)
}

I wanted to implement it iteratively as an exercise, and came up with this:

function walkDOM2(n) {
    var recStack = [];
    // First get the parent of the given node, so that
    // you can get the siblings of the given node too
    // (starting from the last sibling),
    // rather than just start with the children of the
    // given node.
    // (This is to make this behave the
    // same way as the recursive one.)
    recStack.push(n.parentNode);

    while (recStack.length > 0) {
        var current = recStack.pop();
        // Log only if the current node is
        // the given node or a node below it.
        // (This is to make this behave the
        // same way as the recursive one.)
        if (current != n.parentNode)
            console.log(current);
        if (!current.hasChildNodes())
            continue;

        current = current.lastChild;
        do {
            recStack.push(current);
            // Skip the sibling nodes
            // before the given node.
            // (This is to make this behave the
            // same way as the recursive one.)
            if (current === n)
                break;
        } while (current = current && current.previousSibling);
    }
}

I have used a couple tricks to make it behave the same way as the first recursive version. Is there a more concise way of writing this without recursion?


texts: Cellular automata path and fill algorithm

texts:
I have worked for a few days in my cellular automata path algorithm and an easy fill algorithm, but sometimes I get some weird fall in my FPS.

If you need a preview

function createGrid()
{
// Create Grid
for(var y = 0; y < yTotal; y++)
{
  grid[y] = [];
    for(var x = 0; x < xTotal; x++)
  {
       grid[y][x] = RandomRange(0, 1);
  }
}

// 6 loops, why? just to make the path more straight
for(var i = 0; i < 6; i++)
{
  for(var y = 0; y < yTotal; y++)
  {
    for(var x = 0; x < xTotal; x++)
    {
      var total = 0;
      // All neighbour values added to the current one
      for(var h = -1; h <= 1; h++)
      {
        for(var w = -1; w <= 1; w++)
        {
          var yw = Math.max(0, Math.min(xTotal - 1, y + h)),
              xw = Math.max(0, Math.min(yTotal - 1, x + w));
              total += grid[yw][xw];
        }
      }
      // Make current to wall or air
      grid[y][x] = Math.round(total / 3) & 1;
    }
  }
}

// If current Cell has value of 0, it will be air elsed wall
for(var y = 0; y < yTotal; y++)
{
  for(var x = 0; x < xTotal; x++)
  {
       grid[y][x] = grid[y][x] == 0 ? new Air("white") : new Wall("black");
  }
}
}

Draw and fill algorithm:

setInterval(function(){

ctx.clearRect(0, 0, wCanvas, hCanvas);

for(var y = 0; y < yTotal; y++)
{
  for(var x = 0; x < xTotal; x++)
  {
    var celd  = grid[y][x];

    // Fill Algorithm
    if(celd instanceof Fill)
    {
      // Just to make a delay
      if(celd.TotalCooldown-- === 0)
      {
        var xLeft   = Math.max(0  , x - 1),
            xRight  = Math.min(xTotal - 1 , x + 1),
            yTop    = Math.max(0  , y - 1),
            yBottom = Math.min(yTotal - 1 , y + 1);

        if(grid[y][xRight]  instanceof Air) grid[y][xRight]   = new Fill("red");
        if(grid[y][xLeft]   instanceof Air) grid[y][xLeft]    = new Fill("red");
        if(grid[yBottom][x] instanceof Air) grid[yBottom][x]  = new Fill("red");
        if(grid[yTop][x]    instanceof Air) grid[yTop][x]     = new Fill("red");
      }
    }

    // Draw Map
    ctx.beginPath();
    ctx.fillStyle = celd.Color;
    ctx.rect(x * celdSize, y * celdSize, celdSize, celdSize);
    ctx.fill();
    ctx.closePath();
  }
}
}, 1000 / 60);


texts:
I have this code for a website I'm working on. It uses window.scroll events to parallax some items. It's running a bit slow on average machines. Is there any way I could improve it to make it run faster?

$(function() {

    // Tell the DOM that JS is enabled
    $('html').removeClass('no-js');

    // Navigation Waypoints
    $('.waypoint').waypoint(function(event, d) {
        var a = $(this);
        if (d === "up") a = a.prev();
        if (!a.length) a = a.end();
        $('.active').removeClass('active');
        a.addClass('active');
        $('a[href=#'+a.attr('id')+']').addClass('active');
    }, {offset: '40%'});

    // Parallax Effects
    $(window).scroll(function() {
        var s = $(window).scrollTop(),
            b = ($('body').height()/100)*20;
            $('.container').each(function () {
                $(this).css('top', Math.round((($(this).closest('.waypoint').offset().top-s)+b)/$(this).attr('data-speed')));
            });
            $('#home hgroup').css('bottom', '-'+Math.round(s/6)+'px');
    });

    // FAQs
    $(document).on('click', '.faqs a', function () {
        $('.faqs .open').slideToggle().removeClass('open');
        $(this).siblings().slideToggle('fast').addClass('open');
        return false;
    });

    // Kinetics
    $('.counter').kinetic({
        y: false
    });

    // Smooth Scroll
    $(document).on('click', 'nav a', function() {
        var t = $($(this).attr('href')),
            o = t.offset().top,
            b = ($('body').height()/100)*10;
        if($(this).attr('href') === "#home") {
            $('html, body').animate({scrollTop: o}, 'slow');
        } else {
            $('html, body').animate({scrollTop: o+b}, 'slow');
        }
        return false;
    });

    // Set Margin
    function setMargin () {
        var t = $('#about'),
            o = t.offset().top,
            c = $('.container'),
            b = ($('body').height()/100)*20,
            m = Math.round(parseInt(t.css('margin-top'))),
            a = Math.round((((o/2)+b)+m)/2);
        c.css('top', a);
    }

    // Calculate Padding
    function calcPadding() {
        var p = Math.round(($(window).width()-700)/2);
        $('.pr').css('padding-right', p);
        setWidth();
    }

    // Calculate Width
    function setWidth () {
        $('.draggable').each(function () {
            var w = 0;
            $(this).children().each(function () {
                w = w + $(this).outerWidth() + parseInt($(this).css('margin-left')) + parseInt($(this).css('margin-right'));
            });
            $(this).css('width', w);
        });
    }

    // Window Resize
    $(window).on('resize', calcPadding);

    // Initialize Functions
    calcPadding();
    setMargin();

});


texts: Temporary modifying env variables with context manager

texts:
One function of a program I'm working with benefits from using all available openMP threads. The rest of the program has issues with the env variable OMP_NUM_THREADS being unequal to 1.

I'm currently using the following solution to that, and was wondering whether there were any caveats or room for improvement here. I haven't worked much with context managers yet, and greatly appreciate any help/pointers. Thanks!

import os
import multiprocessing as mp

class MaxOMP:
    def __enter__(self):
        os.environ["OMP_NUM_THREADS"] = str(mp.cpu_count())

    def __exit__(self, exc_type, exc_val, exc_tb):
        os.environ["OMP_NUM_THREADS"] = "1"

def main():
    with MaxOMP():
        run_omp_intensive_job()


texts:
I've recently started teaching myself Python but have no prior programming experience or formal training. I've successfully created a program that outputs what I wanted it to output, but I'm looking for guidance on design/efficiency. Is there an overall design that would have been more efficient? Any pieces of code that should be re-written to be more stylistically correct? I purposely wrote this program without utilizing a database, but my next goal is to re-write the program to use a database instead of dictionaries.

The goal of this program is to read in 3 files that have a common key (custID). A customer can have multiple orders, but only one email/customer record. File layouts:

names.txt: custID|firstName|lastName|address1|address2|city|state|zip
emails.txt: custID|email
orders.txt: orderID|orderDate|channel|orderAmt|custID

Then, output a file with each order appearing on a new line:

output.txt: custID|firstName|lastName|city|state|email|orderDate|orderAmount

Program:

import re
import os

cust_info = {}
cust_emails = {}
cust_orders = {}
cust_join = {}

#Read Customer file with layout:
#custID|firstName|lastName|address1|address2|city|state|zip
def read_cust_file():
    with open('names.txt', 'r') as f:
        for line in f:
            split_line = re.sub("\s\s+", '|', line).strip().split('|')
            cust_info[int(split_line[0])] = "|".join(split_line[1:])
    return cust_info

#Read Email file with layout: custID|email
def read_email_file():
    with open('emails.txt', 'r') as g:
        for line in g:
            split_line = re.sub("\s\s+", '|', line).strip().split('|')
            cust_emails[int(split_line[0])] = "|".join(split_line[1:])
    return cust_emails

#Read Order file with layout: orderID|orderDate|channel|orderAmt|custID
#There can be multiple orders per custID
def read_order_file():
    with open('orders.txt', 'r') as f:
        for line in f:
            split_line = re.sub("\s\s+", '|', line).strip().split('|')
            try:
                cust_orders.setdefault(int(split_line[4]),[]).append("|".join(
                    split_line[0:4]))
            except KeyError:
                pass
    return cust_orders

#Join names, emails, and orders together on custID (dict key)
def join_orders():

    for key in set(list(cust_info) + list(cust_emails) + list(cust_orders)):
        try:
            cust_join.setdefault(key,[]).append(cust_info[key])
        except KeyError:
            pass

        try:
            cust_join.setdefault(key,[]).append(cust_emails[key])
        except KeyError:
            pass

        try:
            cust_join.setdefault(key,[]).append(cust_orders[key])
        except KeyError:
            pass

    return cust_join

#Format output layout:
#custID|firstName|lastName|city|state|email|orderDate|orderAmount
#Each order will be on a separate line, even if a cust made more than 1 order.
def write_output():
    output_file = open('output.txt', 'w')
    for k, v in cust_join.items():
        if len(v) == 3:
            for item in v[2]:
                split_cust = v[0].split('|')
                split_item = item.split('|')
                output_file.write("%s|%s|%s|%s|%s|%s|%s|%s\n" % (
                    k, split_cust[0], split_cust[1], split_cust[4],
                    split_cust[5], v[1], split_item[1], split_item[3]))
    output_file.truncate(output_file.tell() - len(os.linesep))
    output_file.close()

def main():

    read_cust_file()
    read_email_file()
    read_order_file()
    join_orders()
    write_output()

if __name__ == "__main__":
    main()

I really appreciate any advice you all can give!


texts:
For a website, I've got some inline PHP, posted below.  It's supposed to log traffic to the website, and it does its job fine.  But at the end of the day, I'm not even close to a PHP developer, and this is really just hacked together from Googling and inferring from other, more familiar languages.  How can I improve this?  Is using PHP in the actual file like this bad?  (This is in index.html.)  Also, I don't believe I'm open to an SQL injection attack since the variables are all drawn directly from the server rather than the user, but I could be wrong.

    <?php
        $ip = (!empty($_SERVER["HTTP_CLIENT_IP"]) ? $_SERVER["HTTP_CLIENT_IP"] : $_SERVER["REMOTE_ADDR"]);
        $fwd = (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]) ? "\"".$_SERVER["HTTP_X_FORWARDED_FOR"]."\"" : "null");
        $hostname = gethostbyaddr($ip);

        if($ip !== "127.0.0.1" && $ip !== "192.168.1.1") {
            $con = mysqli_connect("localhost","username","password","database");
            if(!mysqli_connect_errno($con)) {
                $result = mysqli_query($con, "INSERT INTO table_name VALUES(\"".$ip."\", now(), \"".$hostname."\", ".$fwd.")");
            }
        }
    ?>


texts:
I want to create a container that has an AutoList object list. I wonder if my container is correct.

class Auto{
    string model;
    int co2;
public:
    Auto ();
    Auto(string m, int c);
    ~Auto(){};
    string GetModel(){return model;}
    void SetModel(string s){model = s;}
    int GetCo2(){return co2;}
    void SetCo2(int k){co2 = k;}
    bool operator < (const Auto &kitas);
};

class AutoList{
private:
    Auto data;
    AutoList *next;
public:
    AutoList(Auto a = Auto(), AutoList *al = NULL):
        data(a), next(al){}
    ~AutoList(){}

    void SetData(const Auto &a){data = a;}
    Auto GetData() const {return data;}

    void Set(AutoList *newaut){next = newaut;}
    const AutoList *Get() const {return next;}
    AutoList *Get(){return next;}
};

// I need to make a container class which saves AutoList object list.

class Container{ // is this class is container of AutoList object LIST???
private:
    AutoList *beg, *end, *d;
public:
    Container():beg(NULL), end(NULL), d(NULL){}
    ~Container(){Delete();}
    void Delete();

    Container(const Container & kitas);
    Container & operator = (const Container & kitas);

    void Begin(){d = beg;}
    bool True(){return d != NULL;}
    void Next(){d = d->Get();}
    AutoList GetAutoList(){return d->GetData();}
    void SetAutoList(const Auto & data);
};

void Container::Delete(){
    while(beg){
        d = beg;
        beg = beg->Get();
        delete d;
    }
    end = NULL;
}

void Container::SetAutoList(const Auto & data){
//..........
}


texts:
Is there any room for improvement on this code?

I use mechanize to get the links of a job listing web site. There are pages with pagination (when jobs > 25) and pages without.

If there is, then the link number 5 is labelled after "Next >" and link number 6 is "Last >>".
In order to identify them, I make assertions on their name and act accordingly.
I then check how many pages the pagination occurs, and then, taking the numbers, I scrape the pages one by one.

  def scrape_duty_station
    agent = Mechanize.new
    page=agent.get(self.web_link)

    if page.links[5].text =~ /^next/i
      pagestart=page.links[5].href.match(/\d+/).to_s.to_i
      pageend=page.links[6].href.match(/\d+/).to_s.to_i
      @page=page.links[7...31]
      scrape_single_page
      (pagestart..pageend).each do |i|
        @page=agent.get(self.web_link+"/#{i}")
        @page=@page.links[7...31]
        scrape_single_page
      end
    else
      @page=page.links[5...30]
      scrape_single_page
    end
  end

  def scrape_single_page
    @page.each do |i|
      p=Position.new
      p.title = i.text
      p.web_link = i.href
      p.job_id = i.href.match(/\d+/).to_s
      p.station = Station.where(:web_link => self.web_link).first
      p.save
    end
  end


texts: Java program to add two numbers represented by linked lists

texts:
First of all, I found this question on Leetcode.The two digits of the two numbers are stored in reverse order.We have to add them and create a single linked list composed of the sum of the two numbers.Here is the question for reference.

public class LLAdd {
    static Node head, head1, head2;

    static class Node {
        Node link;
        int data;

        Node(int data){
            this.data = data;
            this.link = null;
        }
    }

public static void printList(Node head){
    Node curr = head;
    while(curr!=null){
        System.out.print(curr.data + "->");
        curr = curr.link;
    }
    System.out.print("NULL \n");
}

public static Node push(int data, Node head){
    Node new_node = new Node(data);
    new_node.link = head;
    head = new_node;
    return head;
}

public static Node addNumbers(){
    Node curr1 = head1, curr2 = head2;

    if(curr1==null) {
        return curr2;
    }
    if(curr2==null) {
        return curr1;
    }

    int data = 0, units = 0, tens = 0;

    while(curr1!=null || curr2!=null){
        data = (curr1!=null ? curr1.data : 0) + (curr2!=null ? curr2.data : 0) + tens;
        units = data % 10;
        tens = data / 10;
        head = push(units, head);
        curr1 = curr1!=null ? curr1.link : null;
        curr2 = curr2!=null ? curr2.link : null;
        if(curr1==null && curr2==null && tens > 0){
            head = push(tens, head);
        }
    }
    return head;
}

public static void main(String[] args){

    head1 = push(3, head1);
    head1 = push(4, head1);
    head1 = push(2, head1);

    head2 = push(4, head2);
    head2 = push(6, head2);
    head2 = push(5, head2);

    System.out.println("Lists before addition: ");
    printList(head1);
    printList(head2);

    System.out.println("List after addition : ");
    head = addNumbers();
    printList(head);
   }
}

Please review this code and suggest better ways to solve this problem.Thank you.


texts: Transpose 2D Matrix in Java - Time & Space Complexity?

texts:
Here's my algorithm / approach for transposing a 2D Matrix on the main diagonal.

Before:

a L M d
b G c N
H K e F
I J O P

After:

a b H I
L G K J
M c e O
d N F P

My code:

public class Matrix {

    static String[][] matrix = {

            {"a", "L", "M", "d"},
            {"b", "G", "c", "N"},
            {"H", "K", "e", "F"},
            {"I", "J", "O", "P"}
    };

    public void transpose(String[][] matrix) {
       String[][] transposedArray = new String [4][4];
       for (int row =0; row < 4; row ++) {
           for (int col = 0; col < 4; col++) {
               transposedArray[row][col] = matrix[col][row];
           }
       }
    }
}

What is the time & space complexity of this approach?

Is there a better optimal solution?


texts: Mapping one JSON message format to another in Java

texts:
This code takes a JSONObject, passes it to another class which is responsible for mapping the data in the JSONObject to a different format (Still a JSONObject though).
I'd just like confirmation if the code below is bad practice or not, I feel it is:

public class DeliveredCommunication{

    private String deviceId;
    private int versionMajor;
    private int versionMinor;
    private int versionPatch;
    private JSONArray messages;
    private DataMapper dataMapper = null;
    private Logger log = (Logger) LogManager.getLogger();

public DeliveredCommunication(String deviceId, int versionMajor, int versionMinor, int versionPatch,
            JSONArray messages) {
        this.deviceId = deviceId;
        this.versionMajor = versionMajor;
        this.versionMinor = versionMinor;
        this.versionPatch = versionPatch;
        this.messages = messages;

    }

    public String getDeviceId() {
        return deviceId;
    }

    public int getVersionMajor() {
        return versionMajor;
    }

    public int getVersionMinor() {
        return versionMinor;
    }

    public int getVersionPatch() {
        return versionPatch;
    }

    public JSONArray getMessages() {
        return messages;
    }

    public void mapData(){
        dataMapper = new DataMapper();
        JSONObject msg = null;
        for(int i = 0; i < messages.length(); i++){
            try {

                msg = messages.getJSONObject(i);
                dataMapper.map(msg);

            } catch (JSONException e) {

                log.warn(deviceId + ": A JSONException occurred trying to map Data for database insertion: " + msg, e);
            }
        }
    }

    public DataMapper getDataMapper(){

            return dataMapper;

    }
}

I'm not 100% sure though, because the mapData() method in the DataMapper only maps one object at a time.

Would it be a better design to pass the whole list into the DataMapper first, then return the DataMapper object without the data being mapped and let the class that called getDataMapper() call dataMapper.mapData() to map all the data in one go?

Does that make sense?

Or Instead of having getDataMapper() I could just have a method called getMappedData() and have that method do the work in mapData() and just get and return a list of mapped objects from the DataMapper.


texts:
I wrote a failback for the fairly new CSS calc() rule. It works fine but I want to use it in a production environment and would appreciate feedback.  Please recommend anything regarding weird/wrong code, possible optimizations, or a way to reduce code size.

// CSS calc() replacement
function calcfailback(){
   var d = document.createElement('div');
   var _body = document.getElementsByTagName('body') [0];
   _body.appendChild(d);
   d.style.visibility = 'hidden';
   d.style.width = "-webkit-calc(10px)";
   d.style.width = "-o-calc(10px)";
   d.style.width = "-moz-calc(10px)";
   d.style.width = "calc(10px)";
   var newwidth = d.offsetWidth;
   if (newwidth == "10"){}
   else{
      function resize(){
         document.getElementById('content').style.height = window.innerHeight - 40 + 'px';
         document.getElementById('content').style.width = window.innerWidth - 300 +'px';
         document.getElementById('sidebar').style.height = window.innerHeight - 40 + 'px';
      };
      resize();
      window.onresize = function (){
         resize();
      }
   };
   _body.removeChild(d)
};
window.onload = calcfailback;


texts: Redirection with params - No query string

texts:
I have a products page with a search box. When a search is submitted there's a redirection to a search results page.
If another search is submitted then the query string remains intact (results are populated via ajax).
So what I've done is running twice to the server, one time using ajax to set the Session value and another for the redirect itself:

Products page

function search() {
    //get the search query text
    var query = $('#productSearchInput').val();
    //url to a method on the search controller
    var url = 'http://SearchPageUrl' + '/SetSearchQuery';
    //set the session value
    $.get(url, { query: query })
        .done(function () {
            //actual redirect
            window.location.href = 'http://SearchPageUrl';
        });
    }

Search results controller - set the session value

public void SetSearchQuery(string query)
{
    System.Web.HttpContext.Current.Session["searchQuery"] = WebUtility.HtmlDecode(query);
}

Search page entry point

public ActionResult Index()
{
    string query = System.Web.HttpContext.Current.Session["searchQuery"].ToString();
    ViewBag.query = query;

    //get the products...
    //var results = GetProducts(query);
    return View("~/Views/something/SearchResults.cshtml", results);
}

So this works but it feels like a lot of not so maintainable or efficient implementation.
How can I make it better?


texts:
The question is probably quite simple, but I would like to hear what drawbacks we will have with our code.

So, we had a simple implementation and interface for it:

public interface ISettings
{
    bool IsOnline { get; set; }
}

public class Settings : ISettings
{
    public bool IsOnline { get; set; }
}

The property shows the application state and used in many conditions. The interface in our case is required for implementing settings for different platforms.

My colleague insists on implementing an additional property:

public interface ISettings
{
    bool IsOnline { get; set; }
    bool IsOffline { get; set; }
}

public class Settings : ISettings
{
    public bool IsOnline { get; set; }
    public bool IsOffline
    {
        get { return !IsOnline; }
        set { IsOnline = !value; }
    }
}

Is it a good practice to have such additional properties just for convenient code-reading?