prompt stringlengths 19 1.03M | completion stringlengths 4 2.12k | api stringlengths 8 90 |
|---|---|---|
import requests
import pandas as pd
import html
from bs4 import BeautifulSoup
class DblpApi:
def __init__(self):
self.session = requests.Session()
self.author_url = 'http://dblp.org/search/author/api'
self.pub_url = 'http://dblp.org/search/publ/api'
def get_pub_list_by_url(self, url... | pd.DataFrame(author_bad_format) | pandas.DataFrame |
'''
Training the pair trading system by calculating correlations
between all combinations of stock pairs.
'''
import os
import time
from multiprocessing import Process, Queue
import pandas as pd
import calc
from util import *
# Control the metrics to calculate. Must match the names defined in "calc.py"
METRICS ... | pd.concat([output_df, result_df]) | pandas.concat |
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import re
import os, sys
import argparse
from collections import defaultdict
sys.path.append('..')
import settings
import utils
import export_metadata
# def get_record_ids_from_fpaths(ser_fpaths):
# """
# using the df from the cal... | pd.DataFrame(data={"name":classes}, index=indices) | pandas.DataFrame |
import abc
import pandas as pd
from pathlib import Path
class DtnAbstractReport(object, metaclass=abc.ABCMeta):
""" Alias name for this report. When saved, this alias will be
used as the name of the report.
"""
_alias = None
def __init__(self, env):
# Store the simulation environment
... | pd.concat(to_concat) | pandas.concat |
# coding: utf-8
# # From Multilayer Networks to Deep Graphs
# ## The Noordin Top Terrorist Data
# ### Preprocessing
# In[1]:
# data i/o
import os
import subprocess
import zipfile
# for plots
import matplotlib.pyplot as plt
# the usual
import numpy as np
import pandas as pd
import deepgraph as dg
# notebook di... | pd.concat((v, vinfo), axis=1) | pandas.concat |
## Coin Flip Simulation ##
# Objective: Verify the Central Limit Theorem
# 1) Importing
import random
import pandas as pd
import matplotlib.pyplot as plt
# 2) Functions
def flip_coin(n, t):
"""
Function used to determine the heads count
Ex: n=2 and t=4 --> possible outcome: [H, H, T, T], [... | pd.DataFrame({'20 coins': heads[19]}) | pandas.DataFrame |
#/usr/bin/env python
import os
import argparse
import numpy as np
import pandas as pd
from slugify import slugify
def do_slugify(txt):
try:
return slugify(txt)
except TypeError:
return slugify(txt.decode())
def add_headers(args, data, headers):
data = pd.DataFrame(
np.zeros((6,... | pd.read_csv(args.xls[0], header=None, dtype=str) | pandas.read_csv |
from __future__ import division
import pandas as pd
import logging
from datetime import datetime
from numpy.random import RandomState
import numpy as np
from trumania.core.util_functions import setup_logging, load_all_logs, build_ids, make_random_bipartite_data
from trumania.core.clock import CyclicTimerProfile, Cycli... | pd.DataFrame({"result": 10}, index=story_data.index) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""
@author: <NAME> - https://www.linkedin.com/in/adamrvfisher/
"""
#This is a two asset portfolio tester with a brute force optimizer
#Takes all pair combos, tests, sorts, returns optimal params from all pairs + top performing pair params
#Import modules
import numpy as np
impo... | pd.DataFrame() | pandas.DataFrame |
import numpy as np
import pandas as pd
import nltk
import matplotlib.pyplot as plt
import string
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.neighbors imp... | pd.read_csv('review3.csv') | pandas.read_csv |
# Copyright (C) 2021 ServiceNow, Inc.
""" Functionality for training all keyword prediction downstream models
and building the downstream task dataset
"""
import pandas as pd
from typing import Union, List, Callable
import tqdm
import datetime
import random
import pathlib
import numpy as np
import subprocess
impo... | pd.read_csv(train_file) | pandas.read_csv |
from influxdb import InfluxDBClient, DataFrameClient
import numpy as np
import pandas as pd
import requests
import datetime
import time
import json
import os
import sys
import logging
def readOutput():
# Set some boolean success variables for timer
success = False
## Go up one directory and to the output folder u... | pd.read_csv('mbientInventory.csv') | pandas.read_csv |
import asyncio
import aiofiles
import aiohttp
from aiohttp.client import ClientTimeout
import pandas as pd
import json
import numpy as np
import time
from os import listdir
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('bert-base-nli-mean-tokens')
np.set_printoptions(threshold=np.in... | pd.DataFrame() | pandas.DataFrame |
import matplotlib.pyplot as plt
import pandas as pd
df_w2v = pd.read_csv("../data/w2v_history.csv", index_col=False)
df_bert = | pd.read_csv("../data/bert_history.csv", index_col=False) | pandas.read_csv |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/00_core.ipynb (unless otherwise specified).
__all__ = ['tokenizer', 'model', 'unmasker', 'spacifySeq', 'maskifySeq', 'allResidueCoordinates',
'allResiduePredictions', 'getTopSeq', 'residuePredictionScore', 'hasNonStandardAA']
# Cell
from transformers import B... | pd.DataFrame.from_dict(residueScoreDict) | pandas.DataFrame.from_dict |
"""
Regression_program
- train_data = 21대 총선 자료, 788개
- test_data = 21대 총선 자료, 788개 나머지
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc
from pandas import Series
from sklearn.linear_model import Lasso, Ridge, ElasticNet
# Make graph font ... | pd.read_csv('C:/Users/khw08/Desktop/OSBAD_Project/Regression/KoNLPY_Youtube_M&D_train_CSV.csv') | pandas.read_csv |
import numpy as np
import pandas as pd
import multiprocessing as mp
import datetime as dt
def linParts(numAtoms,
numThreads):
"""SNIPPET 20.5 THE linParts FUNCTION
partition of atoms with a single loop
"""
parts=np.linspace(0,numAtoms,min(numThreads,numAtoms)+1)
parts=np.ceil(parts).as... | pd.Series() | pandas.Series |
import os
import io
import random
import string
import re
import json
import pandas as pd
import numpy as np
from collections import OrderedDict
import nltk
from nltk import FreqDist
from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer
import config
EMPH_TOKEN = config.EMPH_TOKEN
C... | pd.read_json(f_testset, encoding='utf8') | pandas.read_json |
import itertools
import os
import pandas as pd
from tqdm import tqdm
# set directory
git_dir = os.path.expanduser("~/git/prism-4-paper")
os.chdir(git_dir)
# import functions
from functions import clean_mols, get_ecfp6_fingerprints, get_tanimoto
flatten = lambda x: list(itertools.chain.from_iterable(x))
# read true a... | pd.DataFrame() | pandas.DataFrame |
from datetime import timedelta
from functools import partial
import itertools
from parameterized import parameterized
import numpy as np
from numpy.testing import assert_array_equal, assert_almost_equal
import pandas as pd
from toolz import merge
from zipline.pipeline import SimplePipelineEngine, Pipeline, CustomFacto... | pd.Timestamp("2015-01-20") | pandas.Timestamp |
import argparse
import webbrowser
from bs4 import BeautifulSoup
import requests
import pandas as pd
import re
from helper_funcs import *
# ------------------------------------------------ HIGH_SHORT_INTEREST -------------------------------------------------
def high_short_interest(l_args):
parser = argparse.Argum... | pd.set_option('display.max_colwidth', -1) | pandas.set_option |
"""Example script for testing / validating the electric grid power flow solution."""
import cvxpy as cp
import numpy as np
import matplotlib.pyplot as plt # TODO: Remove matplotlib dependency.
import os
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import mesmo
def main():
... | pd.DataFrame(index=power_multipliers, columns=electric_grid_model_default.nodes, dtype=float) | pandas.DataFrame |
import more_itertools as mit
import peakutils
import warnings
import traceback
import numpy as np
import pandas as pd
import pickle
import logging
import os
import glob
import sys
from tqdm.auto import tqdm
from ceciestunepipe.util.sound import spectral as sp
from ceciestunepipe.util.sound import temporal as st
log... | pd.DataFrame() | pandas.DataFrame |
from collections import OrderedDict
from datetime import datetime, timedelta
import numpy as np
import numpy.ma as ma
import pytest
from pandas._libs import iNaT, lib
from pandas.core.dtypes.common import is_categorical_dtype, is_datetime64tz_dtype
from pandas.core.dtypes.dtypes import (
CategoricalDtype,
Da... | lib.infer_dtype(s, skipna=True) | pandas._libs.lib.infer_dtype |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.7
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# Import Scripts
# %r... | pd.DataFrame({'x':thresh, 'y':precision[1:]}) | pandas.DataFrame |
#dependencies
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.model_selection im... | pd.read_csv('criminal_test.csv') | pandas.read_csv |
# TODO move away from this test generator style since its we need to manage the generator file,
# which is no longer in this project workspace, as well as the output test file.
## ##
# #
# THI... | pd.DataFrame(test_class.data) | pandas.DataFrame |
#%%
# ANCHOR IMPORTS
import sys
import pandas as pd, numpy as np
import pickle
import re
from sklearn import feature_extraction , feature_selection
from scipy.sparse import csr_matrix, hstack
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction import DictVectorizer
from skl... | pd.read_pickle(d) | pandas.read_pickle |
import vectorbt as vbt
import numpy as np
import pandas as pd
from numba import njit
from datetime import datetime
import pytest
from vectorbt.generic import nb as generic_nb
from vectorbt.generic.enums import range_dt
from tests.utils import record_arrays_close
seed = 42
day_dt = np.timedelta64(86400000000000)
ma... | pd.Series([True, True, True, True, True], index=mask.index) | pandas.Series |
import numpy as np
import pandas as pd
import datetime
from TransactionEngine import dictionaries
def generate_transactions(date, size=10000):
df = | pd.DataFrame() | pandas.DataFrame |
""" Panel4D: a 4-d dict like collection of panels """
import warnings
from pandas.core.generic import NDFrame
from pandas.core.panelnd import create_nd_panel_factory
from pandas.core.panel import Panel
from pandas.util._validators import validate_axis_style_args
Panel4D = create_nd_panel_factory(klass_name='Panel4D'... | validate_axis_style_args(self, args, kwargs_, 'labs', 'reindex') | pandas.util._validators.validate_axis_style_args |
import pandas as pd
import pytest
import featuretools as ft
from featuretools.entityset import EntitySet, Relationship
from featuretools.utils.cudf_utils import pd_to_cudf_clean
from featuretools.utils.gen_utils import import_or_none
cudf = import_or_none('cudf')
# TODO: Fix vjawa
@pytest.mark.skipif('not cudf')
de... | pd.to_datetime('2019-01-10') | pandas.to_datetime |
import os
import random
import shutil
import numpy as np
import pandas as pd
import pytest
from PIL import Image
from keras_preprocessing.image import dataframe_iterator
from keras_preprocessing.image import image_data_generator
@pytest.fixture(scope='module')
def all_test_images():
img_w = img_h = 20
rgb_... | pd.DataFrame({"filename": ['image-not-exist.png'] + file_paths}) | pandas.DataFrame |
# 1.题出问题
# 什么样的人在泰坦尼克号中更容易存活?
# 2.理解数据
# 2.1 采集数据
# https://www.kaggle.com/c/titanic
# 2.2 导入数据
# 忽略警告提示
import warnings
warnings.filterwarnings('ignore')
# 导入处理数据包
import numpy as np
import pandas as pd
# 导入数据
# 训练数据集
train = pd.read_csv("./train.csv")
# 测试数据集
test = pd.read_csv("./test.csv")
# 显示所有列
pd.set_opti... | pd.set_option('display.max_rows', None) | pandas.set_option |
import requests
import pandas
from bs4 import BeautifulSoup
# creating a soup object with html we got from the response
url = "https://hacktoberfest.digitalocean.com/events"
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html)
# creating array of datas
all_names = []
all_locations = []
all_dat... | pandas.DataFrame(csv_structure) | pandas.DataFrame |
import os
import math
import numpy as np
import pandas as pd
import nltk
import textstat
from string import punctuation
class Text:
def __init__(self, filename:str, directory:str='CEFR_texts'): # file name must include .txt ending
self.filename = filename
self.dir = directory
# ... | pd.DataFrame(data_tuples, columns=['filename', 'cefr', 'abvmax', 'abvmean', 'abvmin', 'ajcv', 'apps', 'ari', 'asl', 'aslavps', 'attr', 'avps', 'awl', 'bpera', 'cli', 'dcrs', 'fkg', 'fre', 'jcpp', 'len', 'ttr']) | pandas.DataFrame |
from pandas import read_table, DataFrame
from pytest import raises
from gsea_api import cudaGSEA
from gsea_api.gsea import GSEApy
from gsea_api.expression_set import ExpressionSet
from gsea_api.gsea.exceptions import GSEANoResults
from gsea_api.molecular_signatures_db import GeneSets
matrix = read_table('tests/expres... | read_table('tests/cudaGSEA_subprocess_output.tsv') | pandas.read_table |
import nose
import unittest
from numpy import nan
from pandas.core.daterange import DateRange
from pandas.core.index import Index, MultiIndex
from pandas.core.common import rands, groupby
from pandas.core.frame import DataFrame
from pandas.core.series import Series
from pandas.util.testing import (assert_panel_equal,... | assert_frame_equal(filled, expected) | pandas.util.testing.assert_frame_equal |
""" Test cases for DataFrame.plot """
import string
import warnings
import numpy as np
import pytest
import pandas.util._test_decorators as td
import pandas as pd
from pandas import (
DataFrame,
Series,
date_range,
)
import pandas._testing as tm
from pandas.tests.plotting.common import TestPlotBase
fro... | tm.close() | pandas._testing.close |
import pandas as pd
import numpy as np
import csv
from tqdm import trange
def clean(file_name,targets=['11612','11613']):
data = pd.read_csv(file_name)
data['result'].fillna(0,inplace=True)
data['result'] = data['result'].astype(int)
items = | pd.unique(data['item_id'].values) | pandas.unique |
# Necessary Libraries
import yfinance as yf, pandas as pd
import shutil
import os
import time
import glob
import numpy as np
import requests
from get_all_tickers import get_tickers as gt
from statistics import mean
from yahoo_fin import stock_info as si
# tickers = gt.get_tickers_filtered(mktcap_min=150000, mktcap_max... | pd.DataFrame(macd) | pandas.DataFrame |
# Globals #
import re
import numpy as np
import pandas as pd
import dateutil.parser as dp
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import *
from itertools import islice
from scipy.stats import boxcox
from scipy.integrate import simps
from realtime_talib import Indicator
fr... | pd.Series(adx20[:min_length]) | pandas.Series |
import unittest
from unittest import mock
from unittest.mock import MagicMock
import numpy as np
import pandas as pd
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from pandas.util.testing import assert_frame_equal
import tests.test_data as td
from shift_detector.checks.statistical_checks impor... | pd.DataFrame(columns=cols, index=['pvalue']) | pandas.DataFrame |
# flask 서버
import sys
import os
import dateutil.relativedelta
from flask import Flask,request,Response
from multiprocessing import Process
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
import json
from functools import wraps
import mpld3
# koapy
from koapy import KiwoomOpenApiPlusEntry... | pd.DataFrame(columns=['예수금', '출금가능금액', '총매입금액', '총평가금액', '총수익률(%)', '추정예탁자산']) | pandas.DataFrame |
import pandas as pd
import numpy as np
import pytest
from pandas_appender import DF_Appender
# can append: df, series, dict-like, or list of these
# if you append a list of dicts, you end up with a column of objects
# always test ignore_index=True
def test_basics():
for a in range(1, 5):
dfa = DF_Appe... | pd.Series({'a': 'category', 'b': 'int64'}) | pandas.Series |
#coding=utf-8
import pandas as pd
import numpy as np
import sys
import os
from sklearn import preprocessing
import datetime
import scipy as sc
from sklearn.preprocessing import MinMaxScaler,StandardScaler
from sklearn.externals import joblib
#import joblib
class FEbase(object):
"""description of class"""
def ... | pd.merge(df_data, df_adj_all, how='left', on=['ts_code','trade_date']) | pandas.merge |
import itertools, sys, os
import csv
import glob
import numpy as np
import pandas as pd
import statistics
from statistics import mean
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import math
from itertools import tee
import collections
####define scoring scheme and important var... | pd.DataFrame(zero[idx]) | pandas.DataFrame |
import calendar
from struct import unpack, calcsize
import numpy as np
import pandas as pd
import os
from phildb.constants import METADATA_MISSING_VALUE
from phildb.log_handler import LogHandler
def __read(filename):
field_names = ["date", "value", "metaID"]
entry_format = "<qdi" # long, double, int; See fi... | pd.to_datetime(df["date"], unit="s") | pandas.to_datetime |
#!/usr/bin/env python
# coding: utf-8
# In[87]:
import pandas as pd
import numpy as np
import scipy.stats as stats
from datetime import datetime
from datetime import date
import csv
# In[116]:
test = pd.read_csv('./FY1419/TrusteeFY1419P10.csv')
# In[117]:
values={'Ceased Date':date.today()}
# In[118]:
te... | pd.to_datetime(test['Appointed Date'],format='%m/%d/%Y %H:%M') | pandas.to_datetime |
"""util class for doing searches"""
# Copyright 2022 Google LLC
#
# 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 app... | pd.DataFrame() | pandas.DataFrame |
import pandas as pd
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QPlainTextEdit, QSlider, QWidget, QVBoxLayout, QLabel, \
QHBoxLayout, QPushButton
from util.langUtil import check_if_valid_timestr
def get_datatable_sheet(table: QTableWidget):
map = []
... | pd.DataFrame(data) | pandas.DataFrame |
"""PyStan utility functions
These functions validate and organize data passed to and from the
classes and functions defined in the file `stan_fit.hpp` and wrapped
by the Cython file `stan_fit.pxd`.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2015, PyStan dev... | pd.DataFrame() | pandas.DataFrame |
from urllib.parse import urlparse
import pytest
import pandas as pd
import numpy as np
from visions.core.implementations.types import *
from visions.application.summaries.summary import CompleteSummary
@pytest.fixture(scope="class")
def summary():
return CompleteSummary()
def validate_summary_output(test_seri... | pd.Series([0, 1, 2, 3, 4]) | pandas.Series |
import pandas as pd
import geopandas as gpd
import numpy as np
from rasterstats import zonal_stats
import bisect
import requests
import tempfile
import io
from io import BytesIO
from . import parameters as pr
class Power():
def __init__(self,EUSES, **kwargs):
ds = EUSES.ds
year = EUSES.year
... | pd.concat([df, season_df]) | pandas.concat |
# -*- coding: utf-8 -*-
"""
Methods to perform coverage analysis.
@author: <NAME> <<EMAIL>>
"""
import pandas as pd
import numpy as np
import geopandas as gpd
from typing import List, Optional
from shapely import geometry as geo
from datetime import datetime, timedelta
from skyfield.api import load, wgs84, EarthSatel... | pd.Series([], dtype="timedelta64[ns]") | pandas.Series |
import argparse
import glob
import itertools
import os
import random
import numpy as np
import pandas as pd
from scipy.stats import ttest_ind, kendalltau
def parse_argument() -> argparse.Namespace:
"""
Parse input arguments.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--... | pd.DataFrame.from_dict(all_triples_dict, orient='index', columns=['count']) | pandas.DataFrame.from_dict |
"""Mock data for bwaw.insights tests."""
import pandas as pd
ACTIVE_BUSES = pd.DataFrame([
['213', 21.0921481, '1001', '2021-02-09 15:45:27', 52.224536, '2'],
['213', 21.0911025, '1001', '2021-02-09 15:46:22', 52.2223788, '2'],
['138', 21.0921481, '1001', '2021-02-09 15:45:27', 52.224536, '05'],
['138'... | pd.DataFrame([
['213', 16.378041, 52.223457, 21.091625, '2021-02-09 15:45:54.500'],
['138', 16.378041, 52.223457, 21.091625, '2021-02-09 15:45:54.500']
], columns=['Lines', 'Speed', 'Lat', 'Lon', 'Time']) | pandas.DataFrame |
from datetime import datetime, timedelta
import operator
from typing import Any, Sequence, Type, Union, cast
import warnings
import numpy as np
from pandas._libs import NaT, NaTType, Timestamp, algos, iNaT, lib
from pandas._libs.tslibs.c_timestamp import integer_op_not_supported
from pandas._libs.tslibs.period import... | is_period_dtype(self) | pandas.core.dtypes.common.is_period_dtype |
from constants import *
import os
import json
import pandas as pd
import requests
from pathlib import Path
def clean_name(df, name_column, new_column, remove_list):
# Lowercase everything
df[new_column] = df[name_column].str.lower()
remove_list = [x.lower() for x in remove_list]
# Remove undesired wor... | pd.read_csv(path, index_col=0) | pandas.read_csv |
from context import dero
import pandas as pd
from pandas.util.testing import assert_frame_equal
from pandas import Timestamp
from numpy import nan
import numpy
class DataFrameTest:
df = pd.DataFrame([
(10516, 'a', '1/1/2000', 1.01),
(10516, 'a'... | pd.to_datetime(df_gvkey_str['Date']) | pandas.to_datetime |
'''
This module is used for content-based filtering
'''
import os.path
from ast import literal_eval
import pickle
import pandas as pd
import numpy
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from nltk.stem.snowball import SnowballStemmer
Run = F... | pd.read_csv('movies-dataset/links.csv') | pandas.read_csv |
from __future__ import print_function
import os
import torch
import numpy as np
import shutil
import pandas as pd
def test(model, dataloader, use_cuda, criterion, full_return=False, log_path=None):
"""
Computes the balanced accuracy of the model
:param model: the network (subclass of nn.Module)
:par... | pd.concat([results_df, row_df]) | pandas.concat |
from pypowerbifix.client import PowerBIClient
from pypowerbifix.activity_logs import ActivityLogs
from datetime import datetime
import pandas as pd
from Credentials import client_id, username, password
# create your powerbi api client
client = PowerBIClient.get_client_with_username_password(client_id=client_id, user... | pd.set_option('display.width', 1000) | pandas.set_option |
import numpy as np
import pandas as pd
from io import StringIO
import re
import csv
from csv import reader, writer
import sys
import os
import glob
import fnmatch
from os import path
import matplotlib
from matplotlib import pyplot as plt
print("You are using Zorbit Analyzer v0.1")
directory_path = input... | pd.unique(all_merge_just_ortho['SeqID']) | pandas.unique |
"""test_split_utils.py: tests for split_utils.py"""
from os import path
from math import floor
from datetime import datetime, timedelta
from tinydb import TinyDB, Query
import pandas as pd
import pytest
import publicAPI.split_utils as split_utils
import publicAPI.config as api_utils
import publicAPI.crest_utils as cr... | pd.to_numeric(raw_data[column]) | pandas.to_numeric |
import numpy as np
import pandas as pd
from analysis.transform_fast import load_raw_cohort, transform
def test_immuno_group():
raw_cohort = load_raw_cohort("tests/input.csv")
cohort = transform(raw_cohort)
for ix, row in cohort.iterrows():
# IF IMMRX_DAT <> NULL | Select | Next
if pd... | pd.isnull(row["astrxm1_dat"]) | pandas.isnull |
# coding: utf-8
import pandas as pd
import numpy as np
import cv2 # Used to manipulated the images
seed = 1207
np.random.seed(seed)
# Import Keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers import Conv2D, MaxPooling2D
from keras.callb... | pd.read_csv(wdir + 'sub_simple_v1_1.csv') | pandas.read_csv |
import os
#import dill
import numpy as np
import pandas as pd
from Bio import SeqIO, Seq
import scipy.stats as st
import deepak.globals
import deepak.utilities
from deepak.library import MutationLibrary
from deepak.plot import replace_wt, all_correlations, make_heatmaps, make_fig_dir
pad = 948
target_T3 = ":917*ag"
... | pd.DataFrame({"position": [item]*20, "amino_acid": deepak.globals.AA_LIST}) | pandas.DataFrame |
"""
@authors: <NAME> / <NAME>
goal: edf annotation reader
Modified: <NAME>, Stanford University, 2018
"""
import re
import numpy as np
import pandas as pd
import xmltodict
def read_edf_annotations(fname, annotation_format="edf/edf+"):
"""read_edf_annotations
Parameters:
-----------
fnam... | pd.to_timedelta(annot.index, unit='s') | pandas.to_timedelta |
import pandas as pd
import tensorflow as tf
from pathlib import Path
from datetime import datetime
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.models import load_model
#enviroment settings
path = Path(__file__).parent.absolute()/'Deep Training'
name_data = 'none_'#''
metric = 'binary_accu... | pd.read_csv(data_path/targets_name, usecols=targets_columns, index_col=targets_index) | pandas.read_csv |
import re
from pathlib import Path
import pandas as pd
import numpy as np
DATA_DIR = Path(__file__).parents[1] / 'data'
def load_uci():
"""Load data from http://archive.ics.uci.edu/ml/datasets/diabetes"""
data_path = str(DATA_DIR / 'public' / 'uci')
dfs = []
for p in Path(data_path).iterdir():
... | pd.to_numeric(df['Value']) | pandas.to_numeric |
"""
See also: test_reindex.py:TestReindexSetIndex
"""
from datetime import (
datetime,
timedelta,
)
import numpy as np
import pytest
from pandas import (
Categorical,
DataFrame,
DatetimeIndex,
Index,
MultiIndex,
Series,
date_range,
period_range,
to_datetime,
)
import panda... | tm.assert_index_equal(idf.index, ci) | pandas._testing.assert_index_equal |
import math
import collections
import pandas as pd
from IPython.display import clear_output
def get_price_index(year_growth_rate, month):
return math.pow(1 + year_growth_rate/12, month)
Payment = collections.namedtuple('Payment', ['interest_amount',
'capital_downpaym... | pd.DataFrame() | pandas.DataFrame |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
pd.set_option('display.max_columns', None)
import pandas as pd
from sklearn import preprocessing
from pandas.plotting import scatter_matrix
from matplotlib import pyplot
from sklearn.preprocessing import LabelEncoder
from sklearn.... | pd.read_csv("data/data500.csv") | pandas.read_csv |
import numpy as np
import pandas as pd
import sqlite3
class DataTransformation:
"""Performs data loading and data transformation
"""
def __init__(self, url:str) -> None:
try:
self.__data = pd.read_csv(url, sep=";")
self.__transform()
except Exception as error:
raise error("There was a ... | pd.to_datetime(self.__data['birth_date']) | pandas.to_datetime |
import pandas as pd
from sklearn.linear_model import SGDRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error
import matplotlib.pyplot as plt
import os
count = 0
reg = SGDRegressor()
predict_for = "NANOUSD.csv"
batch_size = "30T"
stop = pd.to_datetime("2020-08-01", format="%Y-%m-%d")
for pair... | pd.DataFrame(index=ts_df.index) | pandas.DataFrame |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#import networkx as nx
from scIB.utils import *
from scIB.preprocessing import score_cell_cycle
from scIB.clustering import opt_louvain
from scipy import sparse
from scipy.sparse.csgraph import connected_components
from scipy.io import mmwrite
im... | pd.DataFrame.from_dict(kBET_scores) | pandas.DataFrame.from_dict |
import pandas as pd
from datetime import date, datetime
from functools import wraps
import importlib_resources
import requests
import time
import os
import io
token = "<KEY>"
#<PASSWORD>
#8a0ff681501b0bac557bf90fe6a036f7
def counter(func):
"""
A decorator that counts how many times we executed a funciton.
In o... | pd.read_parquet('data1.parquet', engine='fastparquet') | pandas.read_parquet |
# author <NAME>
import os
import pickle
from collections import defaultdict
import click
import cv2
import pandas as pd
from datetime import datetime
from glob import glob
def validate_files():
"""
Check if files created from faces_train.py script
"""
recognizer_f = glob("./recognizers/*.yml")
pi... | pd.DataFrame(people_logger[key]) | pandas.DataFrame |
# --------------
# import packages
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# Load Offers
offers=pd.read_excel(path,sheet_name=0)
# Load Transactions
transactions=pd.read_excel(path,sheet_name=1)
transactions['n']=1
# Merge dataframes
df=pd.merge(offers,transacti... | pd.DataFrame(data=matrix,columns=['Customer Last Name','cluster','x','y']) | pandas.DataFrame |
# -*- coding: utf-8 -*-
"""Generator reserve plots.
This module creates plots of reserve provision and shortage at the generation
and region level.
@author: <NAME>
"""
import logging
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import marmot.config.mconfig as mconfig
from marmot.plotti... | pd.DataFrame() | pandas.DataFrame |
"""
Provide a generic structure to support window functions,
similar to how we have a Groupby object.
"""
from collections import defaultdict
from datetime import timedelta
from textwrap import dedent
from typing import List, Optional, Set
import warnings
import numpy as np
import pandas._libs.window as libwindow
fro... | Appender(_shared_docs["aggregate"]) | pandas.util._decorators.Appender |
# +
import os
import numpy as np
import pandas as pd
from tasrif.processing_pipeline import SequenceOperator
from tasrif.processing_pipeline.pandas import (
AsTypeOperator,
ConvertToDatetimeOperator,
JsonNormalizeOperator,
SetIndexOperator,
RenameOperator,
ResetIndexOperator,
DropFeaturesOp... | pd.DataFrame() | pandas.DataFrame |
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... | is_integer_dtype(x.dtype) | pandas.core.dtypes.common.is_integer_dtype |
# -*- coding: utf-8 -*-
# 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 file
# to you under the Apache License, Version 2.0 (the
# "... | pd.DataFrame({'decimals': values}) | pandas.DataFrame |
# Author: https://github.com/Gugu7264
import os
import gspread_asyncio as gaio
import hjson
import pandas as pd
from discord import Intents
from discord.ext import commands
from dotenv import load_dotenv
from oauth2client.service_account import ServiceAccountCredentials
import utilities
load_dotenv("../dev.env")
cl... | pd.DataFrame(daily[1:], columns=daily[0]) | pandas.DataFrame |
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input,Output
import os
print(os.getcwd())
df_input_large=pd.read_csv('C:/Users/Asus/ads_covid-19/data/processed/COVID_large... | pd.read_csv('C:/Users/Asus/ads_covid-19/data/processed/COVID_large_fitted_table.csv',sep=';') | pandas.read_csv |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <NAME>
This file contains functions to fetch data from the Domestic Load Research SQL Server database. It must be run from a server with a DLR database installation.
The following functions are defined:
getObs
getProfileID
getMetaPro... | pd.DataFrame(g, columns = ['Province','Municipality','District']) | pandas.DataFrame |
# Import libraries | Standard
import numpy as np
import pandas as pd
pd.set_option('display.max_columns', None)
import os
import datetime
import warnings
warnings.filterwarnings("ignore") # ignoring annoying warnings
from time import time
from rich.progress import track
# Import libraries | Visualization
... | pd.merge(train, features, how='left', on=['Store','Date']) | pandas.merge |
# |------------------------------------------------------------------
# | # Flu Prediction - Time Series Analysis TS2
# |------------------------------------------------------------------
# |
# | ## 1. Introduction
# |
# | This is a notebook to practice the routine procedures
# | commonly used in the time sequence ana... | pd.concat([X_lag, X_search], axis=1) | pandas.concat |
from datetime import datetime
import numpy as np
import pytest
import pandas.util._test_decorators as td
from pandas import DataFrame, DatetimeIndex, Index, MultiIndex, Series
import pandas._testing as tm
from pandas.core.window.common import flex_binary_moment
def _rolling_consistency_cases():
for window in [... | Series([1.1] * 15) | pandas.Series |
#
# Copyright (C) 2022 Databricks, Inc.
#
# 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 required by applicable law or agreed to i... | pd.to_datetime(self.fill_value) | pandas.to_datetime |
# -*- coding: utf-8 -*-
import pytest
import numpy as np
import pandas as pd
from pandas import Timestamp
def create_dataframe(tuple_data):
"""Create pandas df from tuple data with a header."""
return pd.DataFrame.from_records(tuple_data[1:], columns=tuple_data[0])
### REUSABLE FIXTURES --------------------... | Timestamp('2013-04-01 00:00:00') | pandas.Timestamp |
# RCS14_entrainment_naive.py
# Generate timeseries analysis and power estimate
# Author: maria.olaru@
"""
Created on Mon May 3 18:22:44 2021
@author: mariaolaru
"""
import numpy as np
import pandas as pd
import glob
from datetime import datetime
import os
import re
def get_filepaths(dir_name):
nchars = len(dir_... | pd.read_csv(meltp_fp, header=0) | pandas.read_csv |
import pandas as pd
import re
import sys
import os
blast_file = sys.argv[1]
sample=sys.argv[2]
data = pd.read_table(blast_file, header=None)
all_se1_ss2_se2_ss3 = {(data[9][i], data[13][i], data[14][i], data[18][i]) for i in range(len(data))}
if not os.path.exists("reads_group"):
os.mkdir("reads_group")
for item i... | pd.read_table("count_se1_ss2_se2_ss3_" + blast_file, header=None) | pandas.read_table |
"""
boydsworld_scraper
A scraper module for boydsworld.com historical game results
Created by <NAME> in November 2021
"""
# Imports
import pandas as pd
import numpy as np
import requests
from io import StringIO
from datetime import date
import lxml
def get_games(school, start, end=None, vs="all", parse_dates=True)... | pd.concat([wins,losses]) | pandas.concat |
# -*- coding: utf-8 -*-
# pylint: disable=E1101,E1103,W0232
import os
import sys
from datetime import datetime
from distutils.version import LooseVersion
import numpy as np
import pandas as pd
import pandas.compat as compat
import pandas.core.common as com
import pandas.util.testing as tm
from pandas import (Categor... | tm.assert_produces_warning(UserWarning) | pandas.util.testing.assert_produces_warning |
# @Date: 2019-08-16T23:31:03+08:00
# @Email: <EMAIL>
# @Filename: MMCIF_unit.py
# @Last modified time: 2019-08-21T16:02:36+08:00
import pandas as pd
import numpy as np
import os, re, time, requests, sys
from urllib import request, error
from retrying import retry
from multiprocessing.dummy import Pool
from bs4 impor... | pd.read_csv(outpath + integration_file_new, sep='\t', dtype=str) | pandas.read_csv |
#
# This program builds a SVM model to predict a loan payment default.
# It reads a labelled dataset of loan payments, makes the model, measures its accuracy and performs unit tests.
# It ends by a serialization through models. The serialized model is then used by the main program that serves it.
#
import os
import pa... | pd.DataFrame(iris.data) | pandas.DataFrame |
#!/usr/bin/env python
import load_data as ld
from models import vae_models
import training
import utils
import utils_train_predict as utp
import sys
import numpy as np
import pandas as pd
from collections import defaultdict
import subprocess
import argparse
def analyse_model(out_dict, loss_df, summary_function, leav... | pd.concat([recon_hamming, pred_hamming, closest_hamming]) | pandas.concat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.