Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
7,700
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Geoserver to load data on the map In this notebook we'll take a look at using Geoserver to render raster data to the map. Geoserver is an open source server for sharing geospatial data...
Python Code: %matplotlib inline from matplotlib import pylab as plt Explanation: Using Geoserver to load data on the map In this notebook we'll take a look at using Geoserver to render raster data to the map. Geoserver is an open source server for sharing geospatial data. It includes a tiling server which the GeoJS map...
7,701
Given the following text description, write Python code to implement the functionality described below step by step Description: Set up working directory Step1: README This part of pipeline search for the SSU rRNA gene fragments, classify them, and extract reads aligned specific region. It is also heavy lifting part ...
Python Code: cd ~/Desktop/SSUsearch/ mkdir -p ./workdir #check seqfile files to process in data directory (make sure you still remember the data directory) !ls ./data/test/data Explanation: Set up working directory End of explanation Seqfile='./data/test/data/1c.fa' Explanation: README This part of pipeline search for ...
7,702
Given the following text description, write Python code to implement the functionality described below step by step Description: The Carbonic Acid/Bicarbonate/Carbonate Equilibrium $\require{mhchem}$ Carbonic Acid ($\ce{H2CO3}$), Bicarbonate ($\ce{HCO3-}$) and Carbonate ($\ce{CO3^{2-}}$) form in water through the foll...
Python Code: %pylab inline from phreeqpython import PhreeqPython # create new PhreeqPython instance pp = PhreeqPython() Explanation: The Carbonic Acid/Bicarbonate/Carbonate Equilibrium $\require{mhchem}$ Carbonic Acid ($\ce{H2CO3}$), Bicarbonate ($\ce{HCO3-}$) and Carbonate ($\ce{CO3^{2-}}$) form in water through the f...
7,703
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 19 Step1: Now, let's set an initial population $n_0$, pick a couple of different per capita rates of change $r_c$, and run them to see what happens. Step2: The one critical part of...
Python Code: # Preliminary imports %matplotlib inline import matplotlib.pyplot as plt import numpy as np import scipy.integrate as sig # Here's the critical module! import seaborn as sns Explanation: Lecture 19: Computational Modeling CBIO (CSCI) 4835/6835: Introduction to Computational Biology Overview and Objectives...
7,704
Given the following text description, write Python code to implement the functionality described below step by step Description: Next, we'll import the Sequential model type from Keras. This is simply a linear stack of neural network layers, and it's perfect for the type of feed-forward CNN we're building in this tuto...
Python Code: from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.utils import np_utils from keras.datasets import mnist #load pre-shffuled MNIST data into train and test sets (X_train, y_train), (X_test, y_test)...
7,705
Given the following text description, write Python code to implement the functionality described below step by step Description: Casser le code de Vigenère La lettre la plus fréquente en français est la lettre E. Cette information permet de casser le code de César en calculant le décalage entre la lettre la plus fréqu...
Python Code: def code_vigenere ( message, cle, decode = False) : message_code = "" for i,c in enumerate(message) : d = cle[ i % len(cle) ] d = ord(d) - 65 if decode : d = 26 - d message_code += chr((ord(c)-65+d)%26+65) return message_code def DecodeVigenere(message, cle)...
7,706
Given the following text description, write Python code to implement the functionality described below step by step Description: Chord Diagrams for Bokeh Chord diagrams are a wonderful way to visualise interactions between groups, along the genome, and many others (check the circos page for some advances examples). I ...
Python Code: # Each row defines how many items were "send" to the group specified by the column # for the "golden image" use case, the matrix should be symmetric matrix = np.array([[16, 3, 28, 0, 18], [18, 0, 12, 5, 29], [ 9, 11, 17, 27, 0], [19, 0, 31, 11,...
7,707
Given the following text description, write Python code to implement the functionality described below step by step Description: Advanced AD application This notebook documents how the algorithmic (or automatic) differentiation framework may be applied to non-linear equations. For an introduction to the framework, see...
Python Code: import porepy as pp import numpy as np import inspect model = pp.ContactMechanics({}) print(inspect.getsource(model._assign_equations)) Explanation: Advanced AD application This notebook documents how the algorithmic (or automatic) differentiation framework may be applied to non-linear equations. For an i...
7,708
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Session 5 Step2: <a name="introduction"></a> Introduction So far we've seen the basics of neural networks, how they can be used for encoding large datasets, or for predicting labels....
Python Code: # First check the Python version import sys if sys.version_info < (3,4): print('You are running an older version of Python!\n\n', 'You should consider updating to Python 3.4.0 or', 'higher as the libraries built for this course', 'have only been tested in Python 3.4 and hi...
7,709
Given the following text description, write Python code to implement the functionality described below step by step Description: Neural Network 예제 Step1: Tensorflow로 구현되어 있는 golbin님의 예제에서 같은 문제를 가지고 pytorch로 구현하도록 하겠습니다. 털과 날개가 있는지 없는지에 따라서 포유류와 조류를 분류하는 신경망 모델입니다. pytorch의 정형화된 구조 pyTorch는 다음과 정형화된 형태를 사용할 수 있을 것으로...
Python Code: %matplotlib inline Explanation: Neural Network 예제 End of explanation import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F # [털, 날개] x_data = torch.Tensor( [[0, 0], [1, 0], [1, 1], [0, 0], [0, 0], [0, 1]]) # 0: 기타 , 1: 포유류, 2: 조류 y_data = torch.LongTenso...
7,710
Given the following text description, write Python code to implement the functionality described below step by step Description: Outline Glossary 2. Mathematical Groundwork Previous Step1: Import section specific modules Step3: 2.8. The Discrete Fourier Transform (DFT) and the Fast Fourier Transform (FFT)<a id='math...
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline from IPython.display import HTML HTML('../style/course.css') #apply general CSS Explanation: Outline Glossary 2. Mathematical Groundwork Previous: 2.7 Fourier Theorems Next: 2.9 Sampling Theory Import standard modules: End of explanatio...
7,711
Given the following text description, write Python code to implement the functionality described below step by step Description: TFX Components Walk-through Learning Objectives Develop a high level understanding of TFX pipeline components. Learn how to use a TFX Interactive Context for prototype development of TFX pip...
Python Code: import os import time from pprint import pprint import absl import tensorflow as tf import tensorflow_data_validation as tfdv import tensorflow_model_analysis as tfma import tensorflow_transform as tft import tfx from tensorflow_metadata.proto.v0 import schema_pb2 from tfx.components import ( CsvExampl...
7,712
Given the following text description, write Python code to implement the functionality described below step by step Description: 05 - Support Vector Machines by Alejandro Correa Bahnsen and Jesus Solano version 1.4, January 2019 Part of the class Practical Machine Learning This notebook is licensed under a Creative Co...
Python Code: %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats plt.style.use('bmh') Explanation: 05 - Support Vector Machines by Alejandro Correa Bahnsen and Jesus Solano version 1.4, January 2019 Part of the class Practical Machine Learning This notebook is licensed under a ...
7,713
Given the following text description, write Python code to implement the functionality described below step by step Description: ACM SIGKDD Austin Advanced Machine Learning with Python Class 1 Step1: Ever since I discovered Watermark, I love it because it automatically documents the package versions, and information ...
Python Code: %install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py %load_ext watermark %watermark -a "Jaya Zenchenko" -n -t -z -u -h -m -w -v -p scikit-learn,matplotlib,pandas,seaborn,numpy,scipy,conda Explanation: ACM SIGKDD Austin Advanced Machine Learning with Python Class 1: Pre-Model W...
7,714
Given the following text description, write Python code to implement the functionality described below step by step Description: Orbit Plot REBOUND comes with a simple way to plot instantaneous orbits of planetary systems. To show how this works, let's setup a test simulation with 4 planets. Step1: To plot these init...
Python Code: import rebound sim = rebound.Simulation() sim.add(m=1) sim.add(m=0.1, e=0.041, a=0.4, inc=0.2, f=0.43, Omega=0.82, omega=2.98) sim.add(m=1e-3, e=0.24, a=1.0, pomega=2.14) sim.add(m=1e-3, e=0.24, a=1.5, omega=1.14, l=2.1) sim.add(a=-2.7, e=1.4, f=-1.5,omega=-0.7) # hyperbolic orbit Explanation: Orbit Plot R...
7,715
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Seaice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify ...
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'mpi-m', 'mpi-esm-1-2-lr', 'seaice') Explanation: ES-DOC CMIP6 Model Properties - Seaice MIP Era: CMIP6 Institute: MPI-M Source ID: MPI-ESM-1-2-LR Topic: Seaice Sub-Topics: Dynamics, T...
7,716
Given the following text description, write Python code to implement the functionality described below step by step Description: This quickstart guide explains how to join two tables A and B using TF-IDF similarity measure. First, you need to import the required packages as follows (if you have installed py_stringsi...
Python Code: # Import libraries import py_stringsimjoin as ssj import py_stringmatching as sm import pandas as pd import os import sys print('python version: ' + sys.version) print('py_stringsimjoin version: ' + ssj.__version__) print('py_stringmatching version: ' + sm.__version__) print('pandas version: ' + pd.__versi...
7,717
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparing Accuracy Step1: Next, we evaluate scikit-learn accuracy where we predict feed implementation based on latency. Step2: As you can see, scikit-learn has a 99% accuracy rate. We now...
Python Code: import graphviz import pandas from sklearn import tree from sklearn.model_selection import train_test_split clf = tree.DecisionTreeClassifier() input = pandas.read_csv("/home/glenn/git/clojure-news-feed/client/ml/etl/throughput.csv") data = input[input.columns[6:9]] target = input['cloud'] X_train, X_test,...
7,718
Given the following text description, write Python code to implement the functionality described below step by step Description: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and create a logistic regres...
Python Code: import pandas as pd %matplotlib inline import numpy as np from sklearn.linear_model import LogisticRegression Explanation: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and create a logistic ...
7,719
Given the following text description, write Python code to implement the functionality described below step by step Description: Example time line of chords represented as binary pitch class sets in a single song Step1: Distribution of pitch classes accross all songs Step2: Observation Step3: Distribution of chords...
Python Code: draw_track(find_track('Yesterday')[0]) Explanation: Example time line of chords represented as binary pitch class sets in a single song: End of explanation pc_histogram = pd.DataFrame({'pitch_class': pcs_columns, 'relative_count': nonsilent_chords[pcs_columns].mean()}) stem(pc_histogram['relative_count']) ...
7,720
Given the following text description, write Python code to implement the functionality described below step by step Description: This example shows how to use k-NN classifier to classify a dataset. We will first generate a binary classification dataset consisitng of 2D feature vectors, randomly sampled from two Gaussi...
Python Code: import numpy N = 5 Explanation: This example shows how to use k-NN classifier to classify a dataset. We will first generate a binary classification dataset consisitng of 2D feature vectors, randomly sampled from two Gaussian distributions. We will then learn a k-NN classifier to separate the two classes. E...
7,721
Given the following text description, write Python code to implement the functionality described below step by step Description: Goal Initial assessment of how accuracy of DESeq2 changes with the BD window used to select 'heavy' fraction samples Just testing on 'validation' run which just has 100% incorporators User v...
Python Code: workDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/' genomeDir = '/home/nick/notebook/SIPSim/dev/bac_genome1210/genomes/' R_dir = '/home/nick/notebook/SIPSim/lib/R/' Explanation: Goal Initial assessment of how accuracy of DESeq2 changes with the BD window used to select 'heavy' fraction samples Just ...
7,722
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents 1b. Fixed flux spinodal decomposition on a square domain Use Binder For Live Examples Define $f_0$ Define the Equation Solve the Equation Run the Example Locally Movie of E...
Python Code: %matplotlib inline import sympy import fipy as fp import numpy as np A, c, c_m, B, c_alpha, c_beta = sympy.symbols("A c_var c_m B c_alpha c_beta") f_0 = - A / 2 * (c - c_m)**2 + B / 4 * (c - c_m)**4 + c_alpha / 4 * (c - c_alpha)**4 + c_beta / 4 * (c - c_beta)**4 print f_0 sympy.diff(f_0, c, 2) Explanation:...
7,723
Given the following text description, write Python code to implement the functionality described below step by step Description: Index Modeling E-R Diagrams Relational model SQL SELECT JOIN Exercises Using SQLAlchemy Why do we normalize? SQL security issues 1) Modeling When the amount or the complexity of the data we ...
Python Code: %load -r 1-16 solutions/12_01_Databases.py Explanation: Index Modeling E-R Diagrams Relational model SQL SELECT JOIN Exercises Using SQLAlchemy Why do we normalize? SQL security issues 1) Modeling When the amount or the complexity of the data we work with overwhelms us, we look for tools able to help us. D...
7,724
Given the following text description, write Python code to implement the functionality described below step by step Description: EinMix Step1: Logic of EinMix is very close to the one of einsum. If you're not familiar with einsum, follow these guides first Step2: ResMLP — original implementation Building blocks of ...
Python Code: from einops.layers.torch import EinMix as Mix Explanation: EinMix: universal toolkit for advanced MLP architectures Recent progress in MLP-based architectures demonstrated that very specific MLPs can compete with convnets and transformers (and even outperform them). EinMix allows writing such architectures...
7,725
Given the following text description, write Python code to implement the functionality described below step by step Description: Repository AOIs This notebook gathers all the aois used in this repo and saves them as a geojson file. To grab a single aoi geojson string to add to your notebook, just uncomment the line th...
Python Code: import json import geojson from geojson import Polygon, Feature, FeatureCollection # # Local code for compact printing of geojson from utils import CompactFeature, CompactFeatureCollection Explanation: Repository AOIs This notebook gathers all the aois used in this repo and saves them as a geojson file. To...
7,726
Given the following text description, write Python code to implement the functionality described below step by step Description: Beaming and Boosting Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want t...
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: Beaming and Boosting Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation %matplotlib inlin...
7,727
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1><center>How to export 🤗 Transformers Models to ONNX ?<h1><center> [ONNX](http Step1: How to leverage runtime for inference over an ONNX graph As mentionned in the introduction, ONNX is...
Python Code: import sys !{sys.executable} -m pip install --upgrade git+https://github.com/huggingface/transformers !{sys.executable} -m pip install --upgrade torch==1.6.0+cpu torchvision==0.7.0+cpu -f https://download.pytorch.org/whl/torch_stable.html !{sys.executable} -m pip install --upgrade onnxruntime==1.4.0 !{sys....
7,728
Given the following text description, write Python code to implement the functionality described below step by step Description: Metasploit Payload Size Or Step1: We'll start with displaying payload size against the fraction of exploits which will work (or not work) for that size. It looks like any payload over 2048 ...
Python Code: %matplotlib inline import os import re import sys import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt # Set up a path to the Metasploit project's code. basepath = os.path.join('/', 'home', 'dnelson', 'projects', 'msf-stats') rootdir = os.path.join(basepath, 'metaspl...
7,729
Given the following text description, write Python code to implement the functionality described below step by step Description: Step 0 - hyperparams vocab_size is all the potential words you could have (classification for translation case) and max sequence length are the SAME thing decoder RNN hidden units are usuall...
Python Code: batch_size = 1 #full_train_size = 55820 #train_size = 55800 #small_train_size = 6000 #just because of performance reasons, no statistics behind this decision #test_size = 6200 data_path = '../../../../Dropbox/data' phae_path = data_path + '/price_hist_autoencoder' csv_in = '../price_history_03_seq_start_su...
7,730
Given the following text description, write Python code to implement the functionality described below step by step Description: Handling Time When performing feature engineering with temporal data, carefully selecting the data that is used for any calculation is paramount. By annotating dataframes with a Woodwork tim...
Python Code: import pandas as pd pd.options.display.max_columns = 200 import featuretools as ft es = ft.demo.load_mock_customer(return_entityset=True, random_seed=0) es['transactions'].head() Explanation: Handling Time When performing feature engineering with temporal data, carefully selecting the data that is used for...
7,731
Given the following text description, write Python code to implement the functionality described below step by step Description: Model hooks Callback and helper function to add hooks in models Step1: What are hooks? Hooks are functions you can attach to a particular layer in your model and that will be executed in th...
Python Code: from fastai.test_utils import * Explanation: Model hooks Callback and helper function to add hooks in models End of explanation tst_model = nn.Linear(5,3) def example_forward_hook(m,i,o): print(m,i,o) x = torch.randn(4,5) hook = tst_model.register_forward_hook(example_forward_hook) y = tst_model(x) ho...
7,732
Given the following text description, write Python code to implement the functionality described below step by step Description: TITANIC Step1: Here's a sqlite database for you to store the data once it's ready Step2: =>YOUR TURN! Use pandas to open up the csv. Read the documentation to find out how Step3: Explori...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import pandas.io.sql as pd_sql import sqlite3 as sql %matplotlib inline Explanation: TITANIC: Wrangling the Passenger Manifest Exploratory Analysis with Pandas This tutorial is based on the Kaggle Competition, "Predicting Survival Aboar...
7,733
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 ...
7,734
Given the following text description, write Python code to implement the functionality described below step by step Description: What subsets of scientific questions tend to be answered correctly by the same subjects? Mining Step1: Search for interesting rules Interesting rules are more likely to be the ones with hig...
Python Code: from orangecontrib.associate.fpgrowth import * import pandas as pd from numpy import * questions = correctedScientific.columns correctedScientificText = [[] for _ in range(correctedScientific.shape[0])] for q in questions: for index in range(correctedScientific.shape[0]): r = correctedScienti...
7,735
Given the following text description, write Python code to implement the functionality described below step by step Description: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book....
Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf Explanation: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network ...
7,736
Given the following text description, write Python code to implement the functionality described below step by step Description: Desafio 1 1. Entender a API de Streaming do Twitter Ver slides 14 até 21. Da mesma forma que fizemos na API REST do Twitter, temos que salvar as chaves de acesso, bem como definir o objeto O...
Python Code: import tweepy consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' autorizar = tweepy.OAuthHandler(consumer_key, consumer_secret) autorizar.set_access_token(access_token, access_token_secret) Explanation: Desafio 1 1. Entender a API de Streaming do Twitter Ver slides 14 até 21....
7,737
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas II - Working with DataFrames Step1: We'll be using the MovieLens dataset in many examples going forward. The dataset contains 100,000 ratings made by 943 users on 1,682 movies. Step2...
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.set_option('max_columns', 50) Explanation: Pandas II - Working with DataFrames End of explanation # pass in column names for each CSV u_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code'] df_users = pd.read_csv('data/MovieLens...
7,738
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualising statistical significance thresholds on EEG data MNE-Python provides a range of tools for statistical hypothesis testing and the visualisation of the results. Here, we show a few ...
Python Code: import numpy as np import matplotlib.pyplot as plt from scipy.stats import ttest_ind import mne from mne.channels import find_ch_adjacency, make_1020_channel_selections from mne.stats import spatio_temporal_cluster_test np.random.seed(0) # Load the data path = mne.datasets.kiloword.data_path() + '/kword_me...
7,739
Given the following text description, write Python code to implement the functionality described below step by step Description: Step3: Gathering system data - Python for System Administrators Goals Step6: Parsing /proc Linux /proc filesystem is a cool place to get data In the next example we'll see how to get Step8:...
Python Code: import psutil import glob import sys import subprocess # # Our code is p3-ready # from __future__ import print_function, unicode_literals def grep(needle, fpath): A simple grep implementation goal: open() is iterable and doesn't need splitlines() goal: comprehension can filte...
7,740
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 4 Imports Step1: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don...
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns Explanation: Numpy Exercise 4 Imports End of explanation import networkx as nx K_5=nx.complete_graph(5) nx.draw(K_5) Explanation: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or node...
7,741
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 17 - Navier Stokes equations Keywords Step1: 3. Affine Decomposition Step2: 4. Main program 4.1. Read the mesh for this problem The mesh was generated by the data/generate_mesh.ip...
Python Code: from ufl import transpose from dolfin import * from rbnics import * Explanation: Tutorial 17 - Navier Stokes equations Keywords: DEIM, supremizer operator 1. Introduction In this tutorial, we will study the Navier-Stokes equations over the two-dimensional backward-facing step domain $\Omega$ shown below: <...
7,742
Given the following text description, write Python code to implement the functionality described below step by step Description: Sensitivity Analysis Test here Step1: Setting up the base model For a first test Step2: Define parameter uncertainties We will start with a sensitivity analysis for the parameters of the f...
Python Code: from IPython.core.display import HTML css_file = 'pynoddy.css' HTML(open(css_file, "r").read()) %matplotlib inline Explanation: Sensitivity Analysis Test here: (local) sensitivity analysis of kinematic parameters with respect to a defined objective function. Aim: test how sensitivity the resulting model is...
7,743
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create a list from the dictionary keys Step2: Create a list from the dictionary values
Python Code: dict = {'county': ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'], 'year': [2012, 2012, 2013, 2014, 2014], 'fireReports': [4, 24, 31, 2, 3]} Explanation: Title: Creating Lists From Dictionary Keys And Values Slug: create_list_from_dictionary_keys_and_values Summary: Creating Lists F...
7,744
Given the following text description, write Python code to implement the functionality described below step by step Description: Matrix Multiplication Various ways of implementing different matrix multiplications. Read the documentation embedded in the code. Step1: In this example, the assertions essentially tell the...
Python Code: # -*- coding: utf-8 -*- from pylab import * from pyspecdata import * from numpy.random import random import time init_logging('debug') Explanation: Matrix Multiplication Various ways of implementing different matrix multiplications. Read the documentation embedded in the code. End of explanation a_nd = ndd...
7,745
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...
7,746
Given the following text description, write Python code to implement the functionality described below step by step Description: Comparison of bubble trajectories Start by loading some boiler plate Step1: And some more specialized dependencies Step2: Helper routines Step3: Configuration for this figure. config.ref...
Python Code: %matplotlib inline import matplotlib matplotlib.rcParams['figure.figsize'] = (10.0, 8.0) import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import InterpolatedUnivariateSpline from scipy.interpolate import UnivariateSpline import json import pandas as pd from functools import partial...
7,747
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: TFX Keras Component Tutorial A Component-by-Component Introduction to TensorFlow Extended (TFX) Note Step2: Install TFX Note Step3: Did you r...
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...
7,748
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Convolutional Neural Networks Team StoDIG - Statoil Deep-learning Interest Group David Wade, John Thurmond & Eskil Kulseth Dahl In this python notebook we propos...
Python Code: %%sh pip install pandas pip install scikit-learn pip install keras pip install sklearn from __future__ import print_function import time import numpy as np %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes...
7,749
Given the following text description, write Python code to implement the functionality described below step by step Description: Exercises Step1: Exercise 1 Step2: Exercise 2 Step3: Exercise 3 Step4: b. Confidence Intervals. Calculate the first, second, and third confidence intervals. Plot the PDF and the firs...
Python Code: # Useful Functions class DiscreteRandomVariable: def __init__(self, a=0, b=1): self.variableType = "" self.low = a self.high = b return def draw(self, numberOfSamples): samples = np.random.randint(self.low, self.high, numberOfSamples) return samples ...
7,750
Given the following text description, write Python code to implement the functionality described below step by step Description: <div style='background-image Step1: 1. Chebyshev derivative method Exercise Define a python function call "get_cheby_matrix(nx)" that initializes the Chebyshev derivative matrix $D_{ij}$, c...
Python Code: # This is a configuration step for the exercise. Please run it before calculating the derivative! import numpy as np import matplotlib.pyplot as plt from ricker import ricker # Show the plots in the Notebook. plt.switch_backend("nbagg") Explanation: <div style='background-image: url("../../share/images/he...
7,751
Given the following text description, write Python code to implement the functionality described below step by step Description: Enlib write_map bug Step1: We make a full-sky arcminute resolution geometry. I've only been able to reproduce this bug for res=1.0. Step2: We do a pix2sky that is needed by map2alm and mak...
Python Code: %load_ext autoreload %autoreload 2 from enlib import enmap,wcs as mwcs import numpy as np import sys,os Explanation: Enlib write_map bug End of explanation res = 1.0 shape, wcs = enmap.fullsky_geometry(res=res*np.pi/180./60., proj="car") shape = (3,)+shape Explanation: We make a full-sky arcminute resoluti...
7,752
Given the following text description, write Python code to implement the functionality described below step by step Description: KBMOD Documentation This notebook demonstrates the basics of the kbmod image processing and searching python API Before importing, make sure to run source setup.bash in the root directory, a...
Python Code: from kbmodpy import kbmod as kb import numpy path = "../data/demo/" Explanation: KBMOD Documentation This notebook demonstrates the basics of the kbmod image processing and searching python API Before importing, make sure to run source setup.bash in the root directory, and that you are using the python3 ke...
7,753
Given the following text description, write Python code to implement the functionality described below step by step Description: The purpose of this post is to demonstrate a sample template for a Bokeh server. Although the example demonstrated in this notebook is rather simple (linear regression), keeping your Bokeh s...
Python Code: ### Bokeh Linear Regression Example ### Written By: Eric Strong ### Last Updated: 2017/05/10 from sklearn.datasets import make_regression from sklearn.linear_model import LinearRegression as LR from bokeh.io import curdoc from bokeh.plotting import figure from bokeh.models.ranges import Range1d from bokeh....
7,754
Given the following text description, write Python code to implement the functionality described below step by step Description: Facies classification using Random Forest Contest entry by Step1: A complete description of the dataset is given in the Original contest notebook by Brendon Hall, Enthought. A total of fo...
Python Code: ###### Importing all used packages %matplotlib inline import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes_locatable import seaborn a...
7,755
Given the following text description, write Python code to implement the functionality described below step by step Description: Visualizando datos de entrada Step1: Algoritmo de Regresion Lineal en TensorFlow Step2: Regresion Lineal en Polinomios de grado N Step3: Regularizacion Para manejar un poco mejor el impac...
Python Code: import numpy as np import matplotlib.pyplot as plt # Regresa 101 numeros igualmmente espaciados en el intervalo[-1,1] x_train = np.linspace(-1, 1, 101) # Genera numeros pseudo-aleatorios multiplicando la matriz x_train * 2 y # sumando a cada elemento un ruido (una matriz del mismo tamanio con puros numero...
7,756
Given the following text description, write Python code to implement the functionality described below step by step Description: 工作流程: 1.问题定义 2.获取训练集和测试集 3.清洗数据,做好准备 4.分析并识别模式,探索数据 5.建立模型,预测并解决问题 6.可视化解决问题的步骤以及最终的解决方案 7.提交答案 工作目标:分类,将样本进行分类,考虑其与目标类的相关性;相关性,特征与目标的相关性;转换,将特征值转化为符合模型的类型;补充,补充存在的缺失值;修正,修正错误的特征值;创造,创造新的特征值...
Python Code: # data analysis and wrangling import pandas as pd import numpy as np import random as rnd # visualization import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline # machine learning from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC, LinearSVC from sklearn.ensem...
7,757
Given the following text description, write Python code to implement the functionality described below step by step Description: README Notebook to test the Complex class as well as parsing code from cobrame/ecolime From COBRAme/ECOLIme... Flat files / ProcessData Step1: Protein complexes - ComplexData and ComplexFor...
Python Code: import ecolime import ecolime.flat_files Explanation: README Notebook to test the Complex class as well as parsing code from cobrame/ecolime From COBRAme/ECOLIme... Flat files / ProcessData End of explanation # First load the list of complexes which tells you complexes + subunit stoichiometry # Converts th...
7,758
Given the following text description, write Python code to implement the functionality described below step by step Description: read from an Excel file documentation Step1: write to a comma separated value (.csv) file documentation
Python Code: file_name_string = 'C:/Users/Charles Kelly/Desktop/Exercise Files/02_07/Begin/EmployeesWithGrades.xlsx' employees_df = pd.read_excel(file_name_string, 'Sheet1', index_col=None, na_values=['NA']) Explanation: read from an Excel file documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas...
7,759
Given the following text description, write Python code to implement the functionality described below step by step Description: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book....
Python Code: import time from collections import namedtuple import numpy as np import tensorflow as tf Explanation: Anna KaRNNa In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book. This network ...
7,760
Given the following text description, write Python code to implement the functionality described below step by step Description: Serie de Taylor \begin{equation} f(x) = \sum_{n=0}^{\infty} \frac{f^{(n)}(a)}{n!} (x - a)^{n} \end{equation} Expansión hacia adelante \begin{equation} f(x) \approx f(a) + f'(a) (x - ...
Python Code: def g(x): resultado = - 0.1*x**4 - 0.15*x**3 - 0.5*x**2 - 0.25*x + 1.2 return resultado def fx_adelante(f,x,h): derivada = (f(x+h) - f(x))/h return derivada print('f\'(0.5) =', fx_adelante(g,0.5,0.25)) Explanation: Serie de Taylor \begin{equation} f(x) = \sum_{n=0}^{\infty} \frac{f^{(n)...
7,761
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2018 The TensorFlow Authors. Step1: Image captioning with visual attention <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Down...
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...
7,762
Given the following text description, write Python code to implement the functionality described below step by step Description: Introducing Functions One of the core principles of any programming language is, "Don't Repeat Yourself". If you have an action that should occur many times, you can define that action once ...
Python Code: # Let's define a function. def function_name(argument_1, argument_2): # Do whatever we want this function to do, # using argument_1 and argument_2 # Use function_name to call the function. function_name(value_1, value_2) Explanation: Introducing Functions One of the core principles of any programming la...
7,763
Given the following text description, write Python code to implement the functionality described below step by step Description: 'orb' Datasets and Options 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:...
Python Code: #!pip install -I "phoebe>=2.3,<2.4" Explanation: 'orb' Datasets and Options 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 logger = pho...
7,764
Given the following text description, write Python code to implement the functionality described below step by step Description: Monte Carlo Simulations (Section 8.3 in Text) Monte Carlo simulations are used to calculate probabilities using random numbers when the probabilities are difficult (or impossible) to calcula...
Python Code: from IPython.display import Image Image(url='http://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/The_Sun_by_the_Atmospheric_Imaging_Assembly_of_NASA%27s_Solar_Dynamics_Observatory_-_20100819.jpg/251px-The_Sun_by_the_Atmospheric_Imaging_Assembly_of_NASA%27s_Solar_Dynamics_Observatory_-_20100819.jpg') E...
7,765
Given the following text description, write Python code to implement the functionality described below step by step Description: Step4: Boilerplate for graph visualization Step5: Load the data Run 00_download_data.ipynb if you haven't already Step6: Create a simple classifier with low-level TF Ops Step7: We can run...
Python Code: # This is for graph visualization. from IPython.display import clear_output, Image, display, HTML def strip_consts(graph_def, max_const_size=32): Strip large constant values from graph_def. strip_def = tf.GraphDef() for n0 in graph_def.node: n = strip_def.node.add() n.MergeFrom...
7,766
Given the following text description, write Python code to implement the functionality described below step by step Description: TensorFlow Tutorial Welcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that w...
Python Code: import math import numpy as np import h5py import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.python.framework import ops from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict %matplotlib inline np.random.seed(1) Explanation: TensorFlow Tutorial Welcome to...
7,767
Given the following text description, write Python code to implement the functionality described below step by step Description: Statistical inference Here we will briefly cover multiple concepts of inferential statistics in an introductory manner, and demonstrate how to use some MNE statistical functions. Step1: Hyp...
Python Code: # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) from functools import partial import numpy as np from scipy import stats import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa, analysis:ignore import mne from mne.stats import (ttest_1samp_no_p, bonferroni...
7,768
Given the following text description, write Python code to implement the functionality described below step by step Description: Package Step1: Another utility class Step2: Scaling features to a range Example Step3: MaxAbsScaler works in a very similar fashion, but scales in a way that the training data lies within...
Python Code: from sklearn import preprocessing import numpy as np X = np.array([[1.,-1.,2.], [2., 0.,0.], [0., 1.,-1.]]) X_scaled = preprocessing.scale(X) X_scaled X_scaled.mean(axis = 0) X_scaled.std(axis=0) Explanation: Package: sklearn.preprocessing change raw feature vectors into a repre...
7,769
Given the following text description, write Python code to implement the functionality described below step by step Description: Übungen zu SQL Teacher Wir möchten eine Abfrage erstellen, die einem Programm die Namen aller Lehrer für jeden Kurs und jeden Schüler übergibt. Im späteren Ausdruck gibt es im Formular aller...
Python Code: %load_ext sql %sql mysql://steinam:steinam@localhost/celko %%sql select * from Register; Explanation: Übungen zu SQL Teacher Wir möchten eine Abfrage erstellen, die einem Programm die Namen aller Lehrer für jeden Kurs und jeden Schüler übergibt. Im späteren Ausdruck gibt es im Formular allerdings nur Platz...
7,770
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook, we mainly utilize extreme gradient boost to improve the prediction model originially proposed in TLE 2016 November machine learning tuotrial. Extreme gradient boost can be ...
Python Code: %matplotlib inline import pandas as pd from pandas.tools.plotting import scatter_matrix import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns import matplotlib.colors as colors import xgboost as xgb import numpy as np from sklearn.metrics import confusion_matrix, f1_score, accuracy...
7,771
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: <h1 style="text-align Step2: Once the Naive Bayes Classifier has been trained with the train() method, we can use it to classify new elements
Python Code: from collections import Counter, defaultdict import numpy as np class NaiveBaseClass: def calculate_relative_occurences(self, list1): no_examples = len(list1) ro_dict = dict(Counter(list1)) for key in ro_dict.keys(): ro_dict[key] = ro_dict[key] / float(no_examples) ...
7,772
Given the following text description, write Python code to implement the functionality described below step by step Description: One of the newest features of BigBang is the ability to analyze git info for each project. For now, we mostly just look at commits over time. We can also analyze individual committers to run...
Python Code: url = "http://mail.python.org/pipermail/scipy-dev/" arx = Archive(url,archive_dir="../archives") repo = repo_loader.get_repo("bigbang") full_info = repo.commit_data; act = arx.data.groupby("Date").size(); act = act.resample("D", how=np.sum) act = act[act.index.year <= 2014] act_week = act.resample("W", how...
7,773
Given the following text description, write Python code to implement the functionality described below step by step Description: Initializing filters on known motifs In the scenario where data is scarse, it is often useful to initialize the filters of the first convolutional layer to some known position weights matric...
Python Code: %matplotlib inline import matplotlib.pyplot as plt # RBP PWM's from concise.data import attract dfa = attract.get_metadata() dfa # TF PWM's from concise.data import encode dfe = encode.get_metadata() dfe # TF PWM's from concise.data import hocomoco dfh = hocomoco.get_metadata() dfh Explanation: Initializin...
7,774
Given the following text description, write Python code to implement the functionality described below step by step Description: Optimiztion with mystic Step2: mystic Step4: Diagnostic tools Callbacks Step6: NOTE IPython does not handle shell prompt interactive programs well, so the above should be run from a comma...
Python Code: %matplotlib inline Explanation: Optimiztion with mystic End of explanation Example: - Minimize Rosenbrock's Function with Nelder-Mead. - Plot of parameter convergence to function minimum. Demonstrates: - standard models - minimal solver interface - parameter trajectories using retall # ...
7,775
Given the following text description, write Python code to implement the functionality described below step by step Description: Regresión multiple utilizando grandiente descendente de TensorFlow Step1: Input Generamos la muestra de grado 5 Step2: Problema Calcular los coeficientes que mejor se ajusten a la muestra ...
Python Code: import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns sns.set(color_codes=True) %matplotlib inline import sys sys.path.append('/home/pedro/git/ElCuadernillo/ElCuadernillo/20160220_TensorFlowRegresionMultiple') import gradient_descent_tensorflow as gdt Explanation:...
7,776
Given the following text description, write Python code to implement the functionality described below step by step Description: Cual es la mejor estrategia para adivinar? Por Miguel Escalona Step1: ¡Adivina Quién es! El juego de adivina quién es, consiste en adivinar el personaje que tu oponente ha seleccionado ante...
Python Code: import matplotlib import matplotlib.pyplot as plt %matplotlib inline matplotlib.rcParams['figure.figsize'] = (15.0, 6.0) import numpy as np import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) from IPython.display import Image Explanation: Cual es la mejor estrategia para adivina...
7,777
Given the following text description, write Python code to implement the functionality described below step by step Description: Plotting This tutorial explains the high-level interface to plotting provided by the Bundle. You are of course always welcome to access arrays and plot manually. PHOEBE 2.4 uses autofig 1.2...
Python Code: #!pip install -I "phoebe>=2.4,<2.5" Explanation: Plotting This tutorial explains the high-level interface to plotting provided by the Bundle. You are of course always welcome to access arrays and plot manually. PHOEBE 2.4 uses autofig 1.2 as an intermediate layer for highend functionality to matplotlib. S...
7,778
Given the following text description, write Python code to implement the functionality described below step by step Description: Partial derivative equations A linear equation is defined as Step1: Function to calculate loss $$ L(b,m) = \frac{1}{2N} \sum_{i=1}^N (b + m x_{i} - y_{i})^2 $$ Step2: Function to calculate...
Python Code: %matplotlib inline import random import numpy as np import matplotlib.pyplot as plt import pandas as pd from matplotlib import animation, rc from sklearn.linear_model import LinearRegression from IPython.display import HTML Explanation: Partial derivative equations A linear equation is defined as: $$ y(x_{...
7,779
Given the following text description, write Python code to implement the functionality described below step by step Description: Transliteration Transliteration is the conversion of a text from one script to another. For instance, a Latin transliteration of the Greek phrase "Ελληνική Δημοκρατία", usually translated as...
Python Code: from polyglot.transliteration import Transliterator Explanation: Transliteration Transliteration is the conversion of a text from one script to another. For instance, a Latin transliteration of the Greek phrase "Ελληνική Δημοκρατία", usually translated as 'Hellenic Republic', is "Ellēnikḗ Dēmokratía". End ...
7,780
Given the following text description, write Python code to implement the functionality described below step by step Description: Object Oriented Programming What is an Object? First some semantics Step1: Note the reference to object, this means that our new class inherits from object. We won't be going into too much ...
Python Code: class A(object): pass Explanation: Object Oriented Programming What is an Object? First some semantics: - An object is essentially a container which holds some data, and crucially some associated methods for working with that data. - We define objects, and their behaviours, using something called a ...
7,781
Given the following text description, write Python code to implement the functionality described below step by step Description: Pandas 3 Step1: <a id=wants></a> Example Step2: Reminders What kind of object does each of the following produce? Step3: Wants We might imagine doing several different things with this da...
Python Code: import sys # system module import pandas as pd # data package import matplotlib.pyplot as plt # graphics module import datetime as dt # date and time module import numpy as np # foundation for Pandas %matplotlib ...
7,782
Given the following text description, write Python code to implement the functionality described below step by step Description: Applying a 3D convolutional neural network to the data Welcome everyone to my coverage of the Kaggle Data Science Bowl 2017. My goal here is that anyone, even people new to kaggle, can follo...
Python Code: import dicom # for reading dicom files import os # for doing directory operations import pandas as pd # for some simple data analysis (right now, just to load in the labels data and quickly reference it) # Change this to wherever you are storing your data: # IF YOU ARE FOLLOWING ON KAGGLE, YOU CAN ONLY PL...
7,783
Given the following text description, write Python code to implement the functionality described below step by step Description: Loss under a Local Perceptron model Step1: Loss under a Mixture of Gaussians model Step2: We use autograd for functions that deliver gradients of those losses Step3: Just a pretty display...
Python Code: def sigmoid(phi): return 1.0/(1.0 + np.exp(-phi)) def calc_prob_class1(params): # Sigmoid perceptron ('logistic regression') tildex = X - params['mean'] W = params['wgts'] phi = np.dot(tildex, W) return sigmoid(phi) # Sigmoid perceptron ('logistic regression') def calc_membership(p...
7,784
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Values <script type="text/javascript"> localStorage.setItem('language', 'language-py') </script> <table align="left" style="margin-right Step2: Example In the followi...
Python Code: #@title Licensed under the Apache License, Version 2.0 (the "License") # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this fi...
7,785
Given the following text description, write Python code to implement the functionality described below step by step Description: Check Environment This notebook checks that you have correctly created the environment and that all packages needed are installed. Environment The next command should return a line like (Mac...
Python Code: import os import sys sys.executable Explanation: Check Environment This notebook checks that you have correctly created the environment and that all packages needed are installed. Environment The next command should return a line like (Mac/Linux): /&lt;YOUR-HOME-FOLDER&gt;/anaconda/envs/ztdl/bin/python or ...
7,786
Given the following text description, write Python code to implement the functionality described below step by step Description: Examining the MPI-Leipzig Mind-Brain-Body Dataset The MRI data are available at https Step1: We can investigate what keys are available in any .tsv header by examining the corresponding .js...
Python Code: %%bash ls MPI-Leipzig/behavioral_data_MPILMBB/phenotype | head Explanation: Examining the MPI-Leipzig Mind-Brain-Body Dataset The MRI data are available at https://openfmri.org/dataset/ds000221/. The behavioral data are available via NITRC: https://www.nitrc.org/projects/mpilmbb/. Note I was required to ed...
7,787
Given the following text description, write Python code to implement the functionality described below step by step Description: Linearity We consider a second order system of the form Step1: Initial position and intial velocity cases \begin{align} f(t) = 0, \quad x(0) = 1 m, \quad \dot{x}(0) = 0 \ f(t) = 0, ...
Python Code: %matplotlib inline import numpy as np from scipy import signal import matplotlib.pyplot as plt from ipywidgets import interact import ipywidgets as widgets Explanation: Linearity We consider a second order system of the form: \begin{align} G(s) = \frac{1}{ms^2 + cs + k} \end{align} with \begin{align} ...
7,788
Given the following text description, write Python code to implement the functionality described below step by step Description: Node Label Prediction \ Link Prediction Step1: We will start by node label prediction. Download this network. It contains protein communications in Baker’s yeast. Each node (protein) has a ...
Python Code: import numpy as np import matplotlib.pyplot as plt import scipy as sp import networkx as nx %matplotlib inline Explanation: Node Label Prediction \ Link Prediction End of explanation g = nx.read_gml('./data/ppi.CC.gml.txt') cc = list(nx.connected_components(g)) g = nx.subgraph(g,cc[0]) g = nx.relabel.conve...
7,789
Given the following text description, write Python code to implement the functionality described below step by step Description: Streamfunction and velocity potential from zonal and meridional wind component windspharm is a Python library developed by Andrew Dawson which provides an pythonic interface to the pyspharm...
Python Code: from windspharm.standard import VectorWind from windspharm.tools import prep_data, recover_data, order_latdim Explanation: Streamfunction and velocity potential from zonal and meridional wind component windspharm is a Python library developed by Andrew Dawson which provides an pythonic interface to the py...
7,790
Given the following text description, write Python code to implement the functionality described below step by step Description: PSF Photometry Version 0.1 We're going to try to piece together the different elements of a PSF photometry pipeline from scratch. Getting that done in one notebook means we'll have to cut so...
Python Code: import numpy as np from astropy.io import fits import matplotlib.pyplot as plt import astropy.convolution import pandas as pd f = fits.open("calexp-0527247_10.fits") image = f[1].data Explanation: PSF Photometry Version 0.1 We're going to try to piece together the different elements of a PSF photometry pip...
7,791
Given the following text description, write Python code to implement the functionality described below step by step Description: ISL Lab 2.3 Introduction to Statistical Computing with Python Step1: 2.3.1 Basic Commands Step2: 2.3.2 Graphics Step3: Have to dig back into MatPlotLib to set axis labels, so all is not p...
Python Code: import numpy as np import pandas as pd import scipy import scipy.stats import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.simplefilter('ignore',FutureWarning) Explanation: ISL Lab 2.3 Introduction to Statistical Computing with Python End of explanation np.arange(6) a = np.arange...
7,792
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Chapter 20 Copyright 2017 Allen Downey License Step1: Dropping pennies I'll start by getting the units we need from Pint. Step2: And defining the initial ...
Python Code: # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * Explanation: Modeling and Si...
7,793
Given the following text description, write Python code to implement the functionality described below step by step Description: Download and process the Bay Area's street network Step1: Download and extract the counties shapefile if it doesn't already exist, then load it To use OSMnx, we need a polygon of the Bay Ar...
Python Code: import os, zipfile, requests, pandas as pd, geopandas as gpd, osmnx as ox ox.config(use_cache=True, log_console=True) # point to the shapefile for counties counties_shapefile_url = 'http://www2.census.gov/geo/tiger/GENZ2016/shp/cb_2016_us_county_500k.zip' # identify bay area counties by fips code bayarea =...
7,794
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Structures Classes Step3: Magic methods There are a bunch of magic methods available in Python. You can overide some of them Step4: Iterators & Generators Step5: Tricks in function...
Python Code: class MyOwnClass(object): This is a documentation for my class, so anyone can read it. CLASS_CONST = 42 def __init__(self, argument1, default_argument2=1): This is a constructor of MyOwnClass. It saves all arguments as a 'protected' variables of a class. ...
7,795
Given the following text description, write Python code to implement the functionality described below step by step Description: Extinction (ebv, Av, & Rv) Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't ...
Python Code: !pip install -I "phoebe>=2.2,<2.3" Explanation: Extinction (ebv, Av, & Rv) Setup Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation %matplotlib...
7,796
Given the following text description, write Python code to implement the functionality described below step by step Description: Excercises Electric Machinery Fundamentals Chapter 9 Problem 9-3 Step1: Description Suppose that the motor in Problem 9-1 is started and the auxiliary winding fails open while the rotor is ...
Python Code: %pylab notebook %precision %.4g Explanation: Excercises Electric Machinery Fundamentals Chapter 9 Problem 9-3 End of explanation V = 120 # [V] p = 4 R1 = 2.0 # [Ohm] R2 = 2.8 # [Ohm] X1 = 2.56 # [Ohm] X2 = 2.56 # [Ohm] Xm = 60.5 # [Ohm] n = 400 # [r/min] Prot = 51 # [W] n_sync = 180...
7,797
Given the following text description, write Python code to implement the functionality described below step by step Description: https Step1: HTTP Methods with curl GET Step2: POST Step3: Delete Step4: Install JSON-server http Step5: HTTP Methods GET - query Step6: POST - add new Step7: NOTE Step8: PUT - updat...
Python Code: !curl -o todos-1.json https://jsonplaceholder.typicode.com/todos/1 !cat todos-1.json Explanation: https://www.baeldung.com/curl-rest https://jsonplaceholder.typicode.com/ is a great REST API test site Save curl output save curl output response to a file $ curl -o jsonplaceholder.html https://jsonplaceholde...
7,798
Given the following text description, write Python code to implement the functionality described below step by step Description: Libraries and Packages Step1: Connecting to National Data Service Step2: Extracting Data of Midwestern states of the United states from 1992 - 2016. The following query will extract data f...
Python Code: import pymongo from pymongo import MongoClient import time import pandas as pd import numpy as np import seaborn as sns from matplotlib.pyplot import * import matplotlib.pyplot as plt import folium import datetime as dt import random as rnd import warnings import datetime as dt import csv %matplotlib inlin...
7,799
Given the following text description, write Python code to implement the functionality described below step by step Description: Prepara Alta Vista Para Modelacion Se prepara la cuenca de alta vista para que sea modelada en el SIATA en tiempo real, en este caso se preparan ambas cuencas, tanto aguas arriba como aguas ...
Python Code: %matplotlib inline from wmf import wmf import numpy as np import pylab as pl import datetime as dt import os ruta = '/media/nicolas/discoGrande/01_SIATA/' Explanation: Prepara Alta Vista Para Modelacion Se prepara la cuenca de alta vista para que sea modelada en el SIATA en tiempo real, en este caso se pr...