Unnamed: 0 int64 0 16k | text_prompt stringlengths 110 62.1k | code_prompt stringlengths 37 152k |
|---|---|---|
10,300 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Examples of the BioSCRAPE package
Biocircuit Stochastic Simulation of Single Cell Reactions and Parameter Estimation
The purpose of this Python notebook is twofold.
The first is to serve as ... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
#%config InlineBackend.figure_f.ormats=['svg']
color_list = ['r', 'k', 'b','g','y','m','c']
mpl.rc('axes', prop_cycle=(mpl.cycler('color', color_list) ))
mpl.rc('xtick', labelsize=12)
mpl.rc('ytick', labelsize=12)
import numpy as ... |
10,301 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Basics of Algorithms & Coding Tests
this notebook shows some essentials and practical python codes to help in your coding test like hackerrank or codility
Two most important things
- remove... | Python Code:
from IPython.display import Image
Image("../img/big_o1.png", width=600)
Explanation: Basics of Algorithms & Coding Tests
this notebook shows some essentials and practical python codes to help in your coding test like hackerrank or codility
Two most important things
- remove all duplicates before any itera... |
10,302 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Segmentation with tf.keras
<table class="tfo-notebook-buttons" align="left"><td>
<a target="_blank" href="http
Step1: Get all the files
Since this tutorial will be using a dataset fr... | Python Code:
!pip install kaggle
import os
import glob
import zipfile
import functools
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['axes.grid'] = False
mpl.rcParams['figure.figsize'] = (12,12)
from sklearn.model_selection import train_test_split
import matplotlib.image as mp... |
10,303 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
HTML and w3 Schools
Step1: Supporting Technologies
jQuery
Examples
Draggable Elements
https
Step2: Using the %%javascript cell magic and jQuery, we can modify the DOM node's display attrib... | Python Code:
from IPython.display import HTML, Javascript
HTML("Hello World")
Explanation: HTML and w3 Schools
End of explanation
!gvim draggable_1.html
HTML('./draggable_1.html')
Explanation: Supporting Technologies
jQuery
Examples
Draggable Elements
https://www.w3schools.com/tags/att_global_draggable.asp
https://www.... |
10,304 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Take the set of pings, make sure we have actual clientIds and remove duplicate pings. We collect each unique ping.
Step1: Transform and sanitize the pings into arrays.
Step2: Create a set ... | Python Code:
def dedupe_pings(rdd):
return rdd.filter(lambda p: p["meta/clientId"] is not None)\
.map(lambda p: (p["meta/documentId"], p))\
.reduceByKey(lambda x, y: x)\
.map(lambda x: x[1])
Explanation: Take the set of pings, make sure we have actual clientIds and remove d... |
10,305 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h1 class="title">Example-Dependent Cost-Sensitive Fraud Detection using CostCla</h1>
<center>
<h2>Alejandro Correa Bahnsen, PhD</h2>
<p>
<h2>Data Scientist</h2>
<p>
<div>
<img img class="lo... | Python Code:
import pandas as pd
import numpy as np
from costcla import datasets
from costcla.datasets.base import Bunch
def load_fraud(cost_mat_parameters=dict(Ca=10)):
# data_ = pd.read_pickle("trx_fraud_data.pk")
data_ = pd.read_pickle("/home/al/DriveAl/EasySol/Projects/DetectTA/Tests/trx_fraud_data_v3_agg.p... |
10,306 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Binary with Spots
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
Step1: As alwa... | Python Code:
#!pip install -I "phoebe>=2.3,<2.4"
Explanation: Binary with Spots
Setup
Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
End of explanation
import phoebe
from phoebe import u # units
import numpy as np
im... |
10,307 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
USA UFO sightings (Python 3 version)
This notebook is based on the first chapter sample from Machine Learning for Hackers with some added features. I did this to present Jupyter Notebook wit... | Python Code:
import pandas as pd
import numpy as np
Explanation: USA UFO sightings (Python 3 version)
This notebook is based on the first chapter sample from Machine Learning for Hackers with some added features. I did this to present Jupyter Notebook with Python 3 for Tech Days in my Job.
The original link is offline... |
10,308 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Python Basics with Numpy (optional assignment)
Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help fam... | Python Code:
### START CODE HERE ### (≈ 1 line of code)
test = "Hello World"
### END CODE HERE ###
print ("test: " + test)
Explanation: Python Basics with Numpy (optional assignment)
Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will he... |
10,309 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Applications of Linear Alebra
Step2: Variance and covariance
Remember the formula for covariance
$$
\text{Cov}(X, Y) = \frac{\sum_{i=1}^n(X_i - \bar{X})(Y_i - \bar{Y})}{n-1}
$$
where $\text... | Python Code:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
Explanation: Applications of Linear Alebra: PCA
We will explore 3 applications of linear algebra in data analysis - change of basis (for dimension reduction), projections (for solving linear systems) and the quadratic form (for optimizat... |
10,310 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Field sampling tutorial
The particle trajectories allow us to study fields like temperature, plastic concentration or chlorophyll from a Lagrangian perspective.
In this tutorial we will go ... | Python Code:
# Modules needed for the Parcels simulation
from parcels import Variable, FieldSet, ParticleSet, JITParticle, AdvectionRK4
import numpy as np
from datetime import timedelta as delta
# To open and look at the temperature data
import xarray as xr
import matplotlib as mpl
import matplotlib.pyplot as plt
Expl... |
10,311 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Grade
Step1: 1 Make a request from the Forecast.io API for where you were born (or lived, or want to visit!)
Tip
Step2: 2. What's the current wind speed? How much warmer does it feel than ... | Python Code:
import requests
Explanation: Grade: 7 / 7
End of explanation
#https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIME
response = requests.get('https://api.forecast.io/forecast/4da699cf85f9706ce50848a7e59591b7/12.971599,77.594563')
data = response.json()
#print(data)
#print(data.keys())
print("Banga... |
10,312 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2
Step1: Answer
Step2: 3
Step3: 4
Step4: 6
Step5: 7
Step6: 9
Step7: 10
Step8: 12
Step9: 13
Step10: 14
Step11: 15
Step12: Answer
Step13: 16
Step14: Answer
Step15: 18
Step16: A... | Python Code:
# We can use the set() function to convert lists into sets.
# A set is a data type, just like a list, but it only contains each value once.
car_makers = ["Ford", "Volvo", "Audi", "Ford", "Volvo"]
# Volvo and ford are duplicates
print(car_makers)
# Converting to a set
unique_car_makers = set(car_makers)
pri... |
10,313 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
This section is a walk through the pre-alignment sequence filtering in ReproPhylo. We will start by several preliminaries discussed in the previous sections
Step1: 3.5.1 Filtering by sequen... | Python Code:
from reprophylo import *
pj = unpickle_pj('outputs/my_project.pkpj', git=False)
Explanation: This section is a walk through the pre-alignment sequence filtering in ReproPhylo. We will start by several preliminaries discussed in the previous sections:
End of explanation
pj.extract_by_locus()
Explanation: 3.... |
10,314 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Pipeline for microendoscopic data processing in CaImAn using the CNMF-E algorithm
This demo presents a complete pipeline for processing microendoscopic data using CaImAn. It includes
Step1: ... | Python Code:
try:
get_ipython().magic(u'load_ext autoreload')
get_ipython().magic(u'autoreload 2')
get_ipython().magic(u'matplotlib qt')
except:
pass
import logging
import matplotlib.pyplot as plt
import numpy as np
logging.basicConfig(format=
"%(relativeCreated)12d [%(filename... |
10,315 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Land
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify do... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'csiro-bom', 'sandbox-2', 'land')
Explanation: ES-DOC CMIP6 Model Properties - Land
MIP Era: CMIP6
Institute: CSIRO-BOM
Source ID: SANDBOX-2
Topic: Land
Sub-Topics: Soil, Snow, Vegetat... |
10,316 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Stock Spans
Chapter 1 of Real World Algorithms.
Panos Louridas<br />
Athens University of Economics and Business
Stacks in Python
There is no special stack data structure in Python, as all t... | Python Code:
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack
stack.pop()
stack
stack.pop()
stack
stack.pop()
stack
Explanation: Stock Spans
Chapter 1 of Real World Algorithms.
Panos Louridas<br />
Athens University of Economics and Business
Stacks in Python
There is no special stack data structure in Python, as... |
10,317 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Forward Modeling the X-ray Image data
In this notebook, we'll take a closer look at the X-ray image data products, and build a simple, generative, forward model for the observed data.
Step1:... | Python Code:
import astropy.io.fits as pyfits
import astropy.visualization as viz
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 10.0)
Explanation: Forward Modeling the X-ray Image data
In this notebook, we'll take a closer look at the X-ray image data prod... |
10,318 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Py-EMDE
Python Email Data Entry
The following code can gather data from weather stations reporting to the CHORDS portal, package it up into the proper format for GLOBE Email Data Entry , and... | Python Code:
import requests
import json
r = requests.get('http://3d-kenya.chordsrt.com/instruments/1.geojson?start=2016-09-01T00:00&end=2016-11-01T00:00')
if r.status_code == 200:
d = r.json()['Data']
else:
print("Please verify that the URL for the weather station is correct. You may just have to try again wit... |
10,319 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Array Computing
Terminology
List
A sequence of values that can vary in length.
The values can be different data types.
The values can be modified (mutable).
Tuple
A sequence of values with a... | Python Code:
x = 2
y = 3
myList = [x, y]
myList
Explanation: Array Computing
Terminology
List
A sequence of values that can vary in length.
The values can be different data types.
The values can be modified (mutable).
Tuple
A sequence of values with a fixed length.
The values can be different data types.
The values can... |
10,320 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
0. Preparing Data
Before digging into the parser notebook, the version of the CWE xml file within this notebook is v3.0, which can be downloaded from this link. Here we loaded CWE v3.0 xml f... | Python Code:
cwe_xml_file='cwec_v3.0.xml'
Explanation: 0. Preparing Data
Before digging into the parser notebook, the version of the CWE xml file within this notebook is v3.0, which can be downloaded from this link. Here we loaded CWE v3.0 xml file. Therefore, if there is any new version of XML raw file, please make ch... |
10,321 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
NumPy essentials
NumPy is a Python library for manipulation of vectors and arrays. We import it just like any Python module
Step1: Vector creation | Python Code:
import numpy as np
Explanation: NumPy essentials
NumPy is a Python library for manipulation of vectors and arrays. We import it just like any Python module:
End of explanation
# From Python lists or iterators
n1 = np.array( [0,1,2,3,4,5,6] )
n2 = np.array( range(6) )
# Using numpy iterators
n3 = np.arange(... |
10,322 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
2019 Book Update
Step1: Read in my Goodreads Export
Go to https
Step2: Select the books from the goodreads dump
Get relevant columns
Sort by newest
Remove unsightly NaNs,
Filter to only 'r... | Python Code:
import pandas as pd
import numpy as np
Explanation: 2019 Book Update
End of explanation
book_df = pd.read_csv('goodreads_library_export.csv')
book_df['Date Added'] = pd.to_datetime(book_df['Date Added'],
format="%Y/%m/%d")
book_df.columns
Explanation: Read in my Goodr... |
10,323 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Scaling Gaussian Processes to big datasets
This notebook was made with the following version of george
Step1: One of the biggest technical challenges faced when using Gaussian Processes to ... | Python Code:
import george
george.__version__
Explanation: Scaling Gaussian Processes to big datasets
This notebook was made with the following version of george:
End of explanation
import numpy as np
import matplotlib.pyplot as pl
np.random.seed(1234)
x = np.sort(np.random.uniform(0, 10, 50000))
yerr = 0.1 * np.ones_l... |
10,324 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Note
Step1: Python is an interpreted language
fire up an interpreter
assign a value to a variable
print something
switch to ipython
Fundamentals
Python uses whitespaces (tabs and spaces) to... | Python Code:
from IPython.display import Image
Image('images/mem0.jpg')
Image('images/mem1.jpg')
Image('images/C++_machine_learning.png')
Image('images/Java_machine_learning.png')
Image('images/Python_machine_learning.png')
Image('images/R_machine_learning.png')
Explanation: Note: We are using Python here, not Python 2... |
10,325 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
text
Header
для редактирования формулы ниже использует синтаксис tex
$$ c = \sqrt{a^2 + b^2}$$
Step1: Ниже аналоги команд для пользователей Windows
Step2: удаление директории, если она не ... | Python Code:
! echo 'hello, world!'
!echo $t
%%bash
mkdir test_directory
cd test_directory/
ls -a
#удаление директории, если она не нужна
! rm -r test_directory
Explanation: text
Header
для редактирования формулы ниже использует синтаксис tex
$$ c = \sqrt{a^2 + b^2}$$
End of explanation
%%cmd
mkdir test_directory
cd t... |
10,326 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this notebook a simple Q learner will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantity (in fact it determines t... | Python Code:
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
from time import time
from sklearn.metrics import r2_score, median_absolute_error
from multiprocessing import Pool
%matplotlib inline
%pylab inline
... |
10,327 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Skyrme example
Step1: Link the O$_2$scl library
Step2: Get the value of $\hbar c$ from an O$_2$scl find_constants object
Step3: Get a copy (a pointer to) the O$_2$scl unit conversion obje... | Python Code:
import o2sclpy
Explanation: Skyrme example
End of explanation
link=o2sclpy.linker()
link.link_o2scl_o2graph(True,True)
Explanation: Link the O$_2$scl library
End of explanation
fc=o2sclpy.find_constants(link)
hc=fc.find_unique('hbarc','MeV*fm')
print('hbarc = %7.6e' % (hc))
Explanation: Get the value of $\... |
10,328 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Simon #metoo step 4
For sentiment analysis, we will use the VADER library.
Step1: We can get the tweets to analyse by reading the text column from our metoo dataset. We also read the dates ... | Python Code:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
import pandas as pd
pd.set_option('display.max_colwidth', -1)
Explanation: Simon #metoo step 4
For sentiment analysis, we will use the VADER library.
End of explanation
df = pd.DataFrame.from_csv("m... |
10,329 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Resonant excitation
We want to study the behaviour of an undercritically damped SDOF system when it is
subjected to a harmonic force $p(t) = p_o \sin\omega_nt$, i.e., when the excitation fre... | Python Code:
def x_normalized(t, z):
wn = w = 2*pi
wd = wn*sqrt(1-z*z)
# Clough Penzien p. 43
A = z/sqrt(1-z*z)
return (-cos(wd*t)-A*sin(wd*t))*exp(-z*wn*t) + cos(w*t)
Explanation: Resonant excitation
We want to study the behaviour of an undercritically damped SDOF system when it is
subjected to a h... |
10,330 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Intro. to Snorkel
Step1: We repeat our definition of the Spouse Candidate subclass from Parts II and III.
Step2: Using a labeled development set
In our setting here, we will use the phrase... | Python Code:
%load_ext autoreload
%autoreload 2
%matplotlib inline
import os
# TO USE A DATABASE OTHER THAN SQLITE, USE THIS LINE
# Note that this is necessary for parallel execution amongst other things...
# os.environ['SNORKELDB'] = 'postgres:///snorkel-intro'
import numpy as np
from snorkel import SnorkelSession
ses... |
10,331 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Section 5.1
Step1: Import datasets
Using a dictionary of pandas dataframes, with the key as the language. A better way would be to have a tidy dataframe.
Step2: Monthly bot edit counts are... | Python Code:
import pandas as pd
import seaborn as sns
import mwapi
import numpy as np
import glob
%matplotlib inline
Explanation: Section 5.1: proportion of all bot edits to articles that are bot-bot reverts
This is a data analysis script for an analysis presented in section 5.1, which you can run based entirely off t... |
10,332 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Currencies Trend Following Portfolio
1. The Security closes with 50/100 ma > 0, buy.
2. If the Security closes 50/100 ma < 0, sell your long position.
(For a Portfolio of currencies.)
... | Python Code:
import datetime
import matplotlib.pyplot as plt
import pandas as pd
from talib.abstract import *
import pinkfish as pf
import strategy
# Format price data.
pd.options.display.float_format = '{:0.2f}'.format
pd.set_option('display.max_rows', None)
%matplotlib inline
# Set size of inline plots
'''note: rcPar... |
10,333 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
17 - Natural Language Processing
by Alejandro Correa Bahnsen and Jesus Solano
version 1.5, March 2019
Part of the class Practical Machine Learning
This notebook is licensed under a Creative ... | Python Code:
import pandas as pd
import numpy as np
import scipy as sp
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from... |
10,334 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Generative Adversarial Network
In this notebook, we'll be building a generative adversarial network (GAN) trained on the MNIST dataset. From this, we'll be able to generate new handwritten d... | Python Code:
%matplotlib inline
import pickle as pkl
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data')
Explanation: Generative Adversarial Network
In this notebook, we'll be building a gen... |
10,335 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Homework
Step1: Part 1
Step2: Part 3 | Python Code:
import requests
import json
file='US-Senators.json'
senators = requests.get('https://www.govtrack.us/api/v2/role?current=true&role_type=senator').json()['objects']
with open(file,'w') as f:
f.write(json.dumps(senators))
print(f"Saved: {file}")
Explanation: Homework: US Senator Lookup
The Problem
L... |
10,336 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step2: This notebook showcases the analysis applied to LLC outputs. Here the calculations are performed for a single snapshot. The full LLC model outputs can be obtained from the ECCO Projec... | Python Code:
import datetime
import numpy as np
import scipy as sp
from scipy import interpolate
import matplotlib.pyplot as plt
%matplotlib inline
import cmocean
import seawater as sw
from netCDF4 import Dataset
from llctools import llc_model
from pyspec import spectrum as spec
c1 = 'slateblue'
c2 = 'tomato'
c3 = 'k'
... |
10,337 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
INSTRUCTIONS
Go on by clicking on "Run cell" button (above us). DO NOT click again on "Run cell" button unless you have gone to next cell. Please, in order to continue with the questionarie,... | Python Code:
instrument, category, accordion = load_interface1()
check1, slider1, check2, slider2, check3, slider3, check4, slider4 = load_interface2()
display(accordion)
display(check1,slider1)
display(check2,slider2)
display(check3,slider3)
display(check4,slider4)
Explanation: INSTRUCTIONS
Go on by clicking on "Run c... |
10,338 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction
In this exercise, you'll work through several applications of PCA to the Ames dataset.
Run this cell to set everything up!
Step1: Let's choose a few features that are highly co... | Python Code:
# Setup feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.feature_engineering_new.ex5 import *
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.decomposition import PCA
from sklearn.feature_selection import mut... |
10,339 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ex34-Correlations between SOI and SLP, Temperature and Precipitation
This tutorial will reproduce and extend the NCL
Step1: 1. Basic information
Data files
All of these data are publicly av... | Python Code:
%matplotlib inline
import numpy as np
import xarray as xr
import pandas as pd
from numba import jit
from functools import partial
from scipy.stats import pearsonr
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
... |
10,340 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Styles
You can set particular styles
Step2: Spine Removal
Step3: Size and Aspect
You can use matplotlib's plt.figure(figsize=(width,height) to change the size of mos... | Python Code:
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
tips = sns.load_dataset('tips')
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Style and Color
We've shown a few times how to control figure aesthetics in seaborn, but let's now go over i... |
10,341 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Siro Moreno Martín
Cómo destruir y corromper todo lo es bueno y bello
A veces, tenemos que usar Excel
Hay que reconocer que hay gente por ahí que hace maravillas, aunque me de cosilla pensar... | Python Code:
#Vamos a importar numpy y pandas para jugar un poquillo
import numpy as np
import pandas as pd
from openpyxl import Workbook
from openpyxl import load_workbook
#También usaremos funciones para dibujar gráficos
from openpyxl.chart import (
ScatterChart,
Reference,
Series,
)
Explanation: Siro Mor... |
10,342 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2020 The TensorFlow Authors.
Step1: 通过子类化创建新的层和模型
<table class="tfo-notebook-buttons" align="left">
<td data-segment-approved="false"> <a target="_blank" href="https
Step2: ... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
10,343 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Увидел у Игоря Викторовича в vk отличный пост
Step1: X = [Titan, Naga, Djinn, Mage, Golem, Gargoyle, Gremlin, Sold gems]
Step2: Решение найдено почти мгновенно.
Step3: Последний элемент о... | Python Code:
import scipy.optimize
import numpy as np
import pandas as pd
gold = int(2 * 1e5)
gems = 115
mercury = 80
distant_min_health = 4000
air_min_health = 2000
gem_price = 500
units = [
{'name': 'titan', 'health': 300, 'gold': 5000, 'mercury': 1, 'gems': 3, 'available': 10},
{'name': 'naga', 'health': 120... |
10,344 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Installing Python and GraphLab Create
Please follow the installation instructions here before getting started
Step1: Create some variables in Python
Step2: Advanced python types
Step3: Ad... | Python Code:
print 'Hello World!'
Explanation: Installing Python and GraphLab Create
Please follow the installation instructions here before getting started:
We have done
Installed Python
Started Ipython Notebook
Getting started with Python
End of explanation
i = 4 #int
type(i)
f = 4.1 #float
type(f)
b = True #boole... |
10,345 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2021 The TensorFlow Authors.
Step2: Inspecting Quantization Errors with Quantization Debugger
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href=... | Python Code:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dist... |
10,346 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
EOF analysis - global hgt500
In statistics and signal processing, the method of empirical orthogonal function (EOF) analysis is a decomposition of a signal or data set in terms of orthogonal... | Python Code:
% matplotlib inline
import numpy as np
from scipy import signal
import numpy.polynomial.polynomial as poly
from netCDF4 import Dataset
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from eofs.standard import Eof
Explanation: EOF analysis - global hgt500
In statistics and signal pr... |
10,347 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href="https
Step1: Introduction
In this assignment, we'll be returning to the scenario we started analyzing in the Model Evaluation assignment -- analyzing the obesity epidemic in the Un... | Python Code:
# Setup/Imports
!pip install datacommons --upgrade --quiet
!pip install datacommons_pandas --upgrade --quiet
# Data Commons Python and Pandas APIs
import datacommons
import datacommons_pandas
# For manipulating data
import numpy as np
import pandas as pd
# For implementing models and evaluation methods
fro... |
10,348 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
In this tutorial, we'll walk through downloading and preprocessing the compendium of ENCODE and Epigenomics Roadmap data.
This part won't be very iPython tutorial-ly...
First cd in the termi... | Python Code:
!cd ../data; preprocess_features.py -y -m 200 -s 600 -o er -c genomes/human.hg19.genome sample_beds.txt
Explanation: In this tutorial, we'll walk through downloading and preprocessing the compendium of ENCODE and Epigenomics Roadmap data.
This part won't be very iPython tutorial-ly...
First cd in the termi... |
10,349 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 3</font>
Download
Step1: Exercícios - Métodos e Funções | Python Code:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())
Explanation: <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 3</font>
Download: http://github.com/dsacademybr
End of explanation
# Exe... |
10,350 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Converting wind profiles to energy potential
Wind turbines convert the kinetic energy of the wind to electrical energy. The amount of energy produces thus depends on the wind speed, and the ... | Python Code:
# Initialization
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
%matplotlib inline
plt.style.use('fivethirtyeight')
def logprofile(z,ust):
''' Return u as function of z(array) and u_star
Uses Charnock relation for wind-wave interactions'''
z0 = 0.0... |
10,351 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
i need to create a dataframe containing tuples from a series of dataframes arrays. What I need is the following: | Problem:
import pandas as pd
import numpy as np
a = pd.DataFrame(np.array([[1, 2],[3, 4]]), columns=['one', 'two'])
b = pd.DataFrame(np.array([[5, 6],[7, 8]]), columns=['one', 'two'])
def g(a,b):
return pd.DataFrame(np.rec.fromarrays((a.values, b.values)).tolist(),columns=a.columns,index=a.index)
result = g(a.copy(... |
10,352 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
第5回 ランキング学習(Ranking SVM)
この演習課題ページでは,Ranking SVMの実装であるSVM-rankの使い方を説明します.この演習ページの目的は,SVM-rankを用いてモデルの学習,テストデータに対するランク付けが可能になることです.
この演習ページでは以下のツールを使用します.
- SVM-rank (by Prof. Thorsten Joach... | Python Code:
! ../bin/svm_rank_learn -c 0.03 ../data/svmrank_sample/train.dat ../data/svmrank_sample/model
Explanation: 第5回 ランキング学習(Ranking SVM)
この演習課題ページでは,Ranking SVMの実装であるSVM-rankの使い方を説明します.この演習ページの目的は,SVM-rankを用いてモデルの学習,テストデータに対するランク付けが可能になることです.
この演習ページでは以下のツールを使用します.
- SVM-rank (by Prof. Thorsten Joachims)
- h... |
10,353 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
PySnpTools Tutorial
Step up notebook
Step1: Reading Bed files
Use "Bed" to access file "all.bed"
Step2: Find out about iids and sids
Step3: Read all the SNP data in to memory
Step4: Prin... | Python Code:
# set some ipython notebook properties
%matplotlib inline
# set degree of verbosity (adapt to INFO for more verbose output)
import logging
logging.basicConfig(level=logging.WARNING)
# set figure sizes
import pylab
pylab.rcParams['figure.figsize'] = (10.0, 8.0)
Explanation: PySnpTools Tutorial
Step up noteb... |
10,354 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: Language Translation
In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset o... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
import problem_unittests as tests
source_path = 'data/small_vocab_en'
target_path = 'data/small_vocab_fr'
source_text = helper.load_data(source_path)
target_text = helper.load_data(target_path)
Explanation: Language Translation
In this project, you’re going ... |
10,355 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Exercício 1
Step1: Exercício 2
Step2: Exercício 3
Step3: Exercício 4
Step4: Exercício 5
Step5: Exercício 5b
Step6: Exercício 6
Step7: Exercício 7 | Python Code:
print (Triangulo(5,5,5)) # equilatero
print (Triangulo(5,5,7)) # isóceles
print (Triangulo(3,4,5)) # escaleno
print (Triangulo(5,5,11)) # não é triângulo
Explanation: Exercício 1: Crie três funções:
1) Uma função chamada VerificaTriangulo() que recebe como parâmetro o comprimento dos três lados de um ... |
10,356 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Convolutional Neural Networks
In this notebook, we train a CNN to classify images from the CIFAR-10 database.
The images in this database are small color images that fall into one of ten cla... | Python Code:
import torch
import numpy as np
# check if CUDA is available
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...')
Explanation: Convolutional Neural Networks
In this notebook, we trai... |
10,357 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Create environment
Step1: Random action
Step2: No action | Python Code:
import json
from os import path
import pandas as pd
import gym.envs
import numpy as np
num_steps = 100
gym.envs.register(id='obs-v2',
entry_point='gym_bs.envs:EuropeanOptionEnv',
kwargs={'t': num_steps,
'n': 1,
's0': 49... |
10,358 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Predicting Permeability of Berea
Berea Sandstone Simulation Using PoreSpy and OpenPNM
The example explains effective permeabilty calculations using PoreSpy and OpenPNM software. The simulati... | Python Code:
import os
import imageio
import scipy as sp
import numpy as np
import openpnm as op
import porespy as ps
import matplotlib.pyplot as plt
np.set_printoptions(precision=4)
np.random.seed(10)
%matplotlib inline
Explanation: Predicting Permeability of Berea
Berea Sandstone Simulation Using PoreSpy and OpenPNM
... |
10,359 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
We will discover the best actor/director according to imdb ratings
First we import all the necessary libraries to process and plot data.
Step1: We read our data and use the actordirector va... | Python Code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
%matplotlib inline
Explanation: We will discover the best actor/director according to imdb ratings
First we import all the necessary libraries to process and plot data.
End of explanation
df = pd.read_csv('movie_... |
10,360 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Waves in magnetized Plasmas
Step1: We run the simulation up to a fixed number of iterations, controlled by the variable niter, storing the value of the EM fields $E_y$ (X-wave) and $E_z$ (O... | Python Code:
import em1ds as zpic
electrons = zpic.Species( "electrons", -1.0, ppc = 64, uth=[0.005,0.005,0.005])
sim = zpic.Simulation( nx = 1000, box = 100.0, dt = 0.05, species = electrons )
#Bz0 = 0.5
Bz0 = 1.0
#Bz0 = 4.0
sim.emf.set_ext_fld('uniform', B0= [0.0, 0.0, Bz0])
Explanation: Waves in magnetized Plasmas: ... |
10,361 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
5T_Pandas 실습하기 - World 데이터베이스를 이용한 데이터 분석 ( filtering, merge, text mining )
실습
인구가 1억 명 이상이면서, Asia에 포함된 국가 리스트 DataFrame
국가명과 도시명을 가지고 있는 DataFrame(현재는 각각 country_df, city_df에 있는 상태)
Govern... | Python Code:
city_df = pd.read_csv("world_City.csv")
country_df = pd.read_csv("world_Country.csv")
city_df.head()
country_df.head(3)
country_df.columns
country_df.count()
Explanation: 5T_Pandas 실습하기 - World 데이터베이스를 이용한 데이터 분석 ( filtering, merge, text mining )
실습
인구가 1억 명 이상이면서, Asia에 포함된 국가 리스트 DataFrame
국가명과 도시명을 가지고 ... |
10,362 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
$$ \LaTeX \text{ command declarations here.}
\newcommand{\N}{\mathcal{N}}
\newcommand{\R}{\mathbb{R}}
\renewcommand{\vec}[1]{\mathbf{#1}}
\newcommand{\norm}[1]{\|#1\|_2}
\newcommand{\d}{\mat... | Python Code:
# all the packages you need
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
from numpy.linalg import inv
# load data from .mat
mat = scipy.io.loadmat('mnist_49_3000.mat')
print (mat.keys())
x = mat['x'].T
y = mat['y'].T
print (x.shape, y.shape)
# show example image
plt.imshow (x[4, :].re... |
10,363 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step1: TV Script Generation
In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Ne... | Python Code:
DON'T MODIFY ANYTHING IN THIS CELL
import helper
data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]
Explanation: TV Script Generation
In this project, you'll generate your own Simpsons TV script... |
10,364 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modeling 1
Step1: 1) Fit a Linear model
Step2: This catalog has a lot of information, but for this tutorial we are going to work only with periods and magnitudes. Let's grab them using the... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
from astropy.modeling import models, fitting
from astroquery.vizier import Vizier
import scipy.optimize
# Make plots display in notebooks
%matplotlib inline
Explanation: Modeling 1: Make a quick fit using astropy.modeling
Authors
Rocio Kiman, Lia Corrales... |
10,365 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Linear systems
<img src="https
Step1: Diagonally dominance
We say that matrix $A_{nxn}$ is diagonally dominant iff
$$ |a_{ii}| \geq \sum_{j\neq i} |a_{ij}|, \quad \forall i=1, n \, $$
equiv... | Python Code:
def is_square(a):
return a.shape[0] == a.shape[1]
def has_solutions(a, b):
return np.linalg.matrix_rank(a) == np.linalg.matrix_rank(np.append(a, b[np.newaxis].T, axis=1))
Explanation: Linear systems
<img src="https://i.ytimg.com/vi/7ujEpq7MWfE/maxresdefault.jpg" width="400" />
Given square matrix $... |
10,366 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Test isotherm fitting
Our strategy here is to generate data points that follow a given isotherm model, then fit an isotherm model to the data using pyIAST, and check that pyIAST identifies t... | Python Code:
import pyiast
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
Explanation: Test isotherm fitting
Our strategy here is to generate data points that follow a given isotherm model, then fit an isotherm model to the data using pyIAST, and check that pyIAST identifies t... |
10,367 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The objective of this notebook, and more broadly, this project is to see whether we can discern a linear relationship between metrics found on Rotton Tomatoes and Box Office performance.
Box... | Python Code:
df = unpickle_object("final_dataframe_for_analysis.pkl") #dataframe we got from webscraping and cleaning!
#see other notebooks for more info.
df.dtypes # there are all our features. Our target variable is Box_office
df.shape
Explanation: The objective of this notebook, and more broadly, this project is to ... |
10,368 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Note
Step1: To verify this actually works as a RAM, I'll run a little simulation
Step2: The simulation results show the values [1, 4, 7, 10, 13, 16, 19, 22, 25, 28] entering on the data in... | Python Code:
from pygmyhdl import *
@chunk
def ram(clk_i, en_i, wr_i, addr_i, data_i, data_o):
'''
Inputs:
clk_i: Data is read/written on the rising edge of this clock input.
en_i: When high, the RAM is enabled for read/write operations.
wr_i: When high, data is written to the RAM; when l... |
10,369 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
OpenCV template recognition from http
Step1: Crop the image to make an initial test case
Step2: next grab a gold coin as template
Step3: next process template | Python Code:
! wget http://docs.opencv.org/master/res_mario.jpg
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image as PIL_Image
from IPython.display import Image as IpyImage
IpyImage(filename='res_mario.jpg')
Explanation: OpenCV template recognition from http://docs.opencv.org/ma... |
10,370 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Modelling On the Job Search
The implementation draws heavily from the material provided on the Quantitative Economics website.
Model Features
Step1: Parameterization
Step3: Bellman Operato... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
from scipy.optimize import minimize
from scipy.integrate import fixed_quad as integrate
import time
from scipy import interp
Explanation: Modelling On the Job Search
The implementation draws heavily from the material provided on... |
10,371 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I'm trying to reduce noise in a python image array by removing all completely isolated single cells, i.e. setting nonzero value cells to 0 if they are completely surrounded by other... | Problem:
import numpy as np
import scipy.ndimage
square = np.zeros((32, 32))
square[10:-10, 10:-10] = np.random.randint(1, 255, size = (12, 12))
np.random.seed(12)
x, y = (32*np.random.random((2, 20))).astype(int)
square[x, y] = np.random.randint(1, 255, size = (20,))
def filter_isolated_cells(array, struct):
filte... |
10,372 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Atmos
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'inpe', 'sandbox-2', 'atmos')
Explanation: ES-DOC CMIP6 Model Properties - Atmos
MIP Era: CMIP6
Institute: INPE
Source ID: SANDBOX-2
Topic: Atmos
Sub-Topics: Dynamical Core, Radiation,... |
10,373 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Statistics
Summarizing data.
Plotting data.
Confidence intervals.
Statistical tests.
About this Notebook
In this notebook, we download a dataset with data about customers. T... | Python Code:
# Run this cell :)
1+2
Explanation: Introduction to Statistics
Summarizing data.
Plotting data.
Confidence intervals.
Statistical tests.
About this Notebook
In this notebook, we download a dataset with data about customers. Then, we calculate statistical measures and plot distributions. Finally, we perfor... |
10,374 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
결합, 주변, 조건부 확률 밀도 함수
결합누적확률분포는 이제 변수가 2개니까 다변수로 붙어서 나온 개념이다.
두 개 이상의 확률 변수가 서로 관계를 가지며 존재하는 경우를 생각해 보자. 예를 들어 학교에 있는 학생의 키와 몸무게를 측정하는 경우 한 명의 학생 $\omega$에 대해 두 개의 자료 ($x$, $y$)가 한 쌍으로 나오게 된다... | Python Code:
mu = [2, 3]
cov = [[2, -1],[2, 4]]
rv = sp.stats.multivariate_normal(mu, cov)
xx = np.linspace(-1, 5, 150)
yy = np.linspace(0, 6, 120)
XX, YY = np.meshgrid(xx, yy)
ZZ = rv.pdf(np.dstack([XX, YY]))
plt.contour(XX, YY, ZZ)
plt.xlabel("x")
plt.ylabel("y")
plt.title("Joint Probability Density")
plt.axis("equal... |
10,375 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step4: Problem Statement
Whether one trades in Stocks, Index, Currencies, Commodities, a person would like to know questions like
Step7: 2.
sentiment scoring
Step9: 3.
merging data sets
AP... | Python Code:
#data munging and feature extraction packages
import requests
import requests_ftp
import requests_cache
import lxml
import itertools
import pandas as pd
import re
import numpy as np
import seaborn as sns
import string
from bs4 import BeautifulSoup
from collections import Counter
from matplotlib import pypl... |
10,376 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Introduction to Linear Regression
Learning Objectives
Analyze a Pandas Dataframe.
Create Seaborn plots for Exploratory Data Analysis.
Train a Linear Regression Model using Scikit-Learn.
Intr... | Python Code:
# Importing Pandas, a data processing and CSV file I/O libraries
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns # Seaborn is a Python data visualization library based on matplotlib.
%matplotlib inline
Explanation: Introduction to Linear Regressio... |
10,377 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
TMY tutorial
This tutorial shows how to use the pvlib.tmy module to read data from TMY2 and TMY3 files.
This tutorial has been tested against the following package versions
Step1: pvlib com... | Python Code:
# built in python modules
import datetime
import os
import inspect
# python add-ons
import numpy as np
import pandas as pd
# plotting libraries
%matplotlib inline
import matplotlib.pyplot as plt
try:
import seaborn as sns
except ImportError:
pass
import pvlib
Explanation: TMY tutorial
This tutorial... |
10,378 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Retrieve your DKRZ data form
Via this form you can retrieve previously generated data forms and make them accessible via the Web again for completion.
Additionally you can get information on... | Python Code:
from dkrz_forms import form_widgets
form_widgets.show_status('form-retrieval')
Explanation: Retrieve your DKRZ data form
Via this form you can retrieve previously generated data forms and make them accessible via the Web again for completion.
Additionally you can get information on the data ingest process ... |
10,379 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<h2>Create a cross-section from AWOT radar instance</h2>
<p> This example uses a gridded NetCDF windsyn file and produces a 2-panel plot
of horizontal CAPPI of reflectivity at 2 km. The flig... | Python Code:
# Load the needed packages
from glob import glob
import matplotlib.pyplot as plt
import numpy as np
import awot
from awot.graph.common import create_basemap
from awot.graph import RadarHorizontalPlot, RadarVerticalPlot, FlightLevel
%matplotlib inline
Explanation: <h2>Create a cross-section from AWOT radar ... |
10,380 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
ES-DOC CMIP6 Model Properties - Ocean
MIP Era
Step1: Document Authors
Set document authors
Step2: Document Contributors
Specify document contributors
Step3: Document Publication
Specify d... | Python Code:
# DO NOT EDIT !
from pyesdoc.ipython.model_topic import NotebookOutput
# DO NOT EDIT !
DOC = NotebookOutput('cmip6', 'bcc', 'sandbox-3', 'ocean')
Explanation: ES-DOC CMIP6 Model Properties - Ocean
MIP Era: CMIP6
Institute: BCC
Source ID: SANDBOX-3
Topic: Ocean
Sub-Topics: Timestepping Framework, Adve... |
10,381 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Task
Say you think you have pairs of numbers serialized as comma separated values in a file. You want to extract the pair from each line, then sum over the result (per line).
Sample Data
St... | Python Code:
lines = ["1, 1.0", # An errant float
"1, $", # A bad number
"1,-1", # A good line
"10"] # Missing the second value
Explanation: Task
Say you think you have pairs of numbers serialized as comma separated values in a file. You want to extract the pair from each line, th... |
10,382 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Vertex SDK
Step1: Install the latest GA version of google-cloud-storage library as well.
Note
Step2: Restart the kernel
Once you've installed the additional packages, you need to restart t... | Python Code:
import os
# Google Cloud Notebook
if os.path.exists("/opt/deeplearning/metadata/env_version"):
USER_FLAG = "--user"
else:
USER_FLAG = ""
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
Explanation: Vertex SDK: AutoML training text sentiment analysis model for online prediction
<table al... |
10,383 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Ugly To Pretty for CSVS
Run on linux. Set an import path and an export path to folders.
Will take every file in import directory that is a mathematica generated CSV and turn it into a nicely... | Python Code:
importpath = "/home/jwb/repos/github-research/csvs/Companies/Ugly/Stack/"
exportpath = "/home/jwb/repos/github-research/csvs/Companies/Pretty/Stack/"
Explanation: Ugly To Pretty for CSVS
Run on linux. Set an import path and an export path to folders.
Will take every file in import directory that is a mathe... |
10,384 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Even if your data is not strictly related to fields commonly used in
astrophysical codes or your code is not supported yet, you can still feed it to
yt to use its advanced visualization and ... | Python Code:
import yt
import numpy as np
Explanation: Even if your data is not strictly related to fields commonly used in
astrophysical codes or your code is not supported yet, you can still feed it to
yt to use its advanced visualization and analysis facilities. The only
requirement is that your data can be represen... |
10,385 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Decoding Filing Periods
The raw data tables mix together filings from different reporting periods (e.g. quarterlys vs. semi-annual vs. pre-elections). But we need these filings to be sorted ... | Python Code:
from calaccess_processed.models.tracking import ProcessedDataVersion
ProcessedDataVersion.objects.latest()
Explanation: Decoding Filing Periods
The raw data tables mix together filings from different reporting periods (e.g. quarterlys vs. semi-annual vs. pre-elections). But we need these filings to be sort... |
10,386 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
The point of this notebook is to do a quick prediction on some sample images with a pretrained network.
Important Imports
Step1: We're going to test on some train images, so loading the tra... | Python Code:
import sys
sys.path.append('../')
import cPickle as pickle
import re
import glob
import os
from generators import DataLoader
import time
import holoviews as hv
import theano
import theano.tensor as T
import numpy as np
import pandas as p
import lasagne as nn
from utils import hms, architecture_string, get_... |
10,387 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2017 Google LLC.
Step1: TensorFlow Programming Concepts
Learning Objectives
Step2: Don't forget to execute the preceding code block (the import statements).
Other common import s... | Python Code:
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribute... |
10,388 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Day 8 - pre-class assignment
Goals for today's pre-class assignment
Use complex if statements and loops to make decisions in a computer program
Assignment instructions
Watch the videos below... | Python Code:
# Imports the functionality that we need to display YouTube videos in a Jupyter Notebook.
# You need to run this cell before you run ANY of the YouTube videos.
from IPython.display import YouTubeVideo
# WATCH THE VIDEO IN FULL-SCREEN MODE
YouTubeVideo("8_wSb927nH0",width=640,height=360) # Complex 'if' ... |
10,389 |
Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
display a few of images from dataset using imshow()
| Python Code::
import matplotlib.pyplot as plt
fig, ax = plt.subplots(3, 3, sharex=True, sharey=True, figsize=(5,5))
for images, labels in ds.take(1):
for i in range(3):
for j in range(3):
ax[i][j].imshow(images[i*3+j].numpy().astype("uint8"))
ax[i][j].set_title(ds.class_names[labels[... |
10,390 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<a href='http
Step1: Recreate this scatter plot of b vs a. Note the color and size of the points. Also note the figure size. See if you can figure out how to stretch it in a similar fashion... | Python Code:
import pandas as pd
import matplotlib.pyplot as plt
df3 = pd.read_csv('df3')
%matplotlib inline
df3.info()
df3.head()
Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>
Pandas Data Visualization Exercise
This is just a quick exercise for you to review the various ... |
10,391 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
AST 337 In-Class Lab #2
Wednesday, September 13, 2017
Names
Step1: The first step is to download the datasets we need from VizieR for the following clusters
Step2: As before, we would like... | Python Code:
# Load packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Explanation: AST 337 In-Class Lab #2
Wednesday, September 13, 2017
Names: [insert your names here]
In this lab, you will (1) work directly with published astronomical data from the VizieR database, (2... |
10,392 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Statistical Moments - Skewness and Kurtosis
Bonus
Step1: Sometimes mean and variance are not enough to describe a distribution. When we calculate variance, we square the deviations around t... | Python Code:
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
Explanation: Statistical Moments - Skewness and Kurtosis
Bonus: Jarque-Bera Normality Test
By Evgenia "Jenny" Nitishinskaya, Maxwell Margenot, and Delaney Granizo-Mackenzie.
Part of the Quantopian Lecture Series:
www.quantopian.... |
10,393 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Part 1
Assignment
Train a sklearn.ensemble.RandomForestClassifier that given a soccer player description outputs his skin color.
- Show how different parameters passed to the Classifier aff... | Python Code:
# imports
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.pyplot import show
import itertools
# sklearn
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn import preprocessing as pp
from sklearn.model_selectio... |
10,394 | Given the following text problem statement, write Python code to implement the functionality described below in problem statement
Problem:
I have the following torch tensor: | Problem:
import numpy as np
import pandas as pd
import torch
t, idx = load_data()
assert type(t) == torch.Tensor
assert type(idx) == np.ndarray
idxs = torch.from_numpy(idx).long().unsqueeze(1)
# or torch.from_numpy(idxs).long().view(-1,1)
result = t.gather(1, idxs).squeeze(1) |
10,395 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Querying a Population and Plotting the Results
Before we can query a population, we must have one. We will use a population of satellites as an example.
In this portion of the tutorial we wi... | Python Code:
import os
import subprocess
if not os.path.exists('satellites.bdb'):
subprocess.check_call(['curl', '-O', 'http://probcomp.csail.mit.edu/bayesdb/downloads/satellites.bdb'])
Explanation: Querying a Population and Plotting the Results
Before we can query a population, we must have one. We will use a popu... |
10,396 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Step5: Полносвязная нейронная сеть
В данном домашнем задании вы подготовите свою реализацию полносвязной нейронной сети и обучите классификатор на датасете CIFAR-10
Step6: Прямой проход, ск... | Python Code:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
def rel_error(x, y):
returns relative error
return np.max(np.abs(x - y... |
10,397 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Copyright 2019 The TensorFlow Hub Authors.
Licensed under the Apache License, Version 2.0 (the "License");
Step1: 使用 3D 卷积实现视频插画
<table class="tfo-notebook-buttons" align="left">
<td>
... | Python Code:
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... |
10,398 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
Image Display Examples
Step1: Load some image data
Step2: Matplotlib imshow()
Matplotlib is a great high-quality data display tool used by lots of people for a long time. It has long been... | Python Code:
from __future__ import print_function, unicode_literals, division, absolute_import
import io
import IPython
from ipywidgets import widgets
import PIL.Image
from widget_canvas import CanvasImage
from widget_canvas.image import read
Explanation: Image Display Examples
End of explanation
data_image = read('im... |
10,399 | Given the following text description, write Python code to implement the functionality described below step by step
Description:
<hr style="border
Step1: <hr style="border
Step2:
<hr style="border
Step3:
<hr style="border
Step4:
<hr style="border
Step5:
<hr style="border
Step6: ... | Python Code:
# calculate pi
import numpy as np
# N : number of iterations
def calc_pi(N):
x = np.random.ranf(N);
y = np.random.ranf(N);
r = np.sqrt(x*x + y*y);
c=r[ r <= 1.0 ]
return 4*float((c.size))/float(N)
# time the results
pts = 6; N = np.logspace(1,8,num=pts);
result = np.zeros(pts); count = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.