1622779518
I started looking into Heroku as an option for creating personal applications in my free time. In fact, I converted an existing application from the AWS ecosystem to Heroku which was captured in a series on DZone.com:
Moving Away From AWS and Onto Heroku
Starting with a brand new idea with Heroku, I was able to quickly create a fitness-based SaaS solution as well, which was documented in another series on DZone.com:
Using Heroku to Quickly Build a Multi-Tenant SaaS Product
Well over a year into using Heroku for several of my applications, I thought I would take a step back and describe how Heroku works and offer thoughts on why the Salesforce-owned solution should be a consideration for your next project.
Founded in 2007, Heroku is a platform as a service (PaaS) ecosystem which currently supports Ruby, Java, Node.js, Scala, Clojure, Python, PHP, and Go programming languages (plus community support for many other languages). Because of its ability to support multiple languages to accomplish the same result, Heroku is considered a polyglot platform.
At the highest level, Heroku intends to serve the needs of applications looking for a place to live. Developers get started by creating a Heroku “app” and introduce their original code via a standardized git repository. Heroku simply takes things from there—building and deploying the application, then serving it up for consumption as needed. This includes static resources (like an Angular or React.js application), which can be served from a Node.js implementation.
Heroku provides over 175 add-on services to complement each app, featuring:
#heroku #java #go #node #clojure #php
1647852120
Cuando me encontré por primera vez con las funciones lambda en python, estaba muy intimidado y pensé que eran para Pythonistas avanzados. Los tutoriales de Python para principiantes aplauden el lenguaje por su sintaxis legible, pero las lambdas ciertamente no parecían fáciles de usar.
Sin embargo, una vez que entendí la sintaxis general y examiné algunos casos de uso simples, usarlos fue menos aterrador.
En pocas palabras, una función lambda es como cualquier función de python normal, excepto que no tiene nombre al definirla y está contenida en una línea de código.
lambda argument(s): expression
Una función lambda evalúa una expresión para un argumento dado. Le das a la función un valor (argumento) y luego proporcionas la operación (expresión). La palabra clave lambda
debe ir primero. Dos puntos completos (:) separan el argumento y la expresión.
En el código de ejemplo siguiente, x es el argumento y x+x es la expresión.
#Normal python function
def a_name(x):
return x+x
#Lambda function
lambda x: x+x
Antes de entrar en aplicaciones prácticas, mencionemos algunos aspectos técnicos sobre lo que la comunidad de python cree que es bueno y malo con las funciones lambda.
ventajas
Contras
def
función normal (por ejemplo, operaciones condicionales anidadas). Si necesita uno o dos minutos para entender el código, use una función con nombre en su lugar.def
función normal.Al final de este artículo, veremos ejemplos de código de uso común en los que se desaconsejan las funciones de Lambda aunque parezcan legítimas.
Pero primero, veamos situaciones en las que usar funciones lambda. Tenga en cuenta que usamos mucho las funciones lambda con las clases de Python que toman una función como argumento, por ejemplo, map() y filter(). Estas también se llaman funciones de orden superior .
Esto es cuando ejecuta una función lambda en un solo valor.
(lambda x: x*2)(12)
###Results
24
En el código anterior, la función se creó y luego se ejecutó inmediatamente. Este es un ejemplo de una expresión de función invocada inmediatamente o IIFE .
Filtrar(). Esta es una biblioteca incorporada de Python que devuelve solo aquellos valores que se ajustan a ciertos criterios. La sintaxis es filter(function, iterable)
. El iterable puede ser cualquier secuencia, como una lista, un conjunto o un objeto de serie (más abajo).
El siguiente ejemplo filtra una lista por even
números. Tenga en cuenta que la función de filtro devuelve un 'Objeto de filtro' y debe encapsularlo con una lista para devolver los valores.
list_1 = [1,2,3,4,5,6,7,8,9]
filter(lambda x: x%2==0, list_1)
### Results
<filter at 0xf378982348>
list(filter(lambda x: x%2==0, list_1))
###Results
[2, 4, 6, 8]
Mapa(). Esta es otra biblioteca de python incorporada con la sintaxismap(function, iterable).
Esto devuelve una lista modificada en la que todos los valores de la lista original se han cambiado en función de una función. El siguiente ejemplo reduce al cubo todos los números de la lista.
list_1 = [1,2,3,4,5,6,7,8,9]
cubed = map(lambda x: pow(x,3), list_1)
list(cubed)
###Results
[1, 8, 27, 64, 125, 216, 343, 512, 729]
Un objeto Serie es una columna en un marco de datos, o dicho de otra manera, una secuencia de valores con índices correspondientes. Las funciones Lambda se pueden usar para manipular valores dentro de un marco de datos de Pandas .
Vamos a crear un marco de datos ficticio sobre los miembros de una familia.
import pandas as pd
df = pd.DataFrame({
'Name': ['Luke','Gina','Sam','Emma'],
'Status': ['Father', 'Mother', 'Son', 'Daughter'],
'Birthyear': [1976, 1984, 2013, 2016],
})
Lambda con función Apply() de Pandas. Esta función aplica una operación a cada elemento de la columna.
Para obtener la edad actual de cada miembro, restamos su año de nacimiento del año actual. En la siguiente función lambda, x se refiere a un valor en la columna del año de nacimiento y la expresión es 2021(current year) minus the value
.
df['age'] = df['Birthyear'].apply(lambda x: 2021-x)
Lambda con la función Filter() de Python . Esto toma 2 argumentos; uno es una función lambda con una expresión de condición, dos un iterable que para nosotros es un objeto de serie. Devuelve una lista de valores que cumplen la condición.
list(filter(lambda x: x>18, df['age']))
###Results
[45, 37]
Lambda con función Map() de Pandas. El mapa funciona de manera muy similar a apply() en el sentido de que modifica los valores de una columna en función de la expresión.
#Double the age of everyone
df['double_age'] =
df['age'].map(lambda x: x*2)
También podemos realizar operaciones condicionales que devuelven diferentes valores en función de ciertos criterios.
El siguiente código devuelve 'Masculino' si el valor de Estado es padre o hijo, y devuelve 'Femenino' en caso contrario. Tenga en cuenta que apply
y map
son intercambiables en este contexto.
#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')
Principalmente uso funciones de Lambda en columnas específicas (objeto de serie) en lugar de todo el marco de datos, a menos que quiera modificar todo el marco de datos con una expresión.
Por ejemplo, redondear todos los valores a 1 lugar decimal, en cuyo caso todas las columnas deben ser tipos de datos flotantes o int porque round() no puede funcionar en cadenas.
df2.apply(lambda x:round(x,1))
##Returns an error if some
##columns are not numeric
En el siguiente ejemplo, usamos aplicar en un marco de datos y seleccionamos las columnas para modificar en la función Lambda. Tenga en cuenta que debemos usar axis=1
aquí para que la expresión se aplique en forma de columna.
#convert to lower-case
df[['Name','Status']] =
df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)
def
si desea almacenar la función para su reutilización.#Bad
triple = lambda x: x*3
#Good
def triple(x):
return x*3
2. Pasar funciones dentro de funciones Lambda. El uso de funciones como abs
las que solo toman un argumento numérico no es necesario con Lambda porque puede pasar la función directamente a map() o apply().
#Bad
map(lambda x:abs(x), list_3)
#Good
map(abs, list_3)
#Good
map(lambda x: pow(x, 2), float_nums)
Idealmente, las funciones dentro de las funciones lambda deberían tomar dos o más argumentos. Los ejemplos son pow(number,power)
y round(number,ndigit).
puede experimentar con varias funciones de python integradas para ver cuáles necesitan funciones de Lambda en este contexto. Lo he hecho en este cuaderno .
3. Usar funciones de Lambda cuando varias líneas de código son más legibles . Un ejemplo es cuando usa declaraciones if-else dentro de la función lambda. Utilicé el siguiente ejemplo anteriormente en este artículo.
#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')
Los mismos resultados se pueden lograr con el siguiente código. Prefiero esta forma porque puedes tener infinitas condiciones y el código es bastante simple de seguir. Más sobre condiciones vectorizadas aquí .
Muchos programadores a los que no les gustan las Lambdas generalmente argumentan que puede reemplazarlas con las listas de comprensión más comprensibles, las funciones integradas y las bibliotecas estándar. Las expresiones generadoras (similares a las listas de comprensión) también son alternativas prácticas a las funciones map() y filter().
Ya sea que decida o no adoptar las funciones de Lambda en su código, debe comprender qué son y cómo se usan porque inevitablemente las encontrará en el código de otras personas.
Fuente: https://towardsdatascience.com/lambda-functions-with-practical-examples-in-python-45934f3653a8
1647851880
Pythonでラムダ関数に最初に出会ったとき、私は非常に恐れていて、それらが高度なPythonista用であると思いました。初心者のPythonチュートリアルは、その言語の読みやすい構文を称賛していますが、ラムダは確かにユーザーフレンドリーではないようです。
ただし、一般的な構文を理解し、いくつかの単純なユースケースを検討すると、それらを使用することはそれほど怖くありませんでした。
簡単に言うと、ラムダ関数は通常のPython関数と同じですが、定義時に名前がなく、1行のコードに含まれている点が異なります。
lambda argument(s): expression
ラムダ関数は、指定された引数の式を評価します。関数に値(引数)を指定してから、演算(式)を指定します。キーワードlambda
が最初に来る必要があります。完全なコロン(:)は、引数と式を区切ります。
以下のサンプルコードでは、xが引数で、x+xが式です。
#Normal python function
def a_name(x):
return x+x
#Lambda function
lambda x: x+x
実際のアプリケーションに入る前に、Pythonコミュニティがラムダ関数の良い点と悪い点についていくつかの技術について言及しましょう。
長所
短所
def
(ネストされた条件付き操作など)には適していません。コードを理解するのに1、2分必要な場合は、代わりに名前付き関数を使用してください。def
。この記事の最後では、Lambda関数が正当であるように見えても推奨されない、一般的に使用されるコード例を見ていきます。
ただし、最初に、ラムダ関数を使用する場合の状況を見てみましょう。map()やfilter()などの関数を引数として受け取るPythonクラスでは、ラムダ関数を頻繁に使用することに注意してください。これらは高階関数とも呼ばれます。
これは、単一の値に対してラムダ関数を実行する場合です。
(lambda x: x*2)(12)
###Results
24
上記のコードでは、関数が作成され、すぐに実行されました。これは、即時に呼び出される関数式またはIIFEの例です。
フィルター()。これは、特定の基準に適合する値のみを返すPython組み込みライブラリです。構文はfilter(function, iterable)
です。iterableは、リスト、セット、またはシリーズオブジェクト(以下で詳しく説明します)などの任意のシーケンスにすることができます。
以下の例では、数値のリストをフィルタリングしeven
ます。filter関数は「Filterobject」を返すため、値を返すにはリストでカプセル化する必要があることに注意してください。
list_1 = [1,2,3,4,5,6,7,8,9]
filter(lambda x: x%2==0, list_1)
### Results
<filter at 0xf378982348>
list(filter(lambda x: x%2==0, list_1))
###Results
[2, 4, 6, 8]
地図()。これは、構文が含まれるもう1つの組み込みのPythonライブラリです。map(function, iterable).
これにより、元のリストのすべての値が関数に基づいて変更された変更済みリストが返されます。以下の例では、リスト内のすべての数値を3乗しています。
list_1 = [1,2,3,4,5,6,7,8,9]
cubed = map(lambda x: pow(x,3), list_1)
list(cubed)
###Results
[1, 8, 27, 64, 125, 216, 343, 512, 729]
Seriesオブジェクトは、データフレーム内の列、言い換えると、対応するインデックスを持つ値のシーケンスです。Lambda関数を使用して、Pandasデータフレーム内の値を操作できます。
家族のメンバーに関するダミーのデータフレームを作成しましょう。
import pandas as pd
df = pd.DataFrame({
'Name': ['Luke','Gina','Sam','Emma'],
'Status': ['Father', 'Mother', 'Son', 'Daughter'],
'Birthyear': [1976, 1984, 2013, 2016],
})
PandasによるApply()関数を使用したLambda 。この関数は、列のすべての要素に操作を適用します。
各メンバーの現在の年齢を取得するために、現在の年からその誕生年を差し引きます。以下のラムダ関数では、xはbirthyear列の値を指し、式は2021(current year) minus the value
です。
df['age'] = df['Birthyear'].apply(lambda x: 2021-x)
PythonのFilter()関数を使用したLambda 。これには2つの引数が必要です。1つは条件式を使用したラムダ関数で、2つは反復可能で、これはシリーズオブジェクトです。条件を満たす値のリストを返します。
list(filter(lambda x: x>18, df['age']))
###Results
[45, 37]
PandasによるMap()関数を使用したLambda 。Mapは、式に基づいて列の値を変更するという点で、apply()と非常によく似ています。
#Double the age of everyone
df['double_age'] =
df['age'].map(lambda x: x*2)
特定の基準に基づいて異なる値を返す条件付き操作を実行することもできます。
以下のコードは、Status値が父親または息子の場合は「男性」を返し、それ以外の場合は「女性」を返します。このコンテキストでは、apply
とは交換可能であることに注意してください。map
#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')
1つの式でデータフレーム全体を変更する場合を除いて、データフレーム全体ではなく、特定の列(シリーズオブジェクト)でLambda関数を使用することがほとんどです。
たとえば、すべての値を小数点以下1桁に丸めます。この場合、round()は文字列では機能しないため、すべての列はfloatまたはintデータ型である必要があります。
df2.apply(lambda x:round(x,1))
##Returns an error if some
##columns are not numeric
以下の例では、データフレームに適用を使用し、Lambda関数で変更する列を選択します。式が列単位で適用されるように、ここで使用する必要があることに注意してください。axis=1
#convert to lower-case
df[['Name','Status']] =
df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)
def
関数を再利用のために保存する場合は、通常の関数を使用してください。#Bad
triple = lambda x: x*3
#Good
def triple(x):
return x*3
2.Lambda関数内で関数を渡します。abs
関数をmap()またはapply()に直接渡すことができるため、Lambdaでは1つの数値引数のみを取るような関数を使用する必要はありません。
#Bad
map(lambda x:abs(x), list_3)
#Good
map(abs, list_3)
#Good
map(lambda x: pow(x, 2), float_nums)
理想的には、ラムダ関数内の関数は2つ以上の引数を取る必要があります。例は次のとおりです。さまざまな組み込みのPython関数を試してpow(number,power)
、このコンテキストでLambda関数が必要な関数を確認できます。私はこのノートブックでそうしました。round(number,ndigit).
3.複数行のコードが読みやすい場合にLambda関数を使用します。例として、ラムダ関数内でif-elseステートメントを使用している場合があります。この記事の前半で、以下の例を使用しました。
#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')
以下のコードでも同じ結果が得られます。私はこの方法を好みます。なぜなら、あなたは無限の条件を持つことができ、コードは従うのに十分単純だからです。ベクトル化された条件の詳細については、こちらをご覧ください。
Lambdasが気に入らない多くのプログラマーは、通常、Lambdasをより理解しやすいリスト内包表記、組み込み関数、および標準ライブラリに置き換えることができると主張しています。ジェネレータ式(リスト内包表記と同様)も、map()およびfilter()関数の便利な代替手段です。
Lambda関数をコードに含めるかどうかに関係なく、他の人のコードで必然的にLambda関数に遭遇するため、それらが何であるか、およびそれらがどのように使用されるかを理解する必要があります。
ソース:https ://towardsdatascience.com/lambda-functions-with-practical-examples-in-python-45934f3653a8
1647930480
When I first came across lambda functions in python, I was very much intimidated and thought they were for advanced Pythonistas. Beginner python tutorials applaud the language for its readable syntax, but lambdas sure didn’t seem user-friendly.
However, once I understood the general syntax and examined some simple use cases, using them was less scary.
Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code.
lambda argument(s): expression
A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression). The keyword lambda
must come first. A full colon (:) separates the argument and the expression.
In the example code below, x is the argument and x+x is the expression.
#Normal python function
def a_name(x):
return x+x
#Lambda function
lambda x: x+x
Before we get into practical applications, let’s mention some technicalities on what the python community thinks is good and bad with lambda functions.
Pros
Cons
def
function (For example nested conditional operations). If you need a minute or two to understand the code, use a named function instead.def
function.At the end of this article, we’ll look at commonly used code examples where Lambda functions are discouraged even though they seem legitimate.
But first, let’s look at situations when to use lambda functions. Note that we use lambda functions a lot with python classes that take in a function as an argument, for example, map() and filter(). These are also called Higher-order functions.
This is when you execute a lambda function on a single value.
(lambda x: x*2)(12)
###Results
24
In the code above, the function was created and then immediately executed. This is an example of an immediately invoked function expression or IIFE.
Filter(). This is a Python inbuilt library that returns only those values that fit certain criteria. The syntax is filter(function, iterable)
. The iterable can be any sequence such as a list, set, or series object (more below).
The example below filters a list for even
numbers. Note that the filter function returns a ‘Filter object’ and you need to encapsulate it with a list to return the values.
list_1 = [1,2,3,4,5,6,7,8,9]
filter(lambda x: x%2==0, list_1)
### Results
<filter at 0xf378982348>
list(filter(lambda x: x%2==0, list_1))
###Results
[2, 4, 6, 8]
Map(). This is another inbuilt python library with the syntax map(function, iterable).
This returns a modified list where every value in the original list has been changed based on a function. The example below cubes every number in the list.
list_1 = [1,2,3,4,5,6,7,8,9]
cubed = map(lambda x: pow(x,3), list_1)
list(cubed)
###Results
[1, 8, 27, 64, 125, 216, 343, 512, 729]
A Series object is a column in a data frame, or put another way, a sequence of values with corresponding indices. Lambda functions can be used to manipulate values inside a Pandas dataframe.
Let’s create a dummy dataframe about members of a family.
import pandas as pd
df = pd.DataFrame({
'Name': ['Luke','Gina','Sam','Emma'],
'Status': ['Father', 'Mother', 'Son', 'Daughter'],
'Birthyear': [1976, 1984, 2013, 2016],
})
Lambda with Apply() function by Pandas. This function applies an operation to every element of the column.
To get the current age of each member, we subtract their birth year from the current year. In the lambda function below, x refers to a value in the birthyear column, and the expression is 2021(current year) minus the value
.
df['age'] = df['Birthyear'].apply(lambda x: 2021-x)
Lambda with Python’s Filter() function. This takes 2 arguments; one is a lambda function with a condition expression, two an iterable which for us is a series object. It returns a list of values that satisfy the condition.
list(filter(lambda x: x>18, df['age']))
###Results
[45, 37]
Lambda with Map() function by Pandas. Map works very much like apply() in that it modifies values of a column based on the expression.
#Double the age of everyone
df['double_age'] =
df['age'].map(lambda x: x*2)
We can also perform conditional operations that return different values based on certain criteria.
The code below returns ‘Male’ if the Status value is father or son, and returns ‘Female’ otherwise. Note that apply
and map
are interchangeable in this context.
#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')
I mostly use Lambda functions on specific columns (series object) rather than the entire data frame, unless I want to modify the entire data frame with one expression.
For example rounding all values to 1 decimal place, in which case all the columns have to be float or int datatypes because round() can’t work on strings.
df2.apply(lambda x:round(x,1))
##Returns an error if some
##columns are not numeric
In the example below, we use apply on a dataframe and select the columns to modify in the Lambda function. Note that we must use axis=1
here so that the expression is applied column-wise.
#convert to lower-case
df[['Name','Status']] =
df.apply(lambda x: x[['Name','Status']].str.lower(), axis=1)
def
function if you want to store the function for reuse.#Bad
triple = lambda x: x*3
#Good
def triple(x):
return x*3
2. Passing functions inside Lambda functions. Using functions like abs
which only take one number- argument is unnecessary with Lambda because you can directly pass the function into map() or apply().
#Bad
map(lambda x:abs(x), list_3)
#Good
map(abs, list_3)
#Good
map(lambda x: pow(x, 2), float_nums)
Ideally, functions inside lambda functions should take two or more arguments. Examples are pow(number,power)
and round(number,ndigit).
You can experiment with various in-built python functions to see which ones need Lambda functions in this context. I’ve done so in this notebook.
3. Using Lambda functions when multiple lines of code are more readable. An example is when you are using if-else statements inside the lambda function. I used the example below earlier in this article.
#Conditional Lambda statement
df['Gender'] = df['Status'].map(lambda x: 'Male' if x=='father' or x=='son' else 'Female')
The same results can be achieved with the code below. I prefer this way because you can have endless conditions and the code is simple enough to follow. More on vectorized conditions here.
Many programmers who don’t like Lambdas usually argue that you can replace them with the more understandable list comprehensions, built-in functions, and standard libraries. Generator expressions (similar to list comprehensions) are also handy alternatives to the map() and filter() functions.
Whether or not you decide to embrace Lambda functions in your code, you need to understand what they are and how they are used because you will inevitably come across them in other peoples’ code.
Source: https://towardsdatascience.com/lambda-functions-with-practical-examples-in-python-45934f3653a8
1624175100
In my last blog , I went into how you can seed your database from an external API. This is great for grabbing information from a source other than your own backend and is a pretty essential tool for building a lot of projects. However, what happens once you’ve pushed your new project onto Heroku? What if the information you seeded is constantly updating (stocks, weekly sales, etc)? Do you plan on resetting your database every single day so your site information stays current? I mean, sure you could, but in the grand scheme of things this is going to spell out trouble for you and your project. Enter Heroku dynos and one-off dynos.
_ “Dynos are isolated, virtualized Linux containers that are designed to execute code based on a user-specified command.” -_Heroku
As the above quote mentions, dynos are containers filled with code that execute on a user-specified command. Meaning that for code bases of any size, you can store code that will simplify workflow and enhance productivity.
A one-off dyno is executable code that we can use to manage all of our administrative and maintenance tasks. Seeding our database falls into this category, but what else does? According to the Heroku website, one-off dynos can be used in the following ways:
rake db:migrate
or node migrate.js migrate
)rails console
, irb
, or node
)ruby scripts/fix_bad_records.rb
or node tally_results.js
).For this guide, we’re going to be re-seeding our database, which falls under the first category. Also, like the previous guide, I’ll be using Ruby on Rails. Before we jump in, first make sure you’ve done the following.
Now that we have all of our pieces together, it’s time to build a one-off dyno! All we need to do to get started is to build a rake task. To do this, create a file called scheduler.rake
in /app/db/lib/tasks. Once there, you can take a look at the following code.
#database #ruby-on-rails #heroku-scheduler #heroku #ruby #re-seed your heroku database everyday with one-off dynos
1622779518
I started looking into Heroku as an option for creating personal applications in my free time. In fact, I converted an existing application from the AWS ecosystem to Heroku which was captured in a series on DZone.com:
Moving Away From AWS and Onto Heroku
Starting with a brand new idea with Heroku, I was able to quickly create a fitness-based SaaS solution as well, which was documented in another series on DZone.com:
Using Heroku to Quickly Build a Multi-Tenant SaaS Product
Well over a year into using Heroku for several of my applications, I thought I would take a step back and describe how Heroku works and offer thoughts on why the Salesforce-owned solution should be a consideration for your next project.
Founded in 2007, Heroku is a platform as a service (PaaS) ecosystem which currently supports Ruby, Java, Node.js, Scala, Clojure, Python, PHP, and Go programming languages (plus community support for many other languages). Because of its ability to support multiple languages to accomplish the same result, Heroku is considered a polyglot platform.
At the highest level, Heroku intends to serve the needs of applications looking for a place to live. Developers get started by creating a Heroku “app” and introduce their original code via a standardized git repository. Heroku simply takes things from there—building and deploying the application, then serving it up for consumption as needed. This includes static resources (like an Angular or React.js application), which can be served from a Node.js implementation.
Heroku provides over 175 add-on services to complement each app, featuring:
#heroku #java #go #node #clojure #php