id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
181991 | URL_CONFIG ="www.python.org"
DEFAULT_VALUE = 1
DEFAULT_CONSTANT = 0
| StarcoderdataPython |
1795127 | <gh_stars>0
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import transaction
from core.models import Raised, Campaing
class Command(BaseCommand):
help = 'create raised'
def success(self, message):
return self.stdout.write(
... | StarcoderdataPython |
3355239 | # Script Name : USBackup_.py
# Author : <NAME>
# Created : 25.11.2015
# Version : 1.0
# Description : Simple Removable Drive Backup program with python
import os
import platform
import win32com.client
import getpass
import threading
import time
import win32file
allready_plugged=[]
def USBackup_Startup(... | StarcoderdataPython |
3381221 | <reponame>isLinXu/DatasetMarkerTool
import os
import xml.etree.cElementTree as et
import cv2
import numpy as np
if __name__ == "__main__":
path = "./images/"
for file in os.listdir(path):
if ".jpg" in file:# 过滤 xml 文件
path_img = path + file # 图片路径
path_xml = path_img.replace... | StarcoderdataPython |
195878 | <reponame>movingpictures83/CSVUpperTriangular
class CSVUpperTriangularPlugin:
def input(self, filename):
infile = open(filename, 'r')
self.colnames = infile.readline().strip().split(',') # Assume rownames=colnames
self.ADJ = []
for line in infile:
self.ADJ.append(line.strip().... | StarcoderdataPython |
91949 | n1 = int(input('Um valor: '))
n2 = int(input('Outro valor: '))
soma = n1+n2
produto = n1*n2
quociente = n1/n2
resto = n1%n2
div_exata = n1//n2
potencia = n1**n2
print('A soma é {} \nO produto é {} \nO quociente é {} \nO resto é {} \nA divisão exata é {} \nA potência é {}'
.format(soma, produto, quoci... | StarcoderdataPython |
1762474 | <reponame>davmz/PythonProjects
"""
Name: <NAME>
Reason: Random Password Generator
Created: July 17, 2021
Updated: July 17, 2021
"""
import os
clear = lambda: os.system("cls")
import time
import string
import random
## Program
def main():
clear()
print("Welcome to Password Generator!!")
print("Please ente... | StarcoderdataPython |
1600192 | from selenium import webdriver
from selenium.webdriver.common.by import By
from utilities.handy_wrappers import HandyWrappers
import time
class DynamicXPathFormat():
def test(self):
baseUrl = "https://letskodeit.teachable.com"
driver = webdriver.Firefox()
driver.maximize_window()
... | StarcoderdataPython |
3267358 | f = open("mess.txt", 'r')
mess = f.read()
def ispal(s):
a = []
for i in range(0, len(s)):
a.append(s[-i-1])
t = ''.join(a)
if t == s:
return 1
return 0
pal = []
for i in range(0, len(mess) - 4):
if ispal(mess[i:i+5]):
pal.append(mess[i:i+5])
res = []
for p in pal:
... | StarcoderdataPython |
39970 | from django.contrib import admin
from .models import Payload
class PayloadAdmin(admin.ModelAdmin):
list_display = ('method', 'path','get','post')
search_fields = ('get','post')
admin.site.register(Payload, PayloadAdmin) | StarcoderdataPython |
118445 | import sys
import argparse
import numpy as np
from .. import zemax, trains, sdb, _utility, agf
from otk.rt2 import rt2_scalar_qt as rt2
def view_zmx():
parser = argparse.ArgumentParser(
description='Load and view a Zemax lens. Glass catalogs are obtained the directory zemax_glass_catalog_dir'
... | StarcoderdataPython |
3341327 | <filename>sort_list_without_sort_method.py
# A = [0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0]
# for i in range(len(A)):
# for j in range(len(A) - 1):
# if A[j] > A[j + 1]:
# A[j + 1], A[j] = A[j], A[j + 1]
# print(A)
A = [0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0]
i, j = 0, len(A) - 1
while i... | StarcoderdataPython |
74890 | # http://pastie.org/pastes/10943132/text
# Copyright (c) 2016 1wd
#
# 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, modi... | StarcoderdataPython |
92815 | S = input()
is_no = False
for s in S:
if S.count(s) != 2:
is_no = True
break
if is_no:
print("No")
else:
print("Yes")
| StarcoderdataPython |
166140 | <filename>proj/model/base_model.py
import tensorflow as tf
import numpy as np
from logger.Logger import getLoggerV3
import os
from evaluate.metric import cross_validate
from excelutil.output2excel import read_excel,outpu2excel
class BaseModel():
def __init__(self,sess,args):
self.sess=sess
self.arg... | StarcoderdataPython |
851 | <reponame>Rahmatullina/FinalYearProject<filename>EmoPy/EmoPy/examples/convolutional_dropout_model.py
from EmoPy.src.fermodel import FERModel
from EmoPy.src.directory_data_loader import DirectoryDataLoader
from EmoPy.src.csv_data_loader import CSVDataLoader
from EmoPy.src.data_generator import DataGenerator
from EmoPy.s... | StarcoderdataPython |
3232997 | import numpy as np
from gym.envs.mujoco import HalfCheetahEnv, HopperEnv
class HalfCheetahWrapper(HalfCheetahEnv):
"""HalfCheetah Wrapper that wraps Mujoco Halfcheetah-v2 env
with an additional defined reward function for model-based RL.
This is currently used for MBMPO.
"""
def __init__(self, *... | StarcoderdataPython |
176495 | """List all the extensions."""
names = [
"tourney",
"season",
"refresh",
"misc",
]
| StarcoderdataPython |
3340732 | """The Python interface to FINUFFT is divided into two parts: the simple
interface (through the ``nufft*`` functions) and the more advanced plan
interface (through the ``Plan`` class). The former allows the user to perform
an NUFFT in a single call while the latter allows for more efficient reuse of
resources when the ... | StarcoderdataPython |
4813087 | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.settings import settings
engine = create_engine(settings.sqlalchemy_url, connect_args={'check_same_thread': False}, future=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine, future=True)
| StarcoderdataPython |
90121 | from __future__ import print_function
path = '/network/aopp/cirrus/pred/kloewer/swm_bf_cntrl/data/'
dpath = '/network/aopp/cirrus/pred/kloewer/swm_back_ronew/'
outpath = '/network/home/aopp/kloewer/swm/paperplot/'
import os; os.chdir(path) # change working directory
import numpy as np
from scipy import sparse
import ... | StarcoderdataPython |
1651352 |
"""Parse metadata from FITS files on local disk.
Parsers extract metadata from FITS files and format them into standard
representation for more convenient storage and querying. Each header-and-data
unit (HDU) of a FITS file is translated into a Python dictionary in a
standardized way. These dictionaries are stored ... | StarcoderdataPython |
181708 | <reponame>kant/ocean-tensor-package
import pyOcean_cpu as ocean
t = [[ocean.bool, ocean.int8, ocean.int16, ocean.int32, ocean.int64],
[ocean.uint8, ocean.uint16, ocean.uint32, ocean.uint64],
[ocean.half, ocean.float, ocean.double, ocean.chalf, ocean.cfloat, ocean.cdouble]]
for s1 in t :
for s2 in t :
... | StarcoderdataPython |
1652384 | <gh_stars>0
# coding: utf-8
# middleware.py
from __future__ import unicode_literals
class TestMiddle(object):
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
if 'postman' in environ.get('USER_AGENT'):
start_response('403... | StarcoderdataPython |
3222064 | # Generated by Django 3.2.5 on 2021-09-26 23:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("public_data", "0017_auto_20210924_2219"),
]
operations = [
migrations.RemoveField(
model_name="artificielle2018",
na... | StarcoderdataPython |
80934 | import sys
import importlib
import argparse
import numpy as np
import random
import cmath
import math
from dft import dft, inv_dft
from fft import fft, inv_fft
from rsa import *
#arguments for dft, fft, inverse dft and inverse fft
parameters1 = []
parameters2 = []
i=4
while i<2048:
param1 = list(... | StarcoderdataPython |
4836085 | # Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
# Asena UserBot - <NAME>
""" Olayları yönetmek için UserBot modülü.
UserBot'un ana bileşenlerinden biri. """
import... | StarcoderdataPython |
1633478 | <filename>CenterLSTM.py
import torch
import torch.nn as nn
import torchvision
import torch.nn.functional as F
from RNN import ConvLSTMCell, ConvLayer
from model import init_U_Net
from utils import WrappedModel
import numpy as np
class CenterLSTMEncoder(init_U_Net, nn.Module):
def __init__(self, in... | StarcoderdataPython |
1753113 | <reponame>gokmenoz/seammockup
from bokeh.models.mappers import CategoricalColorMapper,LinearColorMapper
from bokeh.models import (GMapOptions, Patches,GMapPlot,Range1d,ColorBar,
WheelZoomTool,PanTool,TapTool,ColumnDataSource, Circle,FixedTicker)
import dill
from bokeh.plotting import gmap
from ... | StarcoderdataPython |
1768112 | from templeplus.pymod import PythonModifier
from toee import *
import tpdp
from utilities import *
import spell_utils
print "Registering sp-Hideous Blow"
hideousBlowSpell = PythonModifier("sp-Hideous Blow", 2) # spell_id, duration
hideousBlowSpell.AddHook(ET_OnGetTooltip, EK_NONE, spell_utils.spellTooltip, ())
hideous... | StarcoderdataPython |
3215657 | import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
PI = 3.1415926535897
def main():
K = int(args[2])
cancer_type_list = load_types(args[1])
cancer_type_num = []
for x in cancer_type_list:
File = open('data/data' + args[1] + '_' + x + '.txt', '... | StarcoderdataPython |
120031 | <reponame>tefra/xsdata-w3c-tests
from output.models.saxon_data.xml_versions.xv001_xsd.xv001 import DKstra
__all__ = [
"DKstra",
]
| StarcoderdataPython |
3265626 | from pydantic import BaseModel
from typing import Optional
from datetime import datetime
class CountryBase(BaseModel):
title: str = ''
description: str = ''
text: str = ''
class Config:
orm_mode = True
class CountryList(CountryBase):
id: Optional[int]
class CountrySingle(CountryBase):... | StarcoderdataPython |
31238 | <reponame>NaviRice/HeadTracking<gh_stars>1-10
import OpenEXR
from navirice_get_image import KinectClient
from navirice_helpers import navirice_image_to_np
DEFAULT_HOST= 'navirice'
DEFAULT_PORT=29000
kin = KinectClient(DEFAULT_HOST, DEFAULT_PORT)
kin.navirice_capture_settings(rgb=False, ir=True, depth=True)
last_co... | StarcoderdataPython |
111566 | <reponame>utkuyucel/flask-restful-for-rr
import datetime as dt
from math import log
class Calculate:
def __init__(self,rr, money, split_value):
self.rr = rr
self.money = money
self.split_value = split_value # optimal split value for position size
self.now = dt.datetime.now()
self.output_dict = {}
self._... | StarcoderdataPython |
4827752 | import re
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphinx.errors import SphinxError
from aplus_nodes import aplusmeta
class AplusMeta(Directive):
''' Injects document meta data for A+ configuration. '''
has_content = False
required_arguments = 0
optional_... | StarcoderdataPython |
1765635 | # coding: utf-8
from datetime import timedelta as td
import json
from unittest.mock import patch
from django.core import mail
from django.utils.timezone import now
from hc.api.models import Channel, Check, Notification
from hc.test import BaseTestCase
class NotifyTestCase(BaseTestCase):
def _setup_data(self, va... | StarcoderdataPython |
3269328 | <filename>scripts/rpc/ioat.py
from .helpers import deprecated_alias
@deprecated_alias('ioat_scan_copy_engine')
@deprecated_alias('scan_ioat_copy_engine')
def ioat_scan_accel_engine(client):
"""Enable IOAT accel engine.
"""
return client.call('ioat_scan_accel_engine')
| StarcoderdataPython |
3287480 | from random import randint
computador = randint(1, 3)
print('Pensei no número...')
nome = (input('Escolha seu nick: '))
print('-=-' * 20)
print('A máquina ira pensar em um número de 1 até 3!')
print('-=-' * 20)
jogador = int(input('- Em que número eu pensei? '))
if jogador == computador:
print('- Parbéns por me de... | StarcoderdataPython |
1752713 | <gh_stars>1-10
import os
import sys
import requests
sys.path.append(os.curdir)
from pelicanconf import *
DELETE_OUTPUT_DIRECTORY = True
GOOGLE_ANALYTICS = 'UA-1316071-6'
SITEURL = 'https://honzajavorek.cz'
FEED_POCKET_ATOM = 'feed-pocket.xml'
| StarcoderdataPython |
1610118 | import pyautogui
import time
import numpy as np
import subprocess
import os
# Caution This Vpn Changer is only Written For NORDVPN!!!
class VpnChanger:
#pause between each action
def __init__(self,vpnlist):
self.vpntexts = vpnlist
self.counter = 0
def changevpn(self)... | StarcoderdataPython |
31361 | <gh_stars>0
""" Class for absorption line component
"""
from __future__ import print_function, absolute_import, division, unicode_literals
# Python 2 & 3 compatibility
try:
basestring
except NameError:
basestring = str
import pdb
import numpy as np
import warnings
from astropy import constants as const
from ... | StarcoderdataPython |
79069 | from app import db
ROLE_USER = 0
ROLE_ADMIN = 1
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
nickname = db.Column(db.String(64), index = True, unique = True)
email = db.Column(db.String(120), index = True, unique = True)
role = db.Column(db.SmallInteger, default = ROLE_USER)
... | StarcoderdataPython |
4800483 | from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from sklearn.metrics import mean_squared_error
# Import entries and various configurations.
from settings import compare, create_map, entries, map_values
def remap(values: np.ndarray, minimum: float, maximum: floa... | StarcoderdataPython |
41002 | import argparse
import os
argparser = argparse.ArgumentParser()
argparser.add_argument("--dataset_names", default="all", type=str) # "all" or names joined by comma
argparser.add_argument("--dataset_path", default="DATASET/odinw", type=str)
args = argparser.parse_args()
root = "https://vlpdatasets.blob.core.windows.ne... | StarcoderdataPython |
1726668 | import numpy as np
def select_new_feature_indices(random_state, x, n_features):
if random_state is None:
lf_idxs = np.random.permutation(x.shape[1])[:n_features]
rf_idxs = np.random.permutation(x.shape[1])[:n_features]
else:
lf_idxs = np.random.RandomState(seed=random_state).permutati... | StarcoderdataPython |
1672145 | """
The raster module is used to analyze raster data from non-specific sources. In an idealized
workflow, use of the convert and download modules can help users obtain and pre-process data
for use with functions in the raster module. The modules capabilities include statistics
generation, subsetting, reprojecting, null... | StarcoderdataPython |
1720189 | import logging
from dataclasses import dataclass
from functools import partial
from typing import Dict, List, Optional
from urllib.parse import urljoin
from pyvultr.utils import BaseDataclass, VultrPagination, get_only_value
from .base import BaseVultrV2, command
from .enums import BackupScheduleType, InstanceUpgrade... | StarcoderdataPython |
80181 | <filename>faust_scraper/joel/utils.py<gh_stars>0
import json
import aioboto3
import requests
from bs4 import BeautifulSoup
from bs4.element import Comment
from config import config
INVISIBLE_TAGS = ['style', 'script', 'head',
'title', 'meta', '[document]']
def _tag_visible(element):
"""Is thi... | StarcoderdataPython |
1701358 | <reponame>demelin/wsd_biases_for_nmt<gh_stars>1-10
import os
import re
import sys
import json
import spacy
import string
import logging
import argparse
import numpy as np
from nltk.corpus import stopwords
WORD_ATTRACTOR_TAGS = ['ADJ']
COMPOUND_POS_LIST = ['NOUN', 'PROPN']
BLACKLIST = ['@-@']
SPECIAL_SYMBOLS = ['&apo... | StarcoderdataPython |
1716113 | from rest_toolkit import resource
@resource('/users/{id}', route_name='user')
class Resource(object):
def __init__(self, request):
pass
| StarcoderdataPython |
3291484 | from requests import get, post, put
import json
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
ip = get('https://api.ipify.org').text
print('Current ip is ', ip)
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer Y... | StarcoderdataPython |
121517 | from __future__ import absolute_import
from collections import Sequence
class ApiScopes(Sequence):
project = (
('project:read'),
('project:write'),
('project:admin'),
('project:releases'),
)
team = (
('team:read'),
('team:write'),
('team:admin'),
... | StarcoderdataPython |
1617871 | <gh_stars>10-100
from math import sqrt
from collections import namedtuple
from itertools import combinations, product
class Stats:
MAX_CARDINALITY = 25
def __init__(self):
self.sum = 0
self.sum2 = 0
self.min = float("+inf")
self.max = float("-inf")
self.count = 0
... | StarcoderdataPython |
3287741 | <gh_stars>0
from abc import ABCMeta, abstractmethod
class CalculatorStore(metaclass=ABCMeta):
@abstractmethod
def insert_computed_notification(self):
pass
@abstractmethod
def fetch_computed_notification_before_date(self):
pass | StarcoderdataPython |
3359644 | <reponame>vovababay/saleor
# Generated by Django 3.2.8 on 2021-10-26 12:02
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0008_alter_numberpaymentorder_date_close'),
]
operations = [
migrations.AlterField(
... | StarcoderdataPython |
1751797 | import copy
import os
import re
from collections import defaultdict
import marshmallow as ma
import paramtools as pt
import numpy as np
import requests
import taxcalc
from taxcalc.growfactors import GrowFactors
from taxcalc.utils import json_to_dict
class CompatibleDataSchema(ma.Schema):
"""
... | StarcoderdataPython |
1702733 | <filename>viauth/persistdb/adminarch.py
# this is shared between withadmin/ withroles, both using different userclasses
from flask import render_template, request, redirect, abort, flash, url_for
from viauth.persistdb import Arch, sqlorm
from sqlalchemy.exc import IntegrityError
class UserMixin:
def admin_create(s... | StarcoderdataPython |
1776276 | <gh_stars>0
from time import sleep
import pandas as pd
import numpy as np
import lightgbm as lgb
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.metrics import roc_auc_score
from miraiml import HyperSearchSpace, Config, Engine
class LightGBM:
def __init__(self, n_folds, **para... | StarcoderdataPython |
1796271 | <reponame>petercb/aggravator
import aggravator
import os.path
from click.testing import CliRunner
def test_createlinks():
runner = CliRunner()
conf_file = os.path.abspath('example/config.yml')
with runner.isolated_filesystem():
result = runner.invoke(aggravator.cli, [
'--uri=' + conf_fi... | StarcoderdataPython |
3236369 | import matplotlib.pyplot as plt
def set_style(style='default', w=1, h=1):
sdict = {
'default': {
'figure.figsize' : (4.98 * w, 2 * h),
'lines.linewidth': 1,
'lines.markersize': 1.5,
'font.size' : 11,
'legend.frameon' : False,
'font.family... | StarcoderdataPython |
125727 | <gh_stars>0
def queens(board):
"""
Doesn't work because the solution is not recursive. It constraints to only
checking the possible solutions of plaicng the queen in a given spot.
Another thing, no need to store the whole board, it's just enough to have a
one dimensional array of the columns.
One more thin... | StarcoderdataPython |
88952 | import os
from askapdev.rbuild.builders import Scons as Builder
# This directory is expected by the build system
if not os.path.exists("icegenerated"):
os.makedirs("icegenerated")
b = Builder(".")
b.build()
# See Issue #2462 as to why we need to run the builder twice.
# build() method in Code removes the ins... | StarcoderdataPython |
3299052 | # Generated by Django 4.0.1 on 2022-01-26 09:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Entry',
fields=[
... | StarcoderdataPython |
3291061 | <reponame>shinoyasan/github-hosts<gh_stars>0
import requests
domain_set=['raw.githubusercontent.com','github.githubassets.com','github.com','avatars.githubusercontent.com','github.global.ssl.fastly.net']
hosts=[]
for i in domain_set:
domain_arr=i.split('.')
len=domain_arr.__len__()
secfirstdomain=domain_a... | StarcoderdataPython |
3357660 | <filename>examples/basic_bot.py
import os
import discord
from discord.ext import commands
from levelling import Level, LevelUpPayload
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.level = Level(self)
async def on_ready(self):
pr... | StarcoderdataPython |
86337 | import click
from arbol.arbol import aprint, asection
from dexp.cli.defaults import DEFAULT_STORE
from dexp.cli.parsing import _get_output_path, _parse_channels
from dexp.datasets.open_dataset import glob_datasets
@click.command()
@click.argument("input_paths", nargs=-1) # , help='input path'
@click.option("--outp... | StarcoderdataPython |
159354 | <filename>whoisleak.py
import whois
import argparse
import requests
import cfscrape
import json
import Image, ImageFont, ImageDraw
import time
def searching(url):
search = whois.whois(url)
return search.email
def consult(email):
try:
r = requests.get('https://hacked-emails.com/api?q='+email)
if r.status_c... | StarcoderdataPython |
142306 | # -*- coding: utf-8 -*-
"""
Using TorchScript to serialize and deploy model
===============================================
Models in TorchANI's model zoo support TorchScript. TorchScript is a way to create
serializable and optimizable models from PyTorch code. It allows users to saved their
models from a Python proce... | StarcoderdataPython |
3301148 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Code relating to a specific Dwarf Fortress installation."""
from __future__ import print_function, unicode_literals, absolute_import
import sys, os, shutil, re
import struct
import zlib
from datetime import datetime
from distutils import dir_util
from glob import glob
f... | StarcoderdataPython |
1671276 | from typing import NamedTuple
from datetime import date as Date
from aiopg.connection import Connection
class Review(NamedTuple):
id: int
date: Date
course_id: int
review_text: str
@classmethod
def from_raw(cls, raw: tuple):
return cls(*raw) if raw else None
@staticmethod
as... | StarcoderdataPython |
1716470 | <reponame>rianadon/iok
import os
from flask import Flask, render_template, request, url_for, send_file, redirect, flash
from iok import AwesomeClient, KnowledgeGraph, NodeType, ResourceType
from networkx.readwrite import json_graph
import networkx as nx
import matplotlib.pyplot as plt
from flask_github import GitHub
fr... | StarcoderdataPython |
87279 |
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
userid = message.from_user.id
banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid))
if banlist:
bot.reply_to(message, "You are banned!")
return
markup = types.ReplyKeyboardMarkup()
numbers = list(range(3, 300... | StarcoderdataPython |
3399920 | from data_load import get_data
from model import encoder_skrnn, decoder_skrnn, skrnn_loss, skrnn_sample
from eval_skrnn import draw_image, load_pretrained_uncond
import torch
data_type = 'cat' # can be kanji character or cat
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
encoder, de... | StarcoderdataPython |
144243 | import numpy as np
import librosa
import json
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import sys
sys.path.append('vggish/')
from math import pi
import pandas as pd
from tqdm import tqdm
from sklearn.preprocessing import OneHotEncoder
import pickle
import xgboost as xgb
from scipy.fftpack import fft, hilb... | StarcoderdataPython |
4837864 | import numpy as np
import os
from .sfr import SFR
from .solar_abundance import solar_abundances
import time
from .data_to_test import likelihood_function, wildcard_likelihood_function, elements_plot, arcturus, sol_norm, plot_processes, save_abundances, cosmic_abundance_standard, ratio_function, star_function, gas_rese... | StarcoderdataPython |
165867 | <filename>bitirmetezi/venv/Lib/site-packages/plot/matplotlibConfig/__init__.py<gh_stars>1-10
from .rcParams import rcParams
| StarcoderdataPython |
3313100 | <reponame>MatthewWolff/DESMAN
#!/usr/bin/env python3
import sys
slistfile = open(sys.argv[2])
tigs = {}
for line in slistfile:
line = line.rstrip("\n")
tigs[line]=1
asmfile = open(sys.argv[1])
printing=0
for line in asmfile:
line = line.rstrip("\n")
if line[0] == '>':
if line[1:] in tigs:
... | StarcoderdataPython |
63734 | # O(log n)
def recursiveBinarySearch(vector, left_index, right_index, wanted):
if left_index <= right_index:
pivot = round(left_index + (right_index - left_index) / 2)
if (vector[pivot] == wanted): return pivot
elif vector[pivot] < wanted:
return recursiveBinarySearch(vector, pivot+1, right_index... | StarcoderdataPython |
3296709 | <reponame>HFrost0/Reinforcement-Learning-With-Gym
import random
from collections import deque
import torch
class Memory:
def __init__(self, max_size):
self.max_size = max_size
self.buffer = deque(maxlen=max_size)
def sample(self, batch_size, device=None):
data = random.sample(self.buf... | StarcoderdataPython |
1701502 | <reponame>victor-abz/saleor
from unittest import mock
from django.core.files import File
from freezegun import freeze_time
from ...core.notification.utils import get_site_context
from ...core.notify_events import AdminNotifyEvent
from ...core.utils import build_absolute_uri
from .. import notifications
from ..notific... | StarcoderdataPython |
4818275 | <reponame>macs1207/python-tutorial<gh_stars>0
from this_is_a_package import a_module
a_module.say_hello("ITC") | StarcoderdataPython |
1761705 | from tests.integration import int_test
example = """
from __future__ import annotations
from typing import List
x: List
"""
expected = """
from __future__ import annotations
x: list
"""
def test_no_duplicate_futures_annotations():
"""
Originally forgot to check for existing futures imports before adding ... | StarcoderdataPython |
1633038 | <gh_stars>1-10
from rest_framework import generics, viewsets
from ..models import Syllabus
from ..serializers import SyllabusSerializer
class SyllabusViewSet(viewsets.ModelViewSet):
queryset = Syllabus.objects.all()
serializer_class = SyllabusSerializer
class FilteredSyllabusViewSet(generics.ListAPIView):
... | StarcoderdataPython |
3276861 | <reponame>danyBautista/sit-system<filename>apps/people/admin.py
from django.contrib import admin
from .models import people
# Register your models here.
class peopleAdmin(admin.ModelAdmin):
search_fields = ('dni', 'name', 'first_name', 'last_name')
list_display = ['dni', 'name', 'first_name', 'last_name', 'use... | StarcoderdataPython |
188521 | from zope.interface import implements
from twisted.cred import checkers, credentials, error as credError
from twisted.internet import defer
from zope.interface import implements
from anchore_engine.db import db_users
from anchore_engine.db import session_scope
class AnchorePasswordChecker:
implements(checkers.IC... | StarcoderdataPython |
149346 | <filename>manage_chat/migrations/0007_auto_20170424_0015.py<gh_stars>10-100
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-24 00:15
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
depende... | StarcoderdataPython |
10353 | <reponame>vleon1/passy
from django.forms import forms
class Form(forms.Form):
def get_value(self, name):
self.is_valid() # making sure we tried to clean the data before accessing it
if self.is_bound and name in self.cleaned_data:
return self.cleaned_data[name]
... | StarcoderdataPython |
98773 | <reponame>FumeauxG/mm-api<filename>python/examples/demo_scratch.py
# short script examples.
# Note that most of these use the SWIG-generated interface directly,
# instead of the mm package
import os
import mmapi
from mmRemote import *
import mm
from mm.mm_math import *
from mm.convert import *
import ctypes
# init... | StarcoderdataPython |
3281514 | # 9/23/2013
# <NAME>
from distutils.core import setup
setup(
name='tinychat',
version='0.0',
packages=['tinychat'],
scripts=['scripts/tinychat-server.py',
'scripts/tinychat-client.py']
)
| StarcoderdataPython |
1603412 | <filename>exercicios_python_brasil/estrutura_repeticao/04_crescimento_populacional.py<gh_stars>0
print('\033[1m>>> CRESCIMENTO POPULACIONAL <<<\033[m')
hab_a = 80000
hab_b = 200000
ano = 0
while hab_a < hab_b:
hab_a = hab_a + (hab_a*3)/100
hab_b = hab_b + (hab_b * 1.5) / 100
ano += 1
print(f'Serão n... | StarcoderdataPython |
1647011 | import datetime
import unittest
from pyramid import testing
from pyramid_mailer import get_mailer
from pyramid import httpexceptions
from ccvpn.models import User, Order, Profile, PasswordResetToken
from ccvpn import views, setup_routes
from ccvpn.tests import BaseTest, DummyRequest
class TestPublicViews(BaseTest):... | StarcoderdataPython |
47021 | from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.views import APIView
from rest_framework.decorators import api_view,permission_classes
from .models im... | StarcoderdataPython |
1726900 | <gh_stars>0
import numpy as np
from games import NimState, TTTState
from ttt import BEGIN
def test_NimState():
assert NimState(25, num_takeaway=5) == NimState(25, num_takeaway=5)
assert NimState(25, num_takeaway=3) == NimState(25)
assert NimState(25, num_takeaway=3) != NimState(24)
assert NimState... | StarcoderdataPython |
3227890 | <reponame>yhs3434/SmartCarrier
from django.db import models
from django.utils import timezone
# Create your models here.
class Gps(models.Model):
name = models.CharField(max_length=200)
latitude = models.FloatField()
longitude = models.FloatField()
upload_date = models.DateTimeField(default = timezone... | StarcoderdataPython |
3279497 | <filename>forenshit/darkpixel/gen_mate.py
# mau buang border braillenya
import cv2
import numpy as np
img = cv2.imread('good_one_mate.png', 0)
cnv = np.zeros(img.shape, np.uint8)
row, col = img.shape
for i in range(row):
for j in range(col):
if img[i, j] == 0:
cnv[i, j] = 0
else:
cnv[i, j] = 255
cv2.imwri... | StarcoderdataPython |
3383804 | <reponame>LanaLana/pose_estimation_demo
#!/usr/bin/env python
from flask import Flask, render_template, Response, request, json
import time
# import json
app = Flask(__name__)
TIME_FILE = './time.txt'
def read_txt(file):
with open(file, 'r') as f:
t = f.read()
return t
def write... | StarcoderdataPython |
3225853 | <reponame>winkidney/PickTrue
import os
from picktrue.engine import Downloader
from picktrue.sites.artstation import ArtStation
from picktrue.sites.douban import DoubanPersonalAlbum
from picktrue.sites.huaban import HuaBan, HuaBanBoard
from picktrue.sites.pixiv import Pixiv
def _user_home_run(site, path_prefix=None)... | StarcoderdataPython |
4836394 | # coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import pytest
from azure.core.exceptions import HttpResponseError, ClientAuthenticationError
from azure.core.credentials import AzureKeyCredential
from ... | StarcoderdataPython |
168640 | # Offline DQM for HLT_Mu3er1p5_PFJet100er2p5_PFMETX_PFMHTX_IDTight (X = 70, 80, 90)
# <NAME> 2018
import FWCore.ParameterSet.Config as cms
from DQMOffline.Trigger.SusyMonitor_cfi import hltSUSYmonitoring
SoftMuHardJetMETSUSYmonitoring = hltSUSYmonitoring.clone()
SoftMuHardJetMETSUSYmonitoring.FolderName = cms.string... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.