id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
3588631
from dataclasses import dataclass from typing import List, Optional, Dict @dataclass class Japanese: word: Optional[str] = None reading: Optional[str] = None @dataclass class Link: text: str url: str @dataclass class Source: language: str word: str @dataclass class Sense: english_def...
StarcoderdataPython
11208347
<reponame>HHC0209/student_recognition_system from PIL import Image import os # 将所有照片保存为450*800的缩略图 # (仅需在放入所有图片后运行一次) class PictureResizer: def __init__(self, path): self.path = path self.all_folder = [] def load_all_photo(self): folders = os.listdir(self.path) for folder in fo...
StarcoderdataPython
86889
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from typing import NoReturn import signal import sys import os from dotenv import load_dotenv, find_dotenv from psycopg.rows import dict_row import psycopg load_dotenv(find_dotenv('.env.sample')) # If `.env` exists, let it override the sample env file. load_dotenv(overr...
StarcoderdataPython
335674
import progeny class Base(progeny.Base): pass class Alpha(Base): pass class Bravo(Alpha): @classmethod def _get_progeny_key(cls): return '={}='.format(cls.__name__) class Charlie(Bravo): __progeny_key__ = 'charlie' class Delta(Charlie): pass def test_progeny(): assert Bas...
StarcoderdataPython
193132
# coding=utf-8 """Main bot file""" import aiohttp import time from collections import Counter, deque from pathlib import Path import discord from discord.ext import commands from pyppeteer import launch, errors from bot.utils.logging import setup_logger from bot.utils.over import send, _default_help_command discord...
StarcoderdataPython
1823542
import pytest from flask import Flask from werkzeug.security import check_password_hash from app.models import User, db, CountdownResult, get_db_column, Cite from app.tools.auth import _check_token from tests.conftest import test_user_email def test_new_user(user, app: Flask): """Testing new user creation""" ...
StarcoderdataPython
3443278
# -*- coding: utf-8 -*- """ @navrajnarula https://machinelearningmastery.com/persistence-time-series-forecasting-with-python/ """ import pandas from pandas import read_csv from pandas import datetime from matplotlib import pyplot from pandas import DataFrame #def parser(x): # return datetime.strptime('190'+x, '%Y-%...
StarcoderdataPython
8010493
<gh_stars>0 """Asynchronous client for the PVOutput API."""
StarcoderdataPython
3394026
import email, email.message import os """ 将 mht 文件转化为 html 文件 """ def convert(filename): mht = open(filename, "rb") print("转化中...\n") a = email.message_from_bytes(mht.read()) parts = a.get_payload() if not type(parts) is list: parts = [a] for p in parts: if not os.path.exis...
StarcoderdataPython
9611726
<gh_stars>0 def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Education, obj[4]: Occupation, obj[5]: Bar, obj[6]: Restaurant20to50, obj[7]: Direction_same, obj[8]: Distance # {"feature": "Coupon", "instances": 8147, "metric_value": 0.9848, "depth": 1} if obj[2]>1: # {"feature": "Dista...
StarcoderdataPython
8025973
<reponame>Altyrost/poediscordbot # http://poeurl.com/api/?shrink={%22url%22:%22https://www.pathofexile.com/passive-skill-tree/AAAABAMBAHpwm6FR-zeDAx7quvfX0PW2-o5kpys3ZsMJ62PviLmT8h3v66EvGyUfQR1PDkiMNkuutUjbXq6zBUJJUZEHQnrsGNfPlS6-iocTf8ZFfjQKDXxfalgHj0ZwUvrSjun3wVF0b57G93gvOw3B86aZES-TJx0UzRYBb9-K0NBGcRhq8NUXL21sgKSQ1h...
StarcoderdataPython
24909
<reponame>jim-bo/silp2<gh_stars>1-10 #!/usr/bin/python ''' creates bundle graph from filtered multigraph ''' ### imports ### import sys import os import logging import networkx as nx import numpy as np import scipy.stats as stats import cPickle import helpers.io as io import helpers.misc as misc ### definitions ###...
StarcoderdataPython
3339258
<reponame>karlwnw/adventofcode2019 import unittest from day12 import run class TestDay12(unittest.TestCase): def test_examples(self): moons = [(-1, 0, 2), (2, -10, -7), (4, -8, 8), (3, 5, -1)] self.assertEqual(run(moons, 10), 179) moons = [(-8, -10, 0), (5, 5, 10), (2, -7, 3), (9, -8, -3...
StarcoderdataPython
3550038
from solver import Solver from run_solver import get_prolog_file_info, get_tile_ids_dictionary from trial import TRIAL_CONFIG_FORMATS import utils import os import argparse def main(trial, levels, num_sol, asp, state_graph): if not (asp or state_graph): utils.error_exit("Must specify at least one valida...
StarcoderdataPython
1711109
<reponame>mvadari/xrpl-py-interview """Top-level exports for the wallet generation package.""" from xrpl.asyncio.wallet import XRPLFaucetException from xrpl.wallet.main import Wallet from xrpl.wallet.wallet_generation import generate_faucet_wallet __all__ = ["Wallet", "generate_faucet_wallet", "XRPLFaucetException"]
StarcoderdataPython
3469055
from datetime import datetime from enum import Enum ChangeType = Enum('ChangeType', 'block tile_entity entity status') def getType(value): if value == 'status': return ChangeType.status elif value == 'BLOCK': return ChangeType.block elif value.startswith('TILE_ENTITY'): return Chang...
StarcoderdataPython
1899270
<reponame>AstraZeneca/jazzy<gh_stars>0 """Test cases for the visualisations methods.""" import base64 import numpy as np import pytest from rdkit import Chem from jazzy.core import calculate_polar_strength_map from jazzy.core import get_charges_from_kallisto_molecule from jazzy.core import get_covalent_atom_idxs from...
StarcoderdataPython
5063595
# -*- coding: utf-8 -*- """ Highcharts Demos Spiderweb: http://www.highcharts.com/demo/polar-spider """ from highcharts import Highchart H = Highchart(width=550, height=400) options = { 'chart': { 'polar': True, 'type': 'line', 'renderTo': 'test' }, 'title': { 'text': 'Bud...
StarcoderdataPython
353514
import torch from sklearn.metrics import classification_report, confusion_matrix, accuracy_score import logging logging.basicConfig(level=logging.INFO) """ Script for evaluating the neural network on test set """ def evaluate_test_set(model, data, data_loader, device): """ Evaluates the model performance on t...
StarcoderdataPython
157307
<gh_stars>10-100 import torch from torch import nn from torch.utils.data import DataLoader import argparse import numpy as np import datetime import os import json from types import SimpleNamespace from datasets import MiniImagenetHorizontal from res12 import resnet12 from res10 import res10 from models import conv64...
StarcoderdataPython
6573615
#modules-and-pip
StarcoderdataPython
6406162
n = int(input()) hash = dict() for t in range(n): arr = input().split() x = arr[0] y = arr[1:] hash[x] = y name = input() val = hash[name] sum = 0.0 for x in val: sum += float(x) print("{0:.2f}".format(sum/3))
StarcoderdataPython
8082820
<gh_stars>1-10 """ """ import numpy as np __all__ = ["bazin09", "karpenka12", "firth17", "bazin09_listarg", "karpenka12_listarg", "firth17_listarg", "_defined_models"] _defined_models = ["bazin09", "karpenka12", "firth17"] def bazin09(x, a, t_0, t_rise, t_fall): return a * np.exp(-(x - ...
StarcoderdataPython
28434
<gh_stars>0 # # Copyright (c) 2013 Docker, Inc. # 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 # # U...
StarcoderdataPython
8191866
from model import * class ArticleService: def find_all_articles(self): articles = Article.query.filter_by(hidden=0).all() return articles def find_by_subject(self, subject): articles = Article.query.filter_by(hidden=0).filter_by( subject=subject).order_by(Article.date.desc...
StarcoderdataPython
5049436
<reponame>francisar/rds_manager<filename>aliyun/api/rest/Rds20140815ModifyDBInstanceSpecRequest.py ''' Created by auto_sdk on 2015.06.23 ''' from aliyun.api.base import RestApi class Rds20140815ModifyDBInstanceSpecRequest(RestApi): def __init__(self,domain='rds.aliyuncs.com',port=80): RestApi.__init__(self,domain, p...
StarcoderdataPython
4992573
import scrapy class BloombergSpider(scrapy.Spider): name = 'bloomberg' start_urls = [ 'http://www.bloomberg.com/quote/AAPL:US', 'http://www.bloomberg.com/quote/GOOGL:US', 'http://www.bloomberg.com/quote/AMZN:US', ] def parse(self, response): for sel in response.css('met...
StarcoderdataPython
3502079
<reponame>mikepm35/estatusboard<filename>app/views.py from flask import render_template, jsonify from app import application import urllib2, json from os import listdir from os.path import isfile, join import config @application.route('/') @application.route('/index') def index(): imgpath = 'app/static/img/' i...
StarcoderdataPython
3245273
<reponame>reanimat0r/isf<gh_stars>100-1000 __author__ = 'fwkz'
StarcoderdataPython
3571473
<filename>lib/rram_NN/test.py # file: test.py # Author : <NAME> # Date : 05/11/2017 # Project : RRAM training NN import tensorflow as tf import numpy as np import random import matplotlib.pyplot as plt from rram_NN.config import cfg from rram_NN.rram_modeling import addDefects def eval_net(network, dataset, weights)...
StarcoderdataPython
8070372
<reponame>BennettDixon/holbertonschool-higher_level_programming #!/usr/bin/python3 class BaseGeometry(): """for use with shapes. Super class. """ def area(self): """instance method to calculate area of shape """ raise Exception("area() is not implemented") def integer_validat...
StarcoderdataPython
6534205
<reponame>lqill/PlatKendaraan import pygame import pygame.freetype import pygame.sprite import pygame.image import pygame.font import pygame.time import pygame.event import pygame.display import pygame_gui from pygame_gui.elements import UIButton from pygame_gui.windows import UIFileDialog from component import Plat, ...
StarcoderdataPython
1925602
<gh_stars>1-10 import numpy as np import pandas as pd import py2neo import sys from scipy import sparse # connect to the database if __name__ == "__main__": outputfile = sys.argv[1] username = "neo4j" password = "<PASSWORD>" uri = "bolt://127.0.0.1:7687" graph = py2neo.Graph(bolt=True, host="loca...
StarcoderdataPython
3548770
<gh_stars>0 import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import griddata as intGrid from random import randint class Particle: def __init__(self,position,isdead=False): self.XY = np.array(position) self.isDed = isdead return None def whereami(self): ...
StarcoderdataPython
8143320
<reponame>thejerrytan/CarND-Behavioural-Cloning-P3 import csv import cv2 import numpy as np import os import sklearn from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # Use this to train track2 TRAINING_DIR = "harder_data" # Use this to train track1 # TRAINING_DIR = "data" # Model f...
StarcoderdataPython
88824
<gh_stars>1-10 import copy from urllib.parse import quote_plus from cryptojwt import KeyJar from cryptojwt.key_jar import init_key_jar from idpyoidc.impexp import ImpExp def add_issuer(conf, issuer): res = {} for key, val in conf.items(): if key == "abstract_storage_cls": res[key] = val ...
StarcoderdataPython
12858165
<reponame>turing4ever/illustrated-python-3-course # place super_test.py code here # place keyword_test.py code here
StarcoderdataPython
178977
#!/usr/bin/python3 from zoo.serving.server import ClusterServing serving = ClusterServing() print("Cluster Serving has been properly set up.")
StarcoderdataPython
11386131
'''---------------------------------------------------------------------------------- Tool Name: WriteFeaturesFromTextFile Source Name: WriteFeaturesFromTextFile.py Version: ArcGIS 9.1 Author: Environmental Systems Research Institute Inc. Required Argumuments: An input feature class ...
StarcoderdataPython
1863623
from panda import Panda panda = Panda() panda.set_safety_mode(Panda.SAFETY_ELM327) panda.can_clear(0) print(panda.can_recv()) global kmsgs while 1: kmsgs = panda.can_recv() nmsgs = [] #print(kmsgs) for i in range(len(kmsgs)): if kmsgs[i][0] == 1042: print(kmsgs[i]) kmsgs = nmsgs[-256:]
StarcoderdataPython
1971970
# -*- coding: utf-8 -*- # Future work
StarcoderdataPython
140078
<filename>core-python/Core_Python/exception/ExceptionMethods.py ''' e. and use all methods ''' ''' also try different exception like java file,array,string,numberformat ''' ''' user define exception ''' try: raise Exception('spam,','eggs') except Exception as inst: print("Type of instance : ",type(inst)) # the...
StarcoderdataPython
208128
"""create DOEs and execute design workflow Caution: This module requires fa_pytuils and delismm! Please contatct the developers for these additional packages. """ import os from collections import OrderedDict import datetime import numpy as np import matplotlib.pyplot as plt from delismm.model.doe import LatinizedCe...
StarcoderdataPython
9799982
from os import path from setuptools import setup, find_packages from qmap import __version__ directory = path.dirname(path.abspath(__file__)) with open(path.join(directory, 'requirements.txt')) as f: required = f.read().splitlines() # Get the long description from the README file with open(path.join(directory, '...
StarcoderdataPython
89347
from __future__ import print_function import os import sys from distutils.core import setup, Extension # Need an 'open' function that supports the 'encoding' argument: if sys.version_info[0] < 3: from codecs import open ## Command-line argument parsing # --with-zlib: use zlib for compressing and decompressing # ...
StarcoderdataPython
4957781
<gh_stars>0 # -*- coding: utf-8 -*- # Copyright (c) 2021 The HERA Collaboration # Licensed under the MIT License """Utilities for comparing k-space covered by different surveys.""" import numpy as np import matplotlib.pyplot as plt from astropy import constants as const from matplotlib.patches import Rectangle from a...
StarcoderdataPython
1890792
from django.urls import path from . import views urlpatterns = [ path('', views.index), path('index.html', views.index), path('about.html', views.about), path('search.html', views.search), path('results.html', views.results), path('login.html', views.login), path('signup.html', views.signup...
StarcoderdataPython
4852849
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module that provides the API entrypoint for the py2log python package. """ import logging.config import sys try: import colorlog except ImportError: colorlog = False TRACE = 5 def configure(config=None, filepath=None, force=True, level=None, name=None): ...
StarcoderdataPython
3476913
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import logging import os from builtins import object, str import mock from pants.binari...
StarcoderdataPython
9708489
from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.text import Truncator from django.utils.translation import ugettext_lazy as _ from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from...
StarcoderdataPython
224785
<gh_stars>1-10 print('\033[33m-=-\033[m' * 20) print('\033[33m************* Fatorial *************\033[m') print('\033[33m-=-\033[m' * 20) v = float(input('Insira um valor: ')) c = 1 f = 1 while c <= v: f = f * c c += 1 print('O fatorial de {} é {}' .format(v, f))
StarcoderdataPython
287404
# Copyright (c) 2020 Foundries.io # SPDX-License-Identifier: Apache-2.0 import yaml import os from helpers import status def normalize_keyvals(params: dict, prefix=''): """Handles two types of docker-app params: 1) traditional. eg: key: val returns data as is 2) docker app nest...
StarcoderdataPython
5040007
import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent)) from config import ANALYSIS as cfg import analysis.utils as utils import portion as P import pickle import os from analysis.transcript_parsing import parse def seg_invalid(row): """ This functions specifies what makes a se...
StarcoderdataPython
162667
from entityfx.string_manipulation_base import StringManipulationBase class StringManipulation(StringManipulationBase): def benchImplementation(self) -> str: str0_ = "the quick brown fox jumps over the lazy dog" str1 = "" i = 0 while i < self._iterrations: str1 = St...
StarcoderdataPython
203774
#!/usr/bin/env python3 # # tmp_multi_cluster.py # # This source file is part of the FoundationDB open source project # # Copyright 2013-2018 Apple Inc. and the FoundationDB project authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
StarcoderdataPython
3218172
<filename>universalmutator/java_handler.py import os import subprocess import shutil def handler(tmpMutantName, mutant, sourceFile, uniqueMutants): backupName = sourceFile + ".um.backup." + str(os.getpid()) classFile = sourceFile.replace(".java", ".class") classBackupName = classFile + ".um.backup" + str(...
StarcoderdataPython
1699493
<reponame>jamhocken/aoc-2021 import regex as re import collections def process_input(file_contents): lines_stripped = [line.strip() for line in file_contents] scanners = dict() scanner_pattern = re.compile("(\d+)") beacon_pattern = re.compile("(-?\d+),(-?\d+),(-?\d+)") for line in lines_stripp...
StarcoderdataPython
3231599
from flask import Flask from config import Config from flask_bootstrap import Bootstrap from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config.from_object(Config) bootstrap = Bootstrap(app) db = SQLAlchemy(app) migrate = Migrate(app, db) from app import routes, mode...
StarcoderdataPython
4934516
import requests from bs4 import BeautifulSoup filename = "keyword.txt" headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64"} def create_soup(url) : res = requests.get(url, headers=headers) res.raise_for_st...
StarcoderdataPython
9771585
<filename>vroombaby/middleware.py class MyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response['X-My-Header'] = "my value" return response
StarcoderdataPython
4822055
<reponame>PasaLab/SparkDQ class A: def __str__(self): return "hhhhh" if __name__ == "__main__": a = A() i = 0 while i < 3 - 1: print(i) i += 1
StarcoderdataPython
5138635
import ngram import random import json class MarkovBot(object): def __init__(self, gramstores=None): if gramstores is None: self.gramstores = [] else: self.gramstores = gramstores def add_gramstore(self, gramstore): self.gramstores.append(gramstore) def _...
StarcoderdataPython
250452
<filename>AIMachine.py from StateMachine import TRANSITIONS from transitions.core import State EVALUATING_POLICY = "evaluating_policy" SEARCHING = "searching" VALUATION = "valuation" IDLE = "idle" STATES = [ State(IDLE), State(EVALUATING_POLICY), State(SEARCHING), State(VALUATION) ] # Triggers VALUE_...
StarcoderdataPython
11356468
<gh_stars>0 import socket, time if __name__ == "__main__": try: serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind(('', 50000)) print('listening') serversocket.listen(5) while 1: (clientsocket, address) = serversocket.accept() ...
StarcoderdataPython
4969523
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals from os import walk from os import sep from functools import partial def fullpath(root, dirpath, fname): if dirpath[len(dirpath) - 1] != sep: dirpath += sep if root[len(root) - 1] != sep: root += sep su...
StarcoderdataPython
6630169
import torch import torch.nn as nn import math import numpy as np class MultivarMLP(nn.Module): def __init__(self, input_dims, hidden_dims, output_dims, extra_dims, actfn, pre_layers=None): """ Module for stacking N neural networks in parallel for more efficient evaluation. In the context ...
StarcoderdataPython
6481354
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RAffyilm(RPackage): """affyILM is a preprocessing tool which estimates gene expression...
StarcoderdataPython
3332958
<gh_stars>0 # First step import cv2 filename = '../../video_for_training/validation.txt' with open(filename) as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] array = [] listImage = [] # print(content) for elem...
StarcoderdataPython
3531909
from functools import partial import aiometer from app import models, schemas from app.factories.dns_record import DnsRecordFactory from app.services.whois import Whois class DomainFactory: @staticmethod async def from_hostname(hostname: str) -> schemas.Domain: tasks = [ partial(Whois.lo...
StarcoderdataPython
11283673
from .MCP3008 import MCP3008
StarcoderdataPython
368707
#!/bin/python import sys assert len(sys.argv) > 1 f = open(sys.argv[1], "r") prefix = sys.argv[1] rTimes = list() #print(prefix + ",benchmark,solve mem,solve time,drat kb,drat sec,lrat kb,lrat sec,restarts,decisions,conflicts,propagations,mark proof sec,dump lrat sec, ana sec, anamem mb") for l in f: data ...
StarcoderdataPython
6583252
<filename>Models/Resnet34V2.py # from google.colab import drive # drive.mount('/content/drive/') from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf import numpy as np import pathlib import os import cv2 as cv import pydotplus from tensorflow.python.keras import...
StarcoderdataPython
11263258
<filename>examples/003_pandapower_modelexchange/pandapower/7EFC7D_pandapower.py from pymodelica import compile_fmu fmu_name = compile_fmu("pandapower", "pandapower.mo",compiler_log_level="d", version="2.0", target="me", compiler_options={'extra_lib_dirs':["C:\\Users\\DRRC\...
StarcoderdataPython
5148079
# coding=utf-8 # Copyright 2021 The Trax Authors. # # 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 a...
StarcoderdataPython
6583112
#/*********************************************************************** # * Licensed Materials - Property of IBM # * # * IBM SPSS Products: Statistics Common # * # * (C) Copyright IBM Corp. 1989, 2020 # * # * US Government Users Restricted Rights - Use, duplication or disclosure # * restricted by GSA ADP Schedule Co...
StarcoderdataPython
1876457
<filename>api/core/middleware/tests/test_cache_control.py from core.middleware.cache_control import NeverCacheMiddleware from django.http import HttpResponse def test_NoCacheMiddleware_adds_cache_control_headers(mocker): # Given a_response = HttpResponse() mocked_get_response = mocker.MagicMock(return_val...
StarcoderdataPython
1648175
""" run.py (batch_geocode) ====================== Geocode any row-delimited json data, with columns corresponding to a city/town/etc and country. """ import logging import os import pandas as pd import s3fs # not called but required import to read from s3:// from nesta.packages.geo_utils.country_iso_code import co...
StarcoderdataPython
1607805
<reponame>insequor/webpy-graphql from .utils import props from inspect import isclass class InitSubclassMeta(type): def __init__(self, classname, baseclasses, attrs): _Meta = getattr(self, "GraphQLMeta", None) _meta_props = {} if _Meta: if isinstance(_Meta, dict): ...
StarcoderdataPython
3390242
<reponame>linksapprentice1/dys # -*- coding: utf-8 -*- from Tkinter import * from tkFileDialog import * def printGameTable(days, left_or_right): print """<table class=\"tableizer-table\" style=\"float:""" + left_or_right +"""\"> <tbody> <tr class=\"tableizer-firstrow\"> <th>DAY</th> <th>DATE</th> <th>&...
StarcoderdataPython
4887657
<reponame>AntoineGagne/ulaval-notify """This module contains the code related to the session handling. :copyright: (c) 2018 by <NAME>. :license: MIT, see LICENSE for more details. """ from collections import namedtuple from copy import copy from threading import Lock, Timer from requests import Request from .consta...
StarcoderdataPython
1939929
<gh_stars>1-10 from typing import Union import numpy as np import talib from jesse.indicators.ma import ma from jesse.helpers import get_candle_source, same_length from jesse.helpers import slice_candles from jesse.indicators.mean_ad import mean_ad from jesse.indicators.median_ad import median_ad def rvi(candles: np...
StarcoderdataPython
4807788
<filename>pyrobolearn/control/dp.py<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- # This file describes the Dynamic Programming algorithm class DP(object): r"""Dynamic Programming (DP) Type: model-based "Dynamic programming usually refers to simplifying a decision by breaking it down into ...
StarcoderdataPython
139775
<filename>python/testData/inspections/PyProtectedMemberInspection/namedTuple.py from collections import namedtuple i = namedtuple('Point', ['x', 'y'], verbose=True) i._replace( **{"a":"a"})
StarcoderdataPython
3451182
<filename>PUG/Demo 1/main.py<gh_stars>100-1000 from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.uix.image import Image from kivy.animation import Animation class DemoApp(App): """ The App class is a singleton and creates the base of your applic...
StarcoderdataPython
178570
import torch from IPython.core.display import display from torch import Tensor from torch.nn import DataParallel # noinspection PyProtectedMember from torch.utils.data import DataLoader from datasets.deep_fashion import ICRBDataset, ICRBCrossPoseDataloader from modules.pgpg import PGPG from train_setup import args, ru...
StarcoderdataPython
243454
# %% from tensorflow import keras import numpy as np import cv2 import os IMG_SIZE = 50 DATASETDIR = 'D:\\Dataset\\test\\Dog' def imgPrepera(path): img_array = cv2.imread(os.path.join(DATASETDIR, path)) img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB) img_array = cv2.resize(img_array, (IMG_SIZE, IM...
StarcoderdataPython
6634685
<filename>ppmessage/__init__.py from . import backend """ version format, MAIN.SUB.HOTFIX.DEV 1.0.0.0: Initial to SaaS for ppmessage.cn 2.0.0.0: Github to SaaS for ppmessage.com 2.0.0.1: PPCom send<->recv with PPKefu 3.0.0.0: one main to start all ppmessage components """ __version__ = "3.0.0.0"
StarcoderdataPython
111582
new_model = tf.keras.models.load_model('my_first_model.h5') cap = cv2.VideoCapture(0) faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') while 1: # get a frame ret, frame = cap.read() # show a frame gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) fac...
StarcoderdataPython
1932912
''' Find Cycle in the List. ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: hare = head turtle = head while(turtle and ...
StarcoderdataPython
6595200
from itertools import product from oop import Customer, Shop from oop import ProductStock from oop import Basket shop = Shop('stock.csv') rich_customer_order=Customer('customer.csv') rich_customer_order.calculate_costs(shop.stock) customer_poor=Customer('OutOfBudget.csv') shop.shop_info() shop.shop_cash(...
StarcoderdataPython
9704954
<filename>pyluna-core/tests/luna/api/radiologyPreprocessingLibrary/test_app.py import pytest from minio import Minio import pyarrow.parquet as pq from luna.api.radiologyPreprocessingLibrary import app @pytest.fixture def client(): # setup flask api client for testing app.app.config["OBJECT_URI"] = "mockuri:1...
StarcoderdataPython
6525882
<gh_stars>0 from flask_restx import Namespace, fields class AuthDto: api = Namespace("Authentication", description="Authenticate and receive tokens.") user_obj = api.model( "User object", { "id": fields.String, "first_name": fields.String, "last_name": fiel...
StarcoderdataPython
12829056
<gh_stars>0 import discord import os import json import numpy as np import reddit_functions as rf import billboard_functions as bf import st import activities as act with open("keys.json") as f: info = json.load(f) headers = ['Task', 'Start', 'End'] todolist = np.empty(shape=[0,3]) client = discord.Client() @...
StarcoderdataPython
254260
from segmenter.models.FoldWeightFinder import FoldWeightFinder import os class OrganizedFoldWeightFinder(FoldWeightFinder): def __init__(self, directory): self.directory = os.path.join(directory, "results", "weights") fold_weights = [ os.path.join(self.directory, d) for d in os.listdir...
StarcoderdataPython
248099
import sys if sys.version[0]=="3": raw_input=input
StarcoderdataPython
9748376
class NeuralNet(): def __init__(self, game): pass def train(self, examples): pass def predict(self, board): pass def save_checkpoint(self, folder, filename): pass def load_checkpoint(self, folder, filename): pass
StarcoderdataPython
299515
class Producto: def __init__(self, nombre, descripcion, precio, stock, codigo): self.nombre = nombre self.descripcion = descripcion self.precio = precio self.stock = stock self.codigo = codigo
StarcoderdataPython
9643915
<reponame>Dimwest/jsonymize<gh_stars>0 import pyspark from configparser import ConfigParser from pathlib import Path from src.spark import df_join, get_source_ids, anonymize_df, show_examples from pyspark.sql.functions import input_file_name if __name__ == '__main__': # Parse config cfg = ConfigParser() ...
StarcoderdataPython
291457
<filename>adc_tmp36.py import spidev, time spi = spidev.SpiDev() spi.open(0,0) def analog_read(channel): r = spi.xfer2([1, (8 + channel) << 4, 0]) adc_out = ((r[1]&3) << 8) + r[2] return adc_out while True: reading = analog_read(0) voltage = reading * 3.3 / 1024 temp_c = voltage * 100 - 50 ...
StarcoderdataPython
3576622
import hyperchamber as hc from hyperchamber import Config from hypergan.ops import TensorflowOps from hypergan.gan_component import ValidationException, GANComponent import os import hypergan as hg import tensorflow as tf class BaseGAN(GANComponent): def __init__(self, config=None, inputs=None, device='/gpu:0', o...
StarcoderdataPython