const square = (x) => x * x
const multiply = (x, y) => {
return x * y;}
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((x) => x * 2);
// doubled is now [2, 4, 6, 8, 10]
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = numbers.filter((x) => x % 2 === 0);
// evens is now [2, 4, 6, 8, 10]
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, x) => acc + x, 0);
// sum is now 15
const words = ['apple', 'banana', 'cherry', 'date'];
const sorted = words.sort((a, b) => a.localeCompare(b));
// sorted is now ['apple', 'banana', 'cherry', 'date']
const numbers = [1, 3, 5, 2, 4, 6];
const firstEven = numbers.find((x) => x % 2 === 0);
// firstEven is now 2
const data = ['apple', 'banana', 'cherry', 'date'];
const allStrings = data.every((x) => typeof x === 'string');
// allStrings is now true
const numbers = [1, 2, 3, 4, 5];
const hasOdds = numbers.some((x) => x % 2 !== 0);
// hasOdds is now true
select
warehouse_name,
sum(credits_used_cloud_services) credits_used_cloud_services,
sum(credits_used) credits_used
from Snowflake.account_usage.warehouse_history
where
start_time >= '2020-01-01 00:00:01'
group by 1;
select
warehouse_name,
sum(credits_used_cloud_services) credits_used_cloud_services,
sum(credits_used) credits_used
from Snowflake.account_usage.warehouse_history
where
start_time >= '2020-01-01 00:00:01'
group by 1;
select
query_type,
sum(credits_used_cloud_services) as cloud_services_credits
from Snowflake.account_usage.query_history
where
start_time >= '2020-01-01 00:00:01'
group by 1;
Example:
"mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]",
DNS Seed List: Use the prefix "mongodb+srv://" for this type of connection URI.
Example:
"mongodb+srv://server.example.com/"
mongoexport --db users --collection cont_collects --type=csv --fields contact_name,contact_address --out /opt/exports/csv/cnts.csv
contact_name,contact_address
Elon Wick,27 Manhattan
John Musk,911 Martian Town
For example, you can specify the "contact_name" and "contact_address" fields in a file named "contact_fields.txt":
contact_name
contact_address
mongoexport --db users --collection cont_collects --type=csv --fields contact_name,contact_address --query '{"last_updated_time": {"$gt":
1548930176}}' --out /opt/exports/csv/cnts.csv
To copy a file to GCS:
gsutil cp file.csv gs://my-bucket
To copy an entire folder:
gsutil -m cp -r folder gs://my-bucket
If the files to be copied are already in S3, the following command can be used:
gsutil cp s3://my-bucket/file.csv gs://my-bucket
bq load --source_format=[FORMAT_NAME][DATASET_NAME].[TABLE_NAME] [SOURCE_PATH] [INLINE_SCHEMA]
[FORMAT_NAME] is CSV.
[DATASET_NAME] is an existing dataset in BigQuery.
[TABLE_NAME] is the name of the table where the data should be loaded
[SOURCE_PATH] is the Cloud Storage URI of the data files.
[INLINE_SCHEMA] is a valid schema to describe the data.
The schema can be a local JSON file or can be specified directly.
To overwrite the target table:
bq load --source_format=CSV --overwrite [DATASET_NAME].[TABLE_NAME] [SOURCE_PATH] [INLINE_SCHEMA]
To append to the target table:
bq load --source_format=CSV --append [DATASET_NAME].[TABLE_NAME] [SOURCE_PATH] [INLINE_SCHEMA]
UPDATE final_table
SET final_table.field1 = interm_delta_table.field1,
final_table.field2 = interm_delta_table.field2
FROM interm_delta_table
WHERE final_table.key = interm_delta_table.key;
INSERT INTO final_table
SELECT *
FROM interm_delta_table
WHERE interm_delta_table.key NOT IN (SELECT Key FROM final_table);
DELETE FROM final_table
WHERE Key IN (SELECT Key FROM interm_delta_table);
INSERT INTO final_table
import requests
response = requests.get('https://api.example.com/endpoint')
print(response.status_code)
print(response.text)
import requests
response = requests.get('https://api.example.com/endpoint')
This will send a GET request to the specified endpoint and store the response in the response variable. You can then access the response data like this:
print(response.status_code) # Print the status code
print(response.text) # Print the response text
print(response.headers) # Print the response headers
params = {'key': 'value'}
response = requests.get('https://api.example.com/endpoint', params=params)
To send headers with the request, you can pass a dictionary as the headers argument:
headers = {'Authorization': 'Bearer abc123'}
response = requests.get('https://api.example.com/endpoint', headers=headers)
import requests
data = {'key': 'value'} # Data to be sent to the server
response = requests.post('https://api.example.com/endpoint', data=data)
import requests
data = {'key': 'value'} # Data to be sent to the server
response = requests.put('https://api.example.com/endpoint', data=data)
import requests
data = {'key': 'value'} # Data to be sent to the server
response = requests.patch('https://api.example.com/endpoint', data=data)
import requests
response = requests.delete('https://api.example.com/endpoint')
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
</book>
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"year": 1925
}
GET /cars HTTP/1.1
Host: api.vehicleinventory.com
A successful response to this request might look like this:
HTTP/1.1 200 OK
Content-Type: application/json
[
{
"id": 1,
"make": "Toyota",
"model": "Camry",
"year": 2020
},
{
"id": 2,
"make": "Honda",
"model": "Accord",
"year": 2021
}
]
GET /cars HTTP/1.1
Host: api.vehicleinventory.com
A successful response to this request might look like this:
HTTP/1.1 200 OK
Content-Type: application/json
[
{
"id": 1,
"make": "Toyota",
"model": "Camry",
"year": 2020
}
POST /cars HTTP/1.1
Host: api.vehicleinventory.com
Content-Type: application/json
{
"make": "Ford",
"model": "Mustang",
"year": 2022
}
A successful response to this request might look like this:
HTTP/1.1 201 Created
Content-Type: application/json
Location: /cars/3
{
"id": 3,
"make": "Ford",
"model": "Mustang",
"year": 2022
}
PUT /cars/3 HTTP/1.1
Host: api.vehicleinventory.com
Content-Type: application/json
{
"make": "Ford",
"model": "Mustang",
"year": 2023
}
A successful response to this request might look like this:
HTTP/1.1 201 OK
Content-Type: application/json
{
"id": 3,
"make": "Ford",
"model": "Mustang",
"year": 2023
}
PATCH /cars/3 HTTP/1.1
Host: api.vehicleinventory.com
{
"year": 2024
}
A successful response to this request might look like this:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 3,
"make": "Ford",
"model": "Mustang",
"year": 2024
}
DELETE /cars/3 HTTP/1.1
Host: api.vehicleinventory.com
A successful response to this request might look like this:
HTTP/1.1 204 No Content
GET /cars/99 HTTP/1.1
Host: api.vehicleinventory.com
In this case, you might return a response like this:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": "Car not found"
}
POST /cars HTTP/1.1
Host: api.vehicleinventory.com
Content-Type: application/x-www-form-urlencoded
make=Ford&model=Mustang&year=2022
In this case, you might return a response like this:
HTTP/1.1 415 Unsupported Media Type
Content-Type: application/json
{
"error": "Unsupported media type"
}
POST /cars HTTP/1.1
Host: api.vehicleinventory.com
Content-Type: application/json
{
"make": "Tesla",
"model": "Cybertruck",
"year": 2025,
"num_wheels": 6
}
In this case, you might return a response like this:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": "Invalid car data"
}
import requests
response = requests.get(
'https://api.example.com/endpoint',
auth=('username', 'password')
)
import requests
session = requests.Session()
You can then use the session object to make requests just like you would with the get, post, put, and delete functions. For example:
response = session.get("http://api.example.com/endpoint")
import requests
response = requests.get("http://www.example.com")
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
You can also use the Response.status_code attribute to check the status code and handle errors as needed manually. For example:
if response.status_code == 404:
print("Page not found")
elif response.status_code == 500:
print("Server error occurred")
# countryapi/settings.py
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"countries",
]
from django.db import models
class Country(models.Model):
name = models.CharField(max_length=200)
capital = models.CharField(max_length=200)
area = models.IntegerField()
[ { "model": "nations.country", "pk": 1, "fields": { "name": "United States", "capital": "Washington D.C.", "area": 9833520 } }, { "model": "nations.country", "pk": 2, "fields": { "name": "Mexico", "capital": "Mexico City", "area": 1964375 } }, { "model": "nations.country", "pk": 3, "fields": { "name": "Canada", "capital": "Ottawa", "area": 9984670 } }]
from rest_framework import serializers
from .models import Country
class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = ('name', 'capital', 'area')
from rest_framework import viewsets
from .serializers import CountrySerializer
from .models import Country
class CountryViewSet(viewsets.ModelViewSet):
serializer_class = CountrySerializer
queryset = Country.objects.all()
from django.urls import include, path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('countries', views.CountryViewSet)
urlpatterns = [
path('', include(router.urls)),
]
urlpatterns = [ path('admin/', admin.site.urls),]
with this code:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('nations.urls')),
]
[ { "name": "United States", "capital": "Washington D.C.", "area": 9833520}, { "name": "Mexico","capital": "Mexico City", "area": 1964375 }, { "name": "Canada", "capital": "Ottawa", "area": 9984670}]
/api/countries/: a list view that allows you to retrieve a list of all countries in the database.
/api/countries/1/: a detail view that allows you to retrieve a specific country by its primary key.
/api/countries/1/update/: an update view that allows you to update a specific country.
/api/countries/create/: a create view that allows you to create a new country.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
@app.route('/countries')
def list_countries():
countries = [
{'name': 'United States', 'capital': 'Washington D.C.', 'area': 9833520},
{'name': 'Mexico', 'capital': 'Mexico City', 'area': 1964375},
{'name': 'Canada', 'capital': 'Ottawa', 'area': 9984670},
]
return {'countries': countries}
# app.py
from fastapi import FastAPI
from pydantic import BaseModel, Field
def _find_next_id():
return max(country.country_id for country in countries) + 1
class Country(BaseModel):
country_id: int = Field(default_factory=_find_next_id, alias="id")
name: str
capital: str
area: int
countries = [
Country(id=1, name="Thailand", capital="Bangkok", area=513120),
Country(id=2, name="Australia", capital="Canberra", area=7617930),
Country(id=3, name="Egypt", capital="Cairo", area=1010408),
]
@app.get("/countries")
async def get_countries():
return countries
@app.post("/countries", status_code=201)
async def add_country(country: Country):
countries.append(country)
return country
from fastapi import FastAPI
app = FastAPI()
@app.get("/nations")
def read_nations():
return [{'name': 'United States', 'capital': 'Washington D.C.', 'area': 914749.09},
{'name': 'Russia', 'capital': 'Moscow', 'area': 17075400.0},
{'name': 'China', 'capital': 'Beijing', 'area': 9596961.0}]
@app.post("/countries")
def create_country(country: Country):
return {'name': country.name, 'capital': country.capital, 'area': country.area}
@app.get("/countries")
def read_countries():
return countries
from fastapi import FastAPI, BaseModel
class Country(BaseModel):
name: str
capital: str
area: float
class Country(BaseModel):
id: int = Field(..., alias="id")
import requests
data = {'title': 'My New Post', 'body': 'This is the body of my new post', 'userId': 1}
response = requests.post('https://jsonplaceholder.typicode.com/posts', json=data)
if response.status_code == 201:
# Successful request
post = response.json()
print(post)
else:
# Request failed
print('Request failed with status code', response.status_code)
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts')
if response.status_code == 200:
# Successful request
post = response.json()
print(post)
else:
# Request failed
print('Request failed with status code', response.status_code)
import requests
params = {'userId': 1}response = requests.get('https://jsonplaceholder.typicode.com/posts', params=params)
if response.status_code == 200:
# Successful request
posts = response.json()
print(posts)
else: # Request failed
print('Request failed with status code', response.status_code)
import requests
data = {'title': 'My New Post', 'body': 'This is the body of my new post', 'userId': 1}
response = requests.post('https://jsonplaceholder.typicode.com/posts', json=data)
if response.status_code == 201:
# Successful request
post = response.json()
print(post)else:
# Request failed
print('Request failed with status code', response.status_code)
import requests
data = {'title': 'Updated Title', 'body': 'Updated body', 'userId': 1}
response = requests.put('https://jsonplaceholder.typicode.com/posts/1', json=data)
if response.status_code == 200:
# Successful request
post = response.json()
print(post)else:
# Request failed
print('Request failed with status code', response.status_code)
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts')
if response.status_code == 200:
# Successful request
headers = response.headers
print(headers)
else
# Request failed
print('Request failed with status code', response.status_code)
import requests
from base64 import b64encode
# Set the username and password
username = 'user'
password = 'pass'
# Encode the credentials
credentials = b64encode(f'{username}:{password}'.encode('utf-8')).decode('utf-8')
# Set the `Authorization` header
headers = {'Authorization': f'Basic {credentials}'}
# Send the request
response = requests.get('https://example.com/api/protected', headers=headers)
import requests
# Set the token
token = 'your-token-here'
# Set the `Authorization` header
headers = {'Authorization': f'Token {token}'}
# Send the request
response = requests.get('https://example.com/api/protected', headers=headers)
import requests
# Set the access token
access_token = 'your-access-token-here'
# Set the `Authorization` header
headers = {'Authorization': f'Bearer {access_token}'}
# Send the request
response = requests.get('https://example.com/api/protected', headers=headers)
import requests
# Obtain an access token using the OAuth2 flow
# Set the access token
access_token = 'your-access-token-here'
# Create a session
session = requests.Session()
# Set the `Authorization` header in the session
session.headers.update({'Authorization': f'Bearer {access_token}'})
# Send a request using the sessionresponse = session.get('https://example.com/api/protected')
import requests
try:
response = requests.get('http://www.example.com')
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err)
import requests
response = requests.get('http://www.example.com')
if response.status_code >= 400:
print("An error occurred:", response.status_code)
try:
response = requests.get('http://api.open-notify.org/astros.json')
response.raise_for_status()
# Code here will only run if the request is successful
except requests.exceptions.TooManyRedirects as error:
print(error).
You may specify the maximum number of redirects using the request options:
response = requests.get('http://api.open-notify.org/astros.json', max_redirects=2)
Alternatively, you may deactivate redirecting entirely in your request options:
response = requests.get('http://api.open-notify.org/astros.json', allow_redirects=False)
try:
response = requests.get('http://api.open-notify.org/astros.json')
# Code here will only run if the request is successful
except requests.ConnectionError as error:
print(error)
try:
response = requests.get('http://api.open-notify.org/astros.json', timeout=0.00001)
# Code here will only run if the request is successful
except requests. Timeout as error:
print(error)
import pyodbc
# Connect to the database using a DSN
cnxn =
pyodbc.connect("DSN=mydsn;UID=myusername;PWD=mypassword")
# Create a cursor
cursor = cnxn.cursor()
# Execute a query
cursor.execute("SELECT * FROM mytable")
# Fetch the results
results = cursor.fetchall()
# Iterate over the results and print each row
for row in results: print(row)
# Close the cursor and connection
cursor.close()
cnxn.close()
import pyodbc
# Connect to the database using a driver
cnxn = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};SERVER=my server;DATABASE=mydatabase;UID=myusername;PWD=mypassword")
pip install pyodbc
import pyodbc
cnxn = pyodbc.connect("DSN=mydsn;UID=myusername;PWD=mypassword")
cursor = cnxn.cursor()
# Execute a query
cursor.execute("SELECT * FROM mytable")
# Fetch the results
results = cursor.fetchall()
# Iterate over the results and print each row
for row in results:
print(row)
# Close the cursor and connection
cursor.close()
cnxn.close()
import pyodbc
# Connect to the database using a DSN
cnxn = pyodbc.connect("DSN=mydsn;UID=myusername;PWD=mypassword")
# Create a cursor
cursor = cnxn.cursor()
# Execute a query
cursor.execute("SELECT * FROM mytable")
# Fetch the results
results = cursor.fetchall()
# Iterate over the results and print each row
for row in results:
print(row)
pyodbc sql server
# Close the cursor and connection
cursor.close()
cnxn.close()
Specify the --read-from-remote-server option.
--host: Specify the DNS name from the instance's endpoint.
--port: Specify the port used by the instance.
--user: Specify a MySQL user that has been granted the replication slave permission.
--password: Specify the password for the user, or omit a password value so that the utility prompts you for a password.
To download the file in binary format, specify the --raw option.
--result-file: Specify the local file to receive the raw output.
mysqlbinlog \
--read-from-remote-server \
--host=MySQL56Instance1.cg034hpkmmjt.region.rds.amazonaws.com \
--port=3306 \
--user ReplUser \
--password \
--raw \
--result-file=/tmp/ \
Binlog.00098
mysqlbinlog ^
--read-from-remote-server ^
--host=MySQL56Instance1.cg034hpkmmjt.region.rds.amazonaws.com ^
--port=3306 ^
--user ReplUser ^
--password ^
--raw ^
--result-file=/tmp/ ^
Binlog.00098
log-bin = /var/lib/mysql/mysql-bin
expire_logs_days = 2
binlog_format=mixed
Alternatively, you can set the "log-bin" variable to a specific file path, such as:
log-bin = /var/lib/mysql/-mysql-bin.log
Once you have made the necessary changes to the configuration file, you can restart the MySQL server to apply the changes.
To verify that BinLogs is enabled, you can use the "SHOW VARIABLES LIKE 'log_bin'" command. If the value of the "log_bin" variable is "ON," it indicates that BinLogs is enabled. If the value is "OFF," you can use the "SET GLOBAL log_bin = ON" command to enable BinLogs.