Return python string as the body of HTTP response

I am using AWS Lambda with python-2.7 replying back to AWS Api Gateway. My lambda function should return a response looking like following, but I am strugling with putting the proper form of body in the JSON response:

    return_value = {
        "statusCode": 200,
        "isBase64Encoded": 'false',
        "headers": {"Content-Type": "application/json"},
        "body": {payload['note']}
    }

the type of payload['note'] is unicode, so I don’t know what exactly to put in the brackets opposite to body, as I am new to python and tried a lot without being able to figure it out. I tried to convert it to string using:

unicodedata.normalize('NFKD', payload['note']).encode('ascii', 'ignore')

But it didn’t work either.

All topic

Deep find in a dictionary (Python)

I was searching for a deep find for dictionaries and didn’t find one. So I created the following. Thanks and Enjoy!!

# Searches a specific key in the list for the value
def deapFind( theList, key, value ):
    result = False
    for x in theList:
        if( value == x[key] ):
            return True
    return result

theList = [{ "n": "aaa", "d": "bbb" }, { "n": "ccc", "d": "ddd" }]
print 'Result: ' + str (deapFind( theList, 'n', 'aaa'))

I’m using == instead of the in operator since in returns true for partial matches. IOW: searching aa on the n key returns true. I don’t think that would be desired.

HTH

All topic

Python: run bash commands sequentially

I am running an executable on a bunch of *.in files in a directory. My script dumps all commands at once. I want to run Popen sequentially after the earlier process has terminated. Here is my script:

import glob, os, subprocess
import sys, re, math

exec_path='/Users/me/path/to/exec'
for name in glob.glob("*.in"):
    print name
    output = name+'.out'
        args = [exec_path, '-o', output, name]
        subprocess.Popen(args)

Thanks for your time.

All topic

Python – How to add an input error message

In Python, I have code where I only want the input to be a number and I want there to be an error message if the user inputs a string(words). How do I do that?

All topic

Output in a Table python

I want my program to output rows*columns in that many rows and columns. For instance, table(2,3) would output

1 2 3
4 5 6 

So far I have

    def table(rows, columns):
         print(*range(1,rows*columns+1))

It prints rows*columns, but I don’t know how to print it in a tabular format. Thank you for the help.

All topic

something wrong with my python code relating to multivariate linear regresssion

import numpy as np
alpha=0.001
iters=10000
def linear_regression(X,Y):
    W=np.random.randn(1,X.shape[0])
    cost = np.zeros(iters)
    for i in range(iters):
        W = W - (alpha / len(X))*np.sum(np.dot(X,np.dot(X , W.T)) - Y)
        cost[i] = computeCost(X, Y, W)
    return W
def computeCost(X,Y,W):
    to = np.power((np.dot(X , W.T)-Y),2)
    return np.sum(to)/(2 * len(X))

this is requirement:
In this machine problem, you will implement multivariate linear regression. You’re required to define a function called linear_regression that takes in:
1. X: n * f matrix
2. Y: n * 1 array
Note: that f is number of features, not including the constant (1-vector) used for bias. Your function should return w, an (f+1, 1) numpy array where the first f elements are coefficients from regression, and w[f] is the bias term.

I want to ask is there anything wrong with my code?

All topic

How to link against Boost.Python when library name varies?

To build a module using Boost.Python I use the following command:

g++ -Wall -o $EXT_NAME.so -fPIC -shared $CFLAGS $SRC_NAME.cpp $LIBS

It’s easy to point GCC at Python headers, pkg-config --cflags python3 gives me the correct path. However, Boost.Python requires me to provide a precise name in the -l parameter which is sometimes -lboost_python3, sometimes -lboost_python-py36 (or -py37 or whatever).

I tried CMake, but its FIND_PACKAGE(Boost COMPONENTS python3) does not work reliably. For example, CMake 3.12 on Debian testing fails to find the library despite detecting Boost as a whole.

What tool to use to find the exact name of the Boost.Python library for Python 3?

All topic

Any simple way to iterate through a c# array like in python, which allows going out of range?

How to achieve similar behavior in c# like in python lists and arrays?
Is there any existing class?

var colors = new Color [4] colors;
(colors[6] == colors[2] == colors[-2]) // Exception, and it would be false, but not in python

I have tried this, but there seems to be a bug somewhere and I just wonder if there is an existing solution for c#.

    public class SafeArray
{
    public T[] data { get; private set; }
    private short index = 0;

    public SafeArray(T[] values, short DefaultIndex = 0)
    {
        data = values;
        index = DefaultIndex;
    }

    public T Get(int delta, bool MoveIndex = false)
    {
        try
        {
            var value = data[delta];
            if (MoveIndex) index = (short)delta;
            return value;
        }

        catch
        {
            // normalize to the array's length, e.g. if delta = 18 and array size 5, subtract 15 from delta 
            delta -= (int)(Mathf.Floor(Mathf.Clamp((float)(delta / data.Length), 0, float.MaxValue)) * data.Length);

            if (index + delta < 0) delta = data.Length - Mathf.Abs(delta + index);

            if (index + delta > data.Length) delta = delta - (data.Length - index);

            if (MoveIndex) index = (short)delta;

            return data[delta];
        }

    }

}

All topic

2-way ANOVA in Python statsmodels yields different Sum of Squares than SPSS

I am learning to use Python for my statistical analyses, and while figuring out how to perform a 2-way ANOVA with statsmodels I found that my Python code yielded slightly aberrant values. Comparing the outputs you can see that the SS_Factor_1 values, and the Adjusted R2 are different for Python vs SPSS/Graphpad. Is this because of a mistake in my code, or some other reason? Are these differences due to something inherent in each software and so small I should just ignore them?

Python code:

formula = 'dependent_variable ~ C(factor_1) * C(factor_2)'
model = ols(formula, data=df_freq_time).fit()
aov_table = anova_lm(model, typ=2)
aov_table

Python output:
output

Also R2 = 0.722, and adj R2 = 0.694

SPSS 2-way ANOVA results:
SPSS output ANOVA table

Graphpad Prism 2-way ANOVA results:
Graphpad output ANOVA table

All topic

Is it possible to communicate with Arduino and Python wireless? [on hold]

What I wonder is how can I communicate (Serial communication) Arduino and Python without USB connection.
Is communication impossible without wireless module or USB connection?

If someone made a robot with Arduino and Python, how can it communicate with Python without them?

All topic