text string | size int64 | token_count int64 |
|---|---|---|
from __future__ import print_function, division
import os,unittest
from pyscf.nao import system_vars_c
sv = system_vars_c().init_siesta_xml(label='water', cd=os.path.dirname(os.path.abspath(__file__)))
class KnowValues(unittest.TestCase):
def test_lil_vs_coo(self):
""" Init system variables on libnao's site ""... | 507 | 204 |
import trimesh
from pyrender import Mesh, Node, Scene, Viewer, PerspectiveCamera
import numpy as np
import json
import os
from latentgan.config import *
NUM_GENERATIONS = 8
OFFSET = 0
viewport_w = 900
viewport_h = 900
def get_trimesh_and_uv(scene_or_mesh):
if isinstance(scene_or_mesh, trimesh.Scene):
mes... | 2,768 | 1,032 |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def fractal_mandelbrot(size=1000, real_range=(-2, 2), imaginary_range=(-2, 2), threshold=4, iterations=25, buddha=False, show=False):
"""Generate a Mandelbrot (or a Buddhabrot) fractal
Vectorized function to efficiently generate a... | 7,588 | 2,619 |
#! /usr/bin/python
import sys
""" This reads the output file from samtools depth command """
""" and iterates over all the base position to calculate """
""" the average coverage depth and width """
"""
Author: Matthew Ezewudo
CPTR ReSeqTB Project - Critical Path Institute
"""
input1 = sys.argv[1]
depth = 0
coun... | 754 | 284 |
# coding=utf-8
import setuptools
with open("README.md") as fh:
long_description = fh.read()
setuptools.setup(
name="huunifie",
version="0.4.3",
author="KurisuD",
author_email="KurisuD@pypi.darnand.net",
description="""A Hue bridge and Unifi controller client.
Enables/disables specified Hue sc... | 905 | 288 |
import helper.colors
import os
import os.path
import math
from objects import Renderable
from random import Random
from svgwrite import Drawing
from svgwrite.container import Group
from PIL import Image
from typing import Tuple
from io import BytesIO
ASSET_DIR = os.path.realpath(os.path.dirname(__file__) + "/../assets... | 3,088 | 990 |
def gen_contents(ids: list):
recipes = list()
pairs = list()
json = """
{{
"type": "minecraft:stonecutting",
"ingredient": {{
"item": "{src}"
}},
"result": "{dest}",
"count": 1
}}
"""
for source_item in ids:
for dest_item in ids:... | 594 | 183 |
# Generated by Django 3.0.7 on 2020-07-04 04:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_auto_20200703_1935'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='rank',
... | 559 | 190 |
#Chapter-3_upper_lower.py
first_name = "Karry";
last_name = "Yee"
full_name = first_name + " " + last_name;
"""
print(full_name.upper());
print(full_name.lower());
print(full_name.title());
"""
celebrated_dictum = '"A person who never made a mistake never tried anything new."';
famous_person = "\tAlbert Einstein\n";
p... | 684 | 251 |
import random
import struct
import time
from typing import TypeVar, Type
from datetime import datetime
from bxcommon import constants
from bxcommon.constants import UL_INT_SIZE_IN_BYTES, NETWORK_NUM_LEN, NODE_ID_SIZE_IN_BYTES, BX_HDR_COMMON_OFF, \
BLOCK_ENCRYPTED_FLAG_LEN, TRANSACTION_FLAG_LEN, BROADCAST_TYPE_LEN
... | 38,080 | 12,241 |
import sys
from QtClass.MainWindow import App
from PyQt5 import QtCore, QtGui, QtWidgets
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = App()
window.show()
sys.exit(app.exec_()) | 222 | 77 |
from datetime import datetime
import time
def get_current_time():
return int(time.time())
def is_today_milliseconds(timestamp):
timestamp = int(timestamp / 1000)
return is_today(timestamp)
def is_today(timestamp):
today = datetime.now()
dt_object = datetime.fromtimestamp(timestamp)
return ... | 435 | 133 |
import os
import pdfplumber
from config import Config, bot, logger
stack = []
def delete_all_previous_messages():
global stack
while stack:
bot.delete_message(Config.TELEGRAM.CHAT_ID, stack.pop())
def send_message(msg, markup=None):
global stack
delete_all_previous_messages()
msg = b... | 824 | 286 |
import os
import collections
import json
import cv2
import time
from utils_BINGO import divide_img_range
from utils_BINGO import gtsToxml
def mkdataset_in_VOC_format(im_path,save_dir,gt_json_path ,dataset_name,section_num, mode=0):
'''
To make a detection dataset in VOC format.
:param im_path: Original i... | 5,327 | 1,800 |
import unittest
from src.marksim import tpm
import numpy as np
class TestTPM(unittest.TestCase):
"""
Tests for the transition probability matrix calculation
"""
def nan_equal(self, a, b):
"""
compare two numpy arrays with NaN
:param a: np.array
:param b: np.array
... | 3,553 | 1,493 |
import pygame.font
from pygame.sprite import Group
from ship import Ship
class Scoreboard():
"""A CLASS TO REPORT SCORING INFORMATION"""
def __init__(self, ai_settings, screen, stats):
"""INITIALIZE SCOREKEEPING ATTRIBUTES"""
self.screen = screen
self.screen_rect = screen.get_rect()
... | 2,032 | 714 |
import model.fastSal as fastsal
from dataset.utils import read_vgg_img
from utils import load_weight
from torch.utils.data import Dataset, DataLoader
import torch.nn as nn
from os.path import isfile, isdir, join
from os import listdir
import numpy as np
import argparse
from generate_img import post_process_png, post_pr... | 4,417 | 1,429 |
import random
import markdown as md
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter(name='markdown')
def markdown(value):
return mark_safe(md.markdown(value, extensions=['extra', 'codehilite']))
@register.simple_tag(name='titlefont')
d... | 947 | 316 |
# Copyright (c) 2015 Davide Gessa
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import time
import cvmutils
if __name__ == "__main__":
cvmutils.spawn (3)
while True:
time.sleep (5)
sys.exit ()
| 315 | 113 |
"""Example of a merge network with human-driven vehicles.
In the absence of autonomous vehicles, the network exhibits properties of
convective instability, with perturbations propagating upstream from the merge
point before exiting the network.
"""
from flow.core.params import SumoParams, EnvParams, \
NetParams, ... | 7,577 | 2,495 |
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | 1,774 | 581 |
from transformers import AutoTokenizer
import torch
class Data:
def __init__(self,texts,labels):
self.class_mapping = {"positive":0,"negative":1}
self.texts = texts
self.labels = labels
self.MAX_LENGTH = 250
self.tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")... | 1,072 | 330 |
# Copyright 2018/2019 The RLgraph authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 8,335 | 2,544 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import random
import sys
import os
from network import ActorCriticFFNetwork
from training_thread import A3CTrainingThread
from scene_loader import THORDiscreteEnvironment as Environment
from utils.ops import sample_ac... | 2,550 | 902 |
import os
from werkzeug.serving import run_simple
from werkzeug.middleware.shared_data import SharedDataMiddleware
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
@Request.application
def app(request):
urls = url_map.bind_to_environ(request.environ)
endpoint, args = url... | 836 | 277 |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float64
import pygame
import sys
from pygame.locals import *
import threading
import sys
import numpy as np
from time import sleep
def center(src, dest):
src.centerx = dest.centerx
src.centery = dest.centery
class Button:
def __init__(self, rect,... | 5,920 | 2,019 |
#!BPY
# -*- coding: latin-1 -*-
"""
Name: 'Bolt Factory'
Blender: 248
Group: 'Wizards'
Tooltip: 'Create models of various types of screw fasteners.'
"""
__author__ = " Aaron Keith (Spudmn) "
__version__ = "2.02 2009/06/10"
__url__ = ["Author's site,http://sourceforge.net/projects/boltfactory/", "Blender,http://wiki.bl... | 87,211 | 35,057 |
import os
import csv
import json
import glob
import gzip
import random
import tarfile
import zipfile
import pandas as pd
from .downloader_utils import get_corpora_dict
from .downloader_utils import get_resource_dir
def _extract_tarfile(filename, target_dir):
with tarfile.open(filename, 'r:*') as tar:
ta... | 14,439 | 4,568 |
from typing import Union, Generator, Iterator
import grpc
from grpc._cython import cygrpc
from v2_plugin.protos import infer_pb2_grpc
from v2_plugin.protos.infer_pb2 import InferRequest, Empty, InferResponse
class RPCClient(object):
def __init__(self, port: int):
self.channel = grpc.insecure_channel(
... | 1,540 | 463 |
# Solution by PauloBA
def expression_out(exp):
list = []
sorter = []
ans = ""
ac = ""
c = 0
op = {'+':'Plus', '-':'Minus', '*':'Times', '/':'Divided By', '**':'To The Power Of', '=':'Equals', '!=':'Does Not Equal'}
expressions = {'1':'One', '2':'Two', '3':'Three', '4':'Four', '5':'Five', '6... | 1,221 | 419 |
import numpy as np
class Spine:
def __init__(self, parameters, initial, attachment_points, g = True):
self.barlength = 0.5
self.parameters = parameters
self.states = initial
self.inputs = None
self.attachments = attachment_points
self.rod = self.bar_length()
... | 4,685 | 1,802 |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
work_dir = '/tmp'
model_version = 9
training_iteration = 1000
input_size = 784
no_classes = 10
batch_size = 100
total_batches = 200
tf_example = tf.parse_example(tf.placeholder(tf.string, name='tf_example'),
... | 1,982 | 699 |
# Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 3,252 | 1,096 |
from django.db import models
import datetime as dt
# Create your models here.
class Location(models.Model):
i_location = models.CharField(max_length=30, blank=True)
def save_location(self):
self.save()
def delete_location(self):
Location.objects.filter(pk=self.id).delete()
def __str__(self):
retur... | 1,452 | 477 |
# coding: utf-8
from __future__ import unicode_literals
import os
try:
import cPickle as pickle
except ImportError:
import pickle
from uuid import uuid4
from django.db.models.fields.related import RelatedField
from django.forms.models import model_to_dict
from django.core.cache import caches
from .settings... | 1,936 | 632 |
import numpy as np
import pkg_resources
import pytest
import optimal_nod_combo.optimal_nods_selection as ons
def test_parse_boolgrid():
testfile = pkg_resources.resource_filename("optimal_nod_combo", "data/boolgrid_test_data.dat")
# 11111011
# 01111111
# 11011101
# 00000010
test_grid = np.arr... | 1,353 | 591 |
#!/usr/bin/env python3
"""
@summary: deploy contract
@version: v46 (03/January/2019)
@since: 2/May/2018
@organization:
@author: https://github.com/drandreaskrueger
@see: https://github.com/drandreaskrueger/chainhammer for updates
"""
################
## Dependencies:
import sys, time, json
from pprint impor... | 5,627 | 1,783 |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | 6,501 | 2,875 |
#####
# CONVERT NCAR CLIMATOLOGIES TO BE CONSISTENT WITH CMIP STRUCTURE FOR PMP USE
# PLANNED IMPROVEMENTS:
# CURRENTLY ASSUMES cdscan XML FILES HAVE BEEN CREATED IN ADVANCE
# CURRENTLY ASSUMES LOCATION OF XML FILES AND PRODUCES CLIMS FOR ALL SIMULATIONS WITH XMLS
# CURRENTLY HAS OUTPUT "data" DIRECTORY
# ... | 5,445 | 2,372 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os, time
import numpy as np
import torch
import json
from log_utils import print_log
from collections import Ordere... | 3,793 | 1,229 |
import torch
from .actor import Actor
from .critic import Critic
from .router import Router
from .encoder import Encoder
from .decoder import Decoder
class MTPM(torch.nn.Module):
def __init__(self):
self.actor = Actor()
self.critic = Critic() # needs to be a q function
self.router = Router()
self.encode... | 565 | 236 |
"""
Module for storing usp files into the database
"""
import warnings
from aiida.plugins import DataFactory
from aiida.common.utils import classproperty
from aiida.common.files import md5_file
from .utils import get_usp_element
OLD_USPGROUP_TYPE = "data.castep.usp.family"
USPGROUP_TYPE = "castep.otfg"
SinglefileDat... | 12,135 | 3,333 |
#Faça um Programa que leia um vetor de 5 números inteiros, mostre a soma, a multiplicação e os número.
import numpy
vetor=[]
for n in range(0,5):
valor=int(input(f'digite o {n+1} valor: '))
vetor.append(valor)
soma=sum(vetor)
mult=numpy.prod(vetor)
print('-=-'*20)
print(f'A soma dos números: {soma}')
print(f'A ... | 391 | 165 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: group_search_service.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import ... | 11,583 | 4,463 |
from abaqusConstants import *
class StabilizationAssignment:
"""The StabilizationAssignment object stores the contact stabilization assignment
definition for domain pairs in a ContactStd object. The StabilizationAssignment object
has no constructor or members.
Notes
-----
This object can be... | 2,467 | 560 |
import torch
from torchvision.utils import make_grid
from src.callbacks.loggers.base_logger import BaseLogger
class Dsb15VSRLogger(BaseLogger):
"""The DSB15 logger for the Video Super-Resolution.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def _add_images(self, epoch, train_... | 1,430 | 476 |
import os
import sys
file_path = sys.argv[1]
coco_info = sys.argv[2]
info_name = sys.argv[3]
image_names = []
image_size = []
with open(coco_info, 'r') as file:
contents = file.read().split('\n')
for content in contents[:-1]:
temp = content.split()
key = temp[1]
image_names.append(key[key.rfind('/')... | 728 | 276 |
'''
Aggregate data
'''
import argparse, os, sys, errno, subprocess, csv
phenotypic_traits = ["not","nand","and","ornot","or","andnot"]#,"nor","xor","equals"]
even_traits = {"not", "and", "or"}#, "nor", "equals"}
odd_traits = {"nand", "ornot", "andnot", "xor"}#, "equals"}
even_profile = "101010"#101"
odd_profile = "01... | 7,433 | 2,443 |
#!/usr/bin/env python3
import math
import random
if __name__ == "__main__":
# Parse arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--activation", default="relu", type=str, help="activation")
parser.add_argument("--x", default=0.0, type=float, help="X")
parse... | 1,456 | 509 |
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import time
import random
import datetime
from datetime import date
from datetime import timedelta
from dateutil.relativedelta import relativedelta
import pickle
from pyomo.environ import *
from pyomo.opt import SolverFactory
def... | 4,692 | 1,797 |
from marshmallow import fields
from lms.services import ExternalRequestError, OAuth2TokenError
from lms.validation import RequestsResponseSchema
from lms.validation.authentication import OAuthTokenResponseSchema
class _OAuthAccessTokenErrorResponseSchema(RequestsResponseSchema):
"""Schema for parsing OAuth 2 acc... | 4,868 | 1,313 |
#Anneliek ter Horst, 2017
# load pandas
import sys
import csv
import pandas as pd
from collections import defaultdict
import time
# load dataframe
df = pd.DataFrame.from_csv(open(sys.argv[1]))
print len(df)
# list to store index that are either unique enough or have highest evalue
results = []
# list to save those... | 2,583 | 795 |
""" A small utility that converts raw pcm audio into wav files
Converts raw PCM samples into .wav files. The .wav files will be stored alongside the .raw files
`--input` the path to where the raw files are being stored.
"""
import json
import os, time, hmac, hashlib
import requests
import serial
import argparse
impo... | 2,131 | 674 |
"""an improvement to the deprecated "terrain" module.
it uses the Block class rather than just strings, which are
now mutable, and easier to use, and change. it also uses blocks based
off of real materials; for example if the template is "sand" it will
actually use a block called "Sand". (Mostly inspired by Minecraft's... | 7,003 | 2,123 |
'''
Created on 22.11.2019
@author: Zoli
'''
import openpyxl
from os import path
from pathlib import Path
import atexit
class ExcelReporter(object):
'''
classdocs
'''
def __init__(self, outputFilename):
'''
Constructor
'''
self.outputFilename = outputFilename
n... | 7,823 | 2,299 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('detail/<int:book_id>/', views.book_detail,{'name':'kangbazi'}),
]
| 168 | 59 |
from greenbot.modules.base import BaseModule
from greenbot.modules.base import ModuleSetting
from greenbot.modules.base import ModuleType
from greenbot.modules.basic import BasicCommandsModule
from greenbot.modules.basic.admincommands import AdminCommandsModule
from greenbot.modules.advancedadminlog import AdvancedAdm... | 1,099 | 305 |
import random
from datetime import datetime
from hashlib import md5
import pygame
from bots import AttackBot, DefenseBot, RangedBot, RepairBot
from bots import BuilderBot, KamikazeBot, Swarm, MotherShipBot, Supplies
from game import Display, Settings, Arena, Colors, ShipRoles, Game
from sim import Queue, QueueControl... | 8,120 | 2,743 |
# Generated by Django 2.2.4 on 2019-09-29 19:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('houses', '0015_house_is_accessible'),
]
operations = [
migrations.AddField(
model_name='house',
name='open_to_student... | 583 | 183 |
# %% [markdown]
# pip install -r pykrx
# %%
from datetime import datetime, timedelta
import FinanceDataReader as fdr
import yfinance as yf
import numpy as np
import pandas as pd
from pykrx import stock
import time
import bt
import warnings
# from tqdm import tqdm
warnings.filterwarnings(action='ignore')
# pd.options.d... | 9,562 | 6,145 |
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import StandardScaler
from utility import function
from ann.Dense import Dense
np.random.seed(135)
data_count = 25
x1_points = np.linspace(0, 10, data_count).reshape((-1, 1))
x2_points = np.multiply(2, x1_points) + np.random.randint(-10, ... | 2,393 | 1,151 |
def get_footer_html(html, opening_tag="<p>"):
opening_tag_start = html.rfind(opening_tag)
opening_tag_end = opening_tag_start + len(opening_tag)
closing_tag = opening_tag.replace("<", "</")
closing_tag_start = html.rfind(closing_tag)
closing_tag_end = closing_tag_start + len(closing_tag)
result ... | 380 | 136 |
>>>pipenv run python3 <program_name>.py
| 41 | 15 |
#!/usr/bin/env python
import argparse
import datetime
import json
import os
import requests
import time
import re
FILES_ENDPOINT = 'https://api.gdc.cancer.gov/files'
DESC = """This program will attempt to use the GDC api to associate a file or set of files with any fields specified
If no fields are specified only the... | 2,983 | 862 |
#!/usr/bin/env python3
# ========================================================================
#
# Imports
#
# ========================================================================
import numpy as np
import argparse
import matplotlib.pyplot as plt
from matplotlib import rcParams
import matplotlib.colors as color... | 13,234 | 5,322 |
from __future__ import division
import os
from ..datasets import build_dataloader
from ..utils import save_imgs
from .env import get_root_logger
def test_geometric_matching(model,
dataset,
cfg,
distributed=False,
... | 3,108 | 1,063 |
#!/usr/bin/python
##############
# View the statistics for a single experiment (bag file)
#
# Statistics are plotted separately, i.e. one window per object per variant,
# showing precision and recall.
import numpy as np
import matplotlib.pylab as plt
import matplotlib
matplotlib.rcParams['ps.useafm'] = True
matplotli... | 1,935 | 748 |
import sys
from os import path
import json
import pytest
import random
from flask import Flask
from .helper import *
# 将路径添加到 sys.path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
class TestUser:
def setup_method(self):
from app.utils import getmd5
self._email = DEFAULT_LO... | 2,333 | 760 |
"""Utility functions for working with strings"""
# --------------------------------------------------------------------------------
# > Functions
# --------------------------------------------------------------------------------
def clean_text(text, char_list, replacement=" "):
"""
Replaces specific character... | 1,545 | 426 |
import json
'''
Classe utilizada como enum para troca de mensagens entre os sitemas. No caso, comandos utilizados.
'''
class Commands:
MOVE_TO = "move_to" # Utilizada pra indicar a nova movimentação do robo
START = "start" # Utilizada para dar inicio a caça as bandeiras
... | 1,706 | 543 |
import h2o
import numpy as np
dir(h2o)
# open FLOW at http://localhost:54321/flow/index.html
h2o.init(ip="127.0.0.1", port=54321)
help(h2o.estimators.glm.H2OGeneralizedLinearEstimator)
h2o.estimators.glm.H2OGeneralizedLinearEstimator?
#h2o.demo("glm")
#l=[[1, 2, 3], ['a','b','c'], [0.1, 0.2, 0.3]]
#df = h2o.H2OFr... | 8,623 | 2,934 |
from setuptools import setup, find_packages
setup(
name='tower',
version='0.4.1',
description='Pull strings from a variety of sources, collapse whitespace, '
'support context (msgctxt), and merging .pot files.',
long_description=open('README.rst').read(),
author='Wil Clouser',
a... | 1,106 | 315 |
"""
Estimate infection curve
Created: 2020-09-09
Last modified: 2020-09-23
"""
# third party
import numpy as np
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
# r imports
genlasso = importr('genlasso')
rlist2dict = lambda x: dict(x.items())
rfloat2arr = lambda x: np.array(x)
# first part... | 2,132 | 737 |
"""
Run all or some tests
"""
import argparse
import glob
import os
from pathlib import Path
import robot
from robot import rebot
def parse_argument():
"""
Parses optional arguments that's then gets passed to the robot files.
This makes it possible to customise the paths for different environments.
"... | 4,174 | 1,113 |
from sklearn.base import BaseEstimator
from warnings import warn
from textwrap import dedent
from ya_pca.PCA import PCA
from mvlearn.utils import check_Xs
from mvdr.mcca.mcca import MCCA, MCCAView
from mvdr.ajive.ajive_fun import ajive, _ajive_docs
from mvdr.ajive.plot_ajive_diagnostic import plot_joint_diagnostic
fr... | 10,994 | 3,405 |
from alpha_vantage.timeseries import TimeSeries
import pandas as pd
import numpy as np
import time
sp = pd.DataFrame(pd.read_csv('./constituents_csv.csv'))
key = '9AD6SV02MT4Z7G8W'
ts = TimeSeries(key, output_format='pandas')
# aapl, meta = ts.get_monthly_adjusted(symbol='AAPL')
# print(aapl[aapl.index >= '2015'])... | 1,553 | 518 |
"""
Module for building a complete daily dataset from quandl sharadar's dataset.
written by https://github.com/ajjcoppola
make sure you set the QUANDL_API_KEY env variable to use this bundle
"""
from io import BytesIO
from zipfile import ZipFile
from click import progressbar
from logbook import Logger
import pandas a... | 9,042 | 2,808 |
from .base import *
class League(BaseModel):
# Implicit id auto increment field created
name = models.TextField(unique=True, blank=True, null=False)
country = models.TextField(blank=True, null=False)
number_of_teams = models.IntegerField(blank=True, null=False, default=0)
most_championships = mode... | 840 | 263 |
NO_DEFAULT = object()
NO_VALUE = object()
| 42 | 15 |
"""
Copyright 2017 Brocade Communications Systems, 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... | 18,929 | 5,110 |
# Generated by Django 3.0.6 on 2020-06-07 07:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('actualPlanner', '0007_planner_rating'),
]
operations = [
migrations.RenameField(
model_name='rating',
old_name='user... | 543 | 176 |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.leveleditor.worldData.interior_spanish_store_destroyed
from pandac.PandaModules import Point3, VBase3, Vec4, Vec3
objectStruct =... | 1,045 | 554 |
# fields.py
from datetime import date, datetime
import logging
import re
logger = logging.getLogger(__name__)
DATE_FORMATS = (
'%m-%d-%Y',
'%m-%d-%y',
'%m/%d/%Y',
'%m/%d/%y',
'%m%d%Y',
'%m%d%y',
'%m/%d',
'%m-%d',
'%m%d',
'%Y%m%d',
'%Y-%m-%d',
'%Y/%m/%d',
'%y%m%d',
... | 4,243 | 1,246 |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.jvm.rules.targets import COMMON_JVM_FIELDS
from pants.engine.target import Sources, StringField, Target
class JavaAntlrSources(Sources):
required = True
class An... | 1,102 | 344 |
from varappx.models.gemini import Samples
#from varappx.data_models.samples import SamplesSelection, Sample
from varappx.models.users import Bam, VariantsDb
import itertools
from operator import attrgetter
#
#
# def sample_factory(s:Samples):
# """Create a more useful Sample instance from a Django Samples instance ... | 2,360 | 785 |
import typing as T
nt = T.NamedTuple("name", field=str) | 56 | 21 |
# Watch how many messages people send and warn them about sending too many messages.
# If you have admin permissions they will be muted.
import time
from pyrogram import Client, filters
from pyrogram.types import Message
app = Client("my_account")
flooders = {}
FLOOD_MUTE_TIME = 60
GROUP_ADMINS = {}
def get_chat... | 1,553 | 499 |
"""
Properties
Stable
O(1) extra space
O(n^2) comparisons and swaps
Adaptive: O(n) time when nearly sorted
Very low overhead
"""
"""
Although it is one of the elementary sorting algorithms
with O(n2) worst-case time, insertion sort is the algorithm
of choice either when the data is nearly sorted
(b... | 2,366 | 863 |
from apps.address.models import City, Country
from rest_framework import serializers
class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = [
"id",
"name",
]
class CitySerializer(serializers.ModelSerializer):
class Meta:
... | 405 | 102 |
from .base import BaseTestCase # NOQA
from .decorators import skip_file_descriptor_check # NOQA
| 98 | 33 |
# all tests need print to work! make sure it does work
print(1)
print('abc')
| 78 | 26 |
# Problem Description
# Input Format. The first line contains an integer 𝑑. The second line contains an integer 𝑚. The third line
# specifies an integer 𝑛. Finally, the last line contains integers stop1, stop2, . . . , stop𝑛.
# Input Format. Assuming that the distance between the cities is 𝑑 miles, a car can tr... | 1,526 | 595 |
"""Various exceptions for the Awair API."""
from typing import Optional
class AwairError(Exception):
"""Base awair exception class."""
message = "Error querying the Awair API."
def __init__(self, extra_message: Optional[str] = None) -> None:
"""Add extra messages to our base message."""
... | 1,147 | 324 |
"""
These are sketches of how to use the ABC graphical model in the algorithms
"""
import numpy as np
class ABCMethod(object):
def __init__(self, N, distance_node=None, parameter_nodes=None, batch_size=10):
if not distance_node or not parameter_nodes:
raise ValueError("Need to give the distan... | 3,236 | 933 |
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto.Protocol.KDF import PBKDF2
try:
from .Sup import sha000
except:
from Sup import sha000
try:
from .eff_long import words
#from .words6 import words
#from .usrsharedictwords6 import words
except:
from eff_long import words
#from words6 impor... | 1,846 | 765 |
from discord.ext.commands.errors import CheckFailure
class NotConnectedToVoice(CheckFailure):
"""No Estas Conectado A un canal de voz"""
pass
class PlayerNotConnected(CheckFailure):
"""Musica no conectada"""
pass
class MustBeSameChannel(CheckFailure):
"""Player and user not i... | 351 | 121 |
import os
from multiprocessing import Queue
from collections import defaultdict
from scxmlProcessor import Loader
class FamillyManager:
def __init__(self, dictData):
self.data = dictData
self.familly = dict()
self.fathers = list()
self.path = dict()
self.toTheEnd = list()... | 3,020 | 930 |
from rest_framework import serializers
from WhereToServer import settings
from .models import User, Place, PlaceImage, CoordinatePlace, Menu, Food, Review, PlaceScore, Relation, FavoritePlace, \
Token, FavoritePlaceType, ReviewVote, PlaceImageVote, Hashtag
class TokenSerializer(serializers.ModelSerializer):
... | 16,968 | 5,084 |
from . import main
from flask import render_template,request,redirect, url_for, abort
from flask_login import login_required,current_user
from ..models import Pitch,User,Comment
from .forms import PitchForm, CommentsForm
from .. import db
@main.route('/')
def index():
'''
View root page function that returns... | 1,914 | 593 |
import gengoal, goal, goalorg | 29 | 10 |