id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3241334 | from numpy import float32
def segment_data(data, perc, train, labels):
"""
Segments the neural network's input data (X). Does it for the training or cross validation according with the percentage.
:param data: 2D array with labels on the first column and the rest of the data in the other
:param p... | StarcoderdataPython |
3378364 | import inspect
import logging
import sys
from typing import Callable, Optional, Type, TypeVar
LOG = logging.getLogger("AutoClick")
EMPTY = inspect.Signature.empty
EMPTY_OR_NONE = {EMPTY, None}
GLOBAL_CONFIG = {}
T = TypeVar("T")
def set_global(name: str, value: T) -> Optional[T]:
"""
Configure global AutoCl... | StarcoderdataPython |
3274445 | #
# MIT License
#
# Copyright (c) 2018 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... | StarcoderdataPython |
3332435 | <gh_stars>0
PLUGIN_NAME = "shareobject" | StarcoderdataPython |
3224431 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import errno
FileNotFoundError = getattr(__builtins__, "FileNotFoundError", IOError)
class Dummy(object):
def __str__(self):
return ""
_default = Dummy()
class BadParameter(Exception):
"""An exception that formats out a standardi... | StarcoderdataPython |
79940 | # coding=utf-8
from __future__ import unicode_literals
from flask import Blueprint
main_entry_mod = Blueprint('main_entry', __name__)
from . import views, test_views, deprecated_views
| StarcoderdataPython |
146652 | """
© Copyright 2021 Graphcore Ltd. All rights reserved.
© Copyright 2020, The Hugging Face Team, Licenced under the Apache License,Version 2.0
"""
"""
# Hugging Face: Fine-tuning a pretrained transformer
This tutorial demonstrates how to fine-tune a pretrained model from the Hugging
Face transformers library using ... | StarcoderdataPython |
147289 | <reponame>lih627/python-algorithm-templates<gh_stars>10-100
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
cnt, pre = 0, 0
length = len(flowerbed)
flowers = flowerbed + [0]
for idx, _ in enumerate(flowerbed):
next_ = flowers[idx]
... | StarcoderdataPython |
1770190 | import unittest
import pathlib
from tocot.toc_builder import TOCBuilder
class TestTOCBuilder(unittest.TestCase):
def test_build(self):
""" test build method """
testdata_dir = pathlib.Path("tests/testdata")
testmd = testdata_dir / "test.md"
tests = [
{
... | StarcoderdataPython |
3256611 | from graph.graph import Graph
| StarcoderdataPython |
3208921 | <filename>robots/saver.py
from pymongo import MongoClient
class Saver():
def __init__(self):
self.client = MongoClient('localhost', 27017)
self.db = self.client.testejoker
#columns
self.coll_rt_tweets = self.db.realTimeTweets
self.coll_s_tweets = self.db.searchedTweets
... | StarcoderdataPython |
1675155 | from flask import (
render_template,
redirect,
jsonify,
request,
flash,
url_for,
get_flashed_messages,
abort
)
from flask_login import (
login_user,
logout_user,
login_required,
current_user
)
from flask_principal import (
identity_changed,
current_app,... | StarcoderdataPython |
94207 | <gh_stars>1-10
import re
from typing import Optional, Tuple
from hummingbot.client.config.config_var import ConfigVar
from hummingbot.client.config.config_methods import using_exchange
CENTRALIZED = True
EXAMPLE_PAIR = "BTC-USDT"
DEFAULT_FEES = [0.02, 0.04]
SPECIAL_PAIRS = re.compile(r"^(BAT|BNB|HNT|ONT|OXT|US... | StarcoderdataPython |
1779821 | from __future__ import unicode_literals
import os.path, shutil
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from require.conf import settings as require_settings
def default_staticfiles_dir():
staticfiles_dirs = getattr(settings, "STATICFILES_DIRS", ())
... | StarcoderdataPython |
1698203 | <reponame>krishnatejakk/cords
import math
import random
import time
import torch
import torch.nn.functional as F
from .dataselectionstrategy import DataSelectionStrategy
class GLISTERStrategy(DataSelectionStrategy):
"""
Implementation of GLISTER-ONLINE Strategy from the paper :footcite:`killamsetty2020glister... | StarcoderdataPython |
22839 | <reponame>BudzynskiMaciej/notifai_recruitment<filename>utils/auth.py
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions
from notifai_recruitment import settings
class MasterKeyNaiveAuthentication(authentication.BaseAuthe... | StarcoderdataPython |
1689611 | import sys
import wordnet
import argparse
import re
import change_manager
import csv
from merge import wn_merge
def main():
parser = argparse.ArgumentParser(description="Merge a synset - delete one or more synset and merge all properties. This may create weird or contradictory results so should be used with care")... | StarcoderdataPython |
191377 | <reponame>richardzhao2/PyvinDurant<gh_stars>0
import numpy
import cv2
import pywinauto
import PIL
import time
import math
basket_color= ([90, 191, 210], [106, 225, 247])
ball_color = ([37, 45, 71], [98, 106, 135])
ball_coords = (959, 860)
vel_fac = 6.70
arc_fac = 0.4
last_pos = (0, 0)
middle_range = 100
sample_in... | StarcoderdataPython |
183411 | <filename>stubs.min/System/Windows/__init___parts/FontSizeConverter.py
class FontSizeConverter(TypeConverter):
"""
Converts font size values to and from other type representations.
FontSizeConverter()
"""
def CanConvertFrom(self,*__args):
"""
CanConvertFrom(self: FontSizeConverter,context: ITypeDes... | StarcoderdataPython |
59565 | import contextlib
import glob
import io
import json
import os
import re
import requests
import subprocess
import time
from dcicutils import ff_utils
from dcicutils.beanstalk_utils import get_beanstalk_real_url
from dcicutils.command_utils import yes_or_no
from dcicutils.env_utils import full_cgap_env_name
from dcicuti... | StarcoderdataPython |
3382615 | import collections
import json
import tensorflow as tf
import os
flags = tf.app.flags
flags.DEFINE_string('token_path', '/home/hillyess/ai/project-image-caption/flickr30k_images/results_20130124.token', 'Root directory to raw dataset.')
flags.DEFINE_integer('vocabulary_size', 5000, 'Vocabulary size of dictionary')
t... | StarcoderdataPython |
3317751 | <filename>music21/graph/findPlot.py
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Name: graph/findPlot.py
# Purpose: Methods for finding appropriate plots for plotStream.
#
# Authors: <NAME>
# <NAME>
#
# Copyright: Copyright... | StarcoderdataPython |
147183 | <reponame>5tefan/py-netcdf-timeseries-gui
from collections import OrderedDict
import numpy as np
from PyQt5.QtCore import QCoreApplication, pyqtSlot, pyqtSignal, QMutex
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QSpinBox, QLabel, QCheckBox
from PyQt5.QtWidgets import QFormLayout
from pyntpg.clear_layout import... | StarcoderdataPython |
194947 | <filename>dace/sdfg/replace.py
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
""" Contains functionality to perform find-and-replace of symbols in SDFGs. """
from dace import dtypes, properties, symbolic
from dace.frontend.python.astutils import ASTFindReplace
import re
import sympy as sp
... | StarcoderdataPython |
102010 | <filename>v1/payments/migrations/0001_initial.py
# Generated by Django 3.0.2 on 2020-01-26 13:22
from django.db import migrations, models
import django.db.models.deletion
import v1.payments.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('business', '0005_auto_2020012... | StarcoderdataPython |
3385268 | <gh_stars>0
#!/usr/bin/python
# coding:utf-8
__Author__ = 'Adair.l'
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='labinstrument',
version = '1.0.2',
description='''This is a package for Communication lab instrument romot... | StarcoderdataPython |
3255548 | <gh_stars>1-10
"""
Extract all AFL runs that aborted, because no input was non-crashing
"""
from os import path
from collections import OrderedDict
from .helper import generic_main, get_fuzz_outdirs
def aflabort(macke_directory):
result = OrderedDict()
aborts = []
for (function, outpath) in get_fuzz_out... | StarcoderdataPython |
60106 | from bluetooth_communication import AndroidAPI, AndroidThread, AndroidExploreRunThread
from pc_communication import PcThread, PcExploreRunThread
from serial_stub import SerialAPIStub
__author__ = 'Danyang'
if __name__=="__main__":
print "Executing main flow"
serial_api = SerialAPIStub()
android_api = Andr... | StarcoderdataPython |
3243835 | from django.contrib import admin
from django.urls import include, path
from gcpdjango.apps.main import urls as main_urls
from gcpdjango.apps.base import urls as base_urls
from gcpdjango.apps.users import urls as user_urls
# Customize admin title, headers
admin.site.site_header = "gcp-django-stanford Administration"
ad... | StarcoderdataPython |
3377555 | <filename>systems.py
import numpy as np
from abc import ABC, abstractmethod
class system(ABC):
def __init__(self):
super().__init__()
@abstractmethod
def __call__(self, x):
pass
@abstractmethod
def diff(self, x):
pass
@abstractmethod
def description(self):
... | StarcoderdataPython |
166118 | """Holonomic Functions and Differential Operators"""
from __future__ import print_function, division
from sympy import symbols, Symbol, diff, S, Dummy, Order, rf, meijerint
from sympy.printing import sstr
from .linearsolver import NewMatrix
from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOper... | StarcoderdataPython |
3209250 | """
used to manage notifications
""" | StarcoderdataPython |
3363419 | import os
import subprocess
import pytest
from git import Repo
from enguard.hooks import HOOKS, hooks_path, install_hook
from enguard.util import repo_path
from tests.util import hooks_ok, stage_tmp_file
@pytest.mark.experiments
def test_register_git_hooks(repo: Repo):
path = hooks_path(repo_path(repo))
fo... | StarcoderdataPython |
1702515 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 11:46:35 2020
@author: Nikki
"""
import numpy as np
import tensorflow as tf
#from tensorflow import keras
from core.config import cfg
from core import utils
import cv2
from PIL import Image
import sys
from threading import Thread
from queue import Queue
import time
... | StarcoderdataPython |
1621176 | """
This module defines redis storage for WindowManager's
"""
from redis.client import Redis
from throttled.models import Hit, Rate
from throttled.storage import BaseStorage
from throttled.storage._abstract import _HitsWindow, _WindowManager
from throttled.storage._duration import DUR_REGISTRY, DurationCalcType
from ... | StarcoderdataPython |
122506 | import random
num = random.randint(1,6)
print(num)
| StarcoderdataPython |
1610861 | <reponame>byteskeptical/sftpretty<filename>tests/test_open.py
'''test sftpretty.open'''
from common import VFS, conn
from sftpretty import Connection
def test_open_read(sftpserver):
'''test the open function'''
with sftpserver.serve_content(VFS):
with Connection(**conn(sftpserver)) as psftp:
... | StarcoderdataPython |
1628344 | from .neologd import (
Neologd,
)
from .config import (
Config,
)
from .tag_japanese import (
TagJapanese,
) | StarcoderdataPython |
77517 | default_app_config = 'gunmel.apps.GunmelConfig' | StarcoderdataPython |
3391722 | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Factories that create entities."""
# pylint: disable=too-many-arguments
# pylint: disable=invalid-name
# pylint: disable=redefined-builtin
import copy
import random
from lib.constants import element, obj... | StarcoderdataPython |
3249268 | <gh_stars>0
# -*- coding: utf-8 -*-
from datasets.mnist import load as load_mnist
from datasets.cifar10 import load as load_cifar10
from datasets.data_utils import make_one_hot_labels
| StarcoderdataPython |
11880 | <reponame>zeyuanxy/HackerRank
if __name__ == "__main__":
data = raw_input().strip(',\n').split(' ')
count = 0
total = 0
for pxl in data:
pxl = pxl.split(',')
mean = 0
for i in pxl:
mean += int(i)
mean /= 3
if mean < 70:
count += 1
t... | StarcoderdataPython |
4833639 | <reponame>igoradriano/manipulacao-dados-python-bd
print("Abrindo um arquivo")
try:
arquivo = open("teste.txt", "w")
print("Arquivo aberto")
arquivo.write("Conteúdo da primeira linha.")
except FileNotFoundError as erro:
print("Arquivo inexistente")
print("Descrição", erro)
except PermissionError as ... | StarcoderdataPython |
3233548 | from __future__ import print_function
import yaml
from lymph.cli.base import Command
class ConfigCommand(Command):
"""
Usage: lymph config [options]
Prints configuration for inspection
{COMMON_OPTIONS}
"""
short_description = 'Prints configuration for inspection'
def run(self):
... | StarcoderdataPython |
193871 | <reponame>g-braeunlich/imSim
from __future__ import print_function
import sys,os,glob,re
import platform
import ctypes
import ctypes.util
import types
import subprocess
import re
import tempfile
import urllib.request as urllib2
import tarfile
import shutil
import setuptools
from setuptools import setup, find_packages
... | StarcoderdataPython |
4830688 | <filename>src/modu/persist/variables.py
# modu
# Copyright (c) 2006-2010 <NAME>
# http://modu.bubblehouse.org
#
#
# See LICENSE for details
"""
Persistent variables.
Somewhat modeled after Drupal variable system, this is a way for modu
developers to easily save some persistent variables.
"""
try:
import cPickle as ... | StarcoderdataPython |
1623711 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-10-31 21:30
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('newsroom', '0027_auto_20161031_1742'),
]
operations = [
migr... | StarcoderdataPython |
36180 | """Tests for 'cloudflare-gh-pages-dns' hook."""
import contextlib
import io
import os
import pytest
from hooks.cf_gh_pages_dns_records import check_cloudflare_gh_pages_dns_records
@pytest.mark.skipif(
not os.environ.get("CF_API_KEY"),
reason=(
"Cloudflare user API key defined in 'CF_API_KEY' enviro... | StarcoderdataPython |
3298689 | import subprocess
import os
import sys
import re
from workflow import Workflow3
adb_path = os.getenv('adb_path')
serial = os.getenv('serial')
api = os.getenv('device_api')
ip = os.getenv("ip")
def wordMatch(arg, sentence):
words = arg.lower().split(" ")
sentenceComponents = sentence.lower().split(" ")
f... | StarcoderdataPython |
154704 | from datetime import date
# Exercise 012 - Military Enlistment
"""Make a program that reads a young person's year of birth and reports, according to their age,whether he is still going to enlist in the military,
whether it's the exact time to enlist or whether it's past the time of enlistment. Your program should al... | StarcoderdataPython |
143844 | #!/usr/bin/env python
from sense2vec import Sense2Vec
from sense2vec.util import split_key
from pathlib import Path
import plac
from wasabi import msg
import numpy
def _get_shape(file_):
"""Return a tuple with (number of entries, vector dimensions). Handle
both word2vec/FastText format, which has a header wit... | StarcoderdataPython |
1731744 | lista = list()
while True:
while True:
num = str(input('Digite um número inteiro:\t'))
v = 0
for n in num:
if n not in '0123456789':
v += 1
if v == 0:
num = int(num)
break
else:
print('\033[31mDigite apenas númer... | StarcoderdataPython |
3273669 | #!/usr/bin/env python
# coding: utf-8
# In[41]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
# In[12]:
... | StarcoderdataPython |
20646 | import asyncio
import time
import uvloop
import importlib
from pyrogram import Client as Bot, idle
from .config import API_ID, API_HASH, BOT_TOKEN, MONGO_DB_URI, SUDO_USERS, LOG_GROUP_ID
from Yukki import BOT_NAME, ASSNAME, app, chacha, aiohttpsession
from Yukki.YukkiUtilities.database.functions import clean_restart_st... | StarcoderdataPython |
3221655 | <gh_stars>1-10
import torch
from neurve.distance import distmfld, pdist_mfld, psim
def test_distmfld_disjoint():
""" Test that points that are not in a common chart have distance 1
"""
q1 = torch.tensor([[1], [0]])
q2 = torch.tensor([[0], [1]])
c1, c2 = [torch.rand(2, 1, 3) for _ in range(2)]
... | StarcoderdataPython |
3246518 | '''
Anaconda Cloud package utilities
'''
from __future__ import print_function
from binstar_client.utils import get_server_api, parse_specs
import logging
log = logging.getLogger('binstar.package')
def main(args):
aserver_api = get_server_api(args.token, args.site, args.log_level)
spec = args.spec
owner ... | StarcoderdataPython |
3389900 | import zipfile
import csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import sklearn
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.models import model_from_json
from keras.optimizers import Adam
from keras.layers.advanced_acti... | StarcoderdataPython |
1609861 | #!/usr/bin/env python
"""
ROS service server node for Rapidly-Exploring Random Trees (RRT's)
Author: <NAME>.
Copyright: Copyright (c) 2021, <NAME>.
License: BSD-3-Clause
Date: March 2021
"""
import rospy
from pp_msgs.srv import PathPlanningPlugin, PathPlanningPluginResponse
from geometry_msgs.msg import Twist
from tr... | StarcoderdataPython |
1712849 | GOLDEN_RATIO = (1 + 5 ** 0.5) / 2
operation = input(
"\n(1) - get the lower value\n(2) - get the higher value\n(3) - get the two values by total\n\nInsert the operation number: ")
if operation == "1":
higher = (int)(input("Higher value: "))
lower = (GOLDEN_RATIO * higher) - higher
print(f"Your lower ... | StarcoderdataPython |
3326363 | <reponame>CrazyXiao/learn-python<gh_stars>10-100
#!/usr/bin/python
# -*- coding: utf8 -*-
"""
author : menqi
desp: 爬取图片,仅供学习O(∩_∩)O
"""
import os
import requests
from requests.adapters import HTTPAdapter
from bs4 import BeautifulSoup
from lxml import etree
from multiprocessing import Process
import codecs
... | StarcoderdataPython |
3309712 | class RandomLocation(object):
"""A Random location in the world, with a name, rate of discovery, and path to an image"""
def __init__(self, name, rate, img_path, index):
self.name = name
self.rate = float(rate)
self.img_path = img_path
self.index = index
def __str__(self):
... | StarcoderdataPython |
30558 | <reponame>satta/TIE-Splunk-TA<gh_stars>1-10
# Copyright (c) 2017, 2020, DCSO GmbH
import json
import sys
import os
# we change the path so that this app can run within the Splunk environment
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib"))
from dcsotie.errors import TIEError
from dcsotiesplun... | StarcoderdataPython |
104608 | """empty message
Revision ID: 865b2e2d02ff
Revises: ('866611669529', 'cb391b878586')
Create Date: 2019-07-03 18:44:00.470730
"""
# revision identifiers, used by Alembic.
revision = '865b2e2d02ff'
down_revision = ('866611669529', 'cb391b878586')
from alembic import op
import sqlalchemy as sa
def upgrade():
pas... | StarcoderdataPython |
3301141 | <reponame>coblo/isccbench
# -*- coding: utf-8 -*-
from elasticsearch import Elasticsearch
es = Elasticsearch()
mapping_data = """
{
"mappings": {
"default": {
"dynamic": "strict",
"properties": {
"isbn": {
"type": "keyword",
"index": "true"
},
"title": {
... | StarcoderdataPython |
27446 | <gh_stars>1-10
#!/usr/bin/env python
import sys
import json
import argparse
class ArgParser(argparse.ArgumentParser):
"""
Argument parser that displays help on error
"""
def error(self, message):
sys.stderr.write("error: {}\n".format(message))
self.print_help()
sys.exit(2)
d... | StarcoderdataPython |
1710407 | from collections import OrderedDict
from pyhocon import ConfigFactory
from pyhocon.tool import HOCONConverter
def linear_scale_func(x, m=4, n=0):
return m*(x+1)+n
class WallyConfBuilder(object):
def __init__(self, pattern, parallelism, memory, scale_func=linear_scale_func):
self.pattern = pattern
... | StarcoderdataPython |
133607 | import logging
from django.conf import settings
from django.contrib import auth
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exe... | StarcoderdataPython |
3394994 | <reponame>Akiros001/platform-resource-manager<gh_stars>10-100
import pytest
from prm.resource import Resource, RDTResource
from prm.membw import MemoryBw
from wca.allocators import AllocationType
@pytest.fixture(scope="module")
def membw():
res = MemoryBw()
return res
def test_membw_budgeting(membw):
a... | StarcoderdataPython |
17370 | # -*- coding: utf-8 -*-
"""
Created on %(date)s
@author: %Christian
"""
"""
#BASE +BN层
#dropout改为0.15
"""
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddlenlp as ppnlp
class QuestionMatching_base(nn.Layer):
'''
base模型
dropout改为0.15
'''
de... | StarcoderdataPython |
1788907 | """
THIS SCRIPT COMPARES THE INDEX VALUES OF TWO YEARS AND CREATES A NUMBER OF OUTPUT
FIELDS:
1. A NUMERIC VALUE OF HOW MUCH THE INDEX CATEGORY SHIFTED, AND IN WHICH DIRECTION
2. A RECLASSIFIED NUMERIC VALUE OF POSITIVE CHANGE, NO CHANGE, OR NEGATIVE CHANGE
3. A STRING VALUE STATING WHICH CATEGORY TO WHI... | StarcoderdataPython |
4833198 | #!/usr/bin/python3
import sensor
sensor.Sensor("HUMI")
| StarcoderdataPython |
3255920 | <reponame>jwills/dbt-core
import pytest
from dbt.tests.util import run_dbt, get_manifest, write_file, write_config_file
dbt_project_yml = """
models:
test:
my_model:
+grants:
my_select: ["reporter", "bi"]
"""
append_schema_yml = """
version: 2
models:
- name: my_model
config:
grants:
... | StarcoderdataPython |
196550 | <reponame>akyboy9/PlexLandingPage
from flask import request, render_template, redirect, Flask, abort, request, session
from flask_login import LoginManager, UserMixin, login_required, login_user, logout_user
from plexapi.myplex import MyPlexAccount
from pushbullet import Pushbullet
from validation import verify_plex_ac... | StarcoderdataPython |
158140 | <filename>src/devices/esp32-test02/main.py
import test02
import prometheus.pgc as gc
import prometheus.server.multiserver
import prometheus.server.socketserver.udp
import prometheus.server.socketserver.tcp
import prometheus.server.socketserver.jsonrest
import prometheus.tftpd
import prometheus.logging as logging
gc.co... | StarcoderdataPython |
4834889 | from sagemaker_rl.coach_launcher import SageMakerCoachPresetLauncher
import tensorflow as tf
import shutil
class MyLauncher(SageMakerCoachPresetLauncher):
def default_preset_name(self):
"""This points to a .py file that configures everything about the RL job.
It can be overridden at runtime by spe... | StarcoderdataPython |
1764903 | # -*- coding: utf-8 -*-
"""
Recommended installs: pip install pytrends fredapi yfinance
Uses a number of live public data sources to construct an example production case.
Some ~100 lines are just pulling in data.
While stock price forecasting is shown here, time series forecasting alone is not a recommended basis for ... | StarcoderdataPython |
3373533 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import pdb, importlib, inspect, time, datetime, json
# from PyFin.api import advanceDateByCalendar
# from data.polymerize import DBPolymerize
from data.storage_engine import StorageEngine
import time
import pandas as pd
import numpy as np
from datetime import timedelta, datetime
... | StarcoderdataPython |
1679108 | #!/usr/bin/env python3
"""简单选择排序的改进——二元选择排序
简单选择排序,每趟循环只能确定一个元素排序后的定位。我们可以考虑改进为每趟循环确定两个元素(当前趟最大和最小记录)的位置,从而减少排序所需的循环次数。改进后对n个数据进行排序,最多只需进行[n/2]趟循环即可。
:author <NAME> <email><EMAIL> / <EMAIL></email>
:sine 2017/9/2
:version 1.0
"""
def select_key(arr, start, end):
"""
除首尾位置外,从剩余的元素中选出最小值,并返回其... | StarcoderdataPython |
179323 | import random
import torch
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.utils.data import RandomSampler, BatchSampler
from .utils import calculate_accuracy, Cutout, calculate_accuracy_by_labels, calculate_FP, calculate_FP_Max
from .newtrainer import Trainer... | StarcoderdataPython |
4842650 | <reponame>Evoiis/Robot-Follow-Ahead-with-Obstacle-Avoidance
from gym.envs.registration import register
register(
id='gazeborosAC-v0',
entry_point='gym_gazeboros_ac.envs.gym_gazeboros_ac:GazeborosEnv',
)
| StarcoderdataPython |
1622920 | <filename>main.py
from datetime import datetime as dt
from google.appengine.ext import ndb
from google.appengine.ext import deferred
from google.appengine.api import urlfetch
from flask import Flask, render_template, request, jsonify, abort
from flask_restplus import Resource, Api
from google.appengine.api import app... | StarcoderdataPython |
79547 | <filename>lib/training/schemes/tsp/svd.py
import tensorflow as tf
from tensorflow.keras import (optimizers, losses, metrics)
from tqdm import tqdm
import numpy as np
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import os
from lib.base.dotdict import HDict
from lib.data.datasets.t... | StarcoderdataPython |
3239702 | <gh_stars>0
import collections
import copy
import sys
from typing import Dict
#sorry this code is really terrible, i was working quickly
MAX_FLOOR = 3
class Item:
def __init__(self, id, isMicrochip):
self.id = id
self.isMicrochip = isMicrochip
class Node:
def __init__(self, personFloor... | StarcoderdataPython |
4810112 | import os
import zipfile
import click
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
from loss import dice_np, fmicro_np, score_np
TRUEDIR = 'data/training/truth/'
@click.command()
@click.option('-n', '--name', default='invalid9000', help='Model name')
@click.option('-m', '--mode', defaul... | StarcoderdataPython |
1607688 | <filename>python/aghast/aghast_generated/SystematicUnits.py
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: aghast_generated
class SystematicUnits(object):
syst_unspecified = 0
syst_confidence = 1
syst_sigmas = 2
| StarcoderdataPython |
1738880 | <reponame>SourceZh/Docklet
from webViews.view import normalView
from webViews.dockletrequest import dockletRequest
from flask import redirect, request, abort
class registerView(normalView):
template_path = 'register.html'
@classmethod
def post(self):
form = dict(request.form)
if (request.f... | StarcoderdataPython |
3290362 | <reponame>nickmoreton/wagtail-wordpress-import<gh_stars>10-100
import copy
import json
from datetime import datetime
from functools import cached_property
from xml.dom import pulldom
from bs4 import BeautifulSoup
from django.apps import apps
from django.conf import settings
from django.utils.module_loading import impo... | StarcoderdataPython |
3236933 | # xmlexportfile - Tests
from src import sfcparse
from os import remove, path
import time
import xml.etree.ElementTree as __xml_etree
test_file_path = './tests/test_files/xml/'
file_delay_timer = 0.5
################################################################
# TESTS
# 1. XML Data Export - Exporting xml file da... | StarcoderdataPython |
4804930 | <reponame>yebrinomar/ia-course
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import gym # cargamos la librería de OpenAI Gym
#'SpaceInvaders-v0'
environment = gym.make('MountainCar-v0') # Lanzamos una instancia del videojuego de la Montaña rusa
environment.reset() # Limpiamos y prepar... | StarcoderdataPython |
41931 | <reponame>ukayaj620/cp-solution<gh_stars>1-10
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isMirror(self, left: TreeNode, right: TreeNode) -> bool:
if left is None and right is None:
... | StarcoderdataPython |
154228 | #!/usr/bin/python3
"""
similarity_mapper2
"""
import sys
import pandas as pd
import numpy as np
big_data = pd.read_csv('ratings.csv')
all_films = np.unique(big_data.movieId)
for line in sys.stdin:
film, film_statistics = line.strip().split('\t', 1)
for f in all_films:
if int(film) < f:
... | StarcoderdataPython |
1630487 | import mtgcompiler.AST.core as core
import abc
from enum import Enum,auto
from num2words import num2words
class MgAbstractExpression(core.MgNode):
"""This is the parent class for all expressions such as power/toughness,
types, and mana costs. This class is not instantiated, but provides common
... | StarcoderdataPython |
136327 | <reponame>drecali/pymodi
import threading as th
from modi.task.exe_task import ExeTask
class ExeThrd(th.Thread):
"""
:param send_q: Inter-process queue for serial writing message
:param recv_q: Inter-process queue for receiving json message
:param dict() module_ids: dict() of module_id : ['timestamp'... | StarcoderdataPython |
1751078 | from typing import Dict
from pydantic import BaseModel
class ProductoInDB(BaseModel):
codigo: str
nombre: str
precio: float
cantidad: int
seccion:str
database_producto = {
"1001": ProductoInDB(**{"codigo": "1001",
"nombre": "Mause",
"... | StarcoderdataPython |
148092 | <filename>blambda/show.py<gh_stars>0
"""
List local functions
"""
from .utils.findfunc import find_all_manifests
from termcolor import colored
# don't delete, this is necessary for the argparsing logic
def setup_parser(parser):
pass
def run(args):
manifests = find_all_manifests(".", verbose=(args.verbose >... | StarcoderdataPython |
3396902 | # ckwg +28
# Copyright 2018 by Kitware, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditi... | StarcoderdataPython |
1683856 | import pyrebase
config = {
"apiKey": "<KEY>",
"authDomain": "projectpicle.firebaseio.com",
"databaseURL": "https://projectpicle.firebaseio.com/",
"storageBucket": "projectpicle.appspot.com"
}
firebase = pyrebase.initialize_app(config)
db = firebase.database()
#db.child("fridge_itmes").child("Tomato Ketchup")
... | StarcoderdataPython |
1674239 | <reponame>oliverwatts/snickery<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Project: ... - February 2017 - ...
## Contact: <NAME> - <EMAIL>
import sys
import os
import glob
import os
import fileinput
from argparse import ArgumentParser
import numpy as np
# modify import path to obtain module... | StarcoderdataPython |
3229821 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import fnmatch
import json
import numbers
import sys
import threading
import traceback
import _frida
class DeviceManager(object):
def __init__(self, impl):
self._impl = impl
def __repr__(self):
return repr(self.... | StarcoderdataPython |
1652559 | <gh_stars>10-100
from typing import Callable
import pp
from pp.components.coupler90 import coupler90
from pp.components.coupler_straight import coupler_straight
from pp.drc import assert_on_2nm_grid
from pp.component import Component
@pp.autoname
def coupler_ring(
coupler90: Callable = coupler90,
coupler: Cal... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.