id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3350200 | <gh_stars>0
import os
import pytest
from pathlib import Path
from setuptools.config import read_configuration
namespace = 'bourbaki'
pardir = Path(__file__).parent.parent
modname = next(f.name for f in (pardir / namespace).iterdir() if f.is_dir() and f.name != '__pycache__')
@pytest.fixture(scope='module')
def pkgnam... | StarcoderdataPython |
1611809 | #046_Contagem_regressiva.py
#
from time import sleep
for i in range(0, 11):
sleep(1)
print(i)
print("Acabou")
for i in range(10, -1, -1):
sleep(1)
print(i)
print("Acabou") | StarcoderdataPython |
4823343 | <reponame>edrmonteiro/DataSciencePython<gh_stars>0
"""
Agrupamento com k-means
"""
import os
path = os.path.abspath(os.getcwd()) + r"/0_dataset/"
from sklearn import datasets
import numpy as np
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# Carregamen... | StarcoderdataPython |
4840009 | from peewee import *
import datetime
from dataModels.BaseModel import BaseModel
class MachinePool(BaseModel):
name = TextField()
ipAddress = TextField()
internalIpAddress=TextField()
userId = TextField()
password = TextField()
sshFilePath=TextField(default=None)
kubeVersion = TextField()
... | StarcoderdataPython |
83397 | <reponame>FilipeMaia/euxfel2013-analysis
'''
CrystFEL geometry file conversion scripts
Author: <NAME>
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
cspad_psana_shape = (4, 8, 185, 388)
cspad_... | StarcoderdataPython |
3397898 | <reponame>jkpubsrc/python-module-jk-simplexml
from .HAbstractElement import HAbstractElement
class HText(HAbstractElement):
def __init__(self, text:str):
self.text = text
self.tag = None
#
def isDeepEqualTo(self, obj) -> bool:
if isinstance(obj, HText):
return obj.text == self.text
else:
return... | StarcoderdataPython |
1267 | <reponame>hadrianmontes/jax-md<gh_stars>100-1000
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | StarcoderdataPython |
84436 | <filename>ball_catching/config.py
#!/usr/bin/python
###############################################
# Configuration
import os
here = os.path.abspath(os.path.dirname(__file__))
params_yml = 'params.yml'
data_root = os.path.expanduser("~/ball_catching_data")
settings_root = os.path.join(here, "_files") | StarcoderdataPython |
3390019 | '''
Do some forced-photometry simulations to look at how errors in
astrometry affect the results. Can we do anything with forced
photometry to measure astrometric offsets? (photometer PSF + its
derivatives?)
'''
from __future__ import print_function
import sys
import os
import numpy as np
import pylab as plt
import fi... | StarcoderdataPython |
148340 | <reponame>fsanges/glTools
import maya.cmds as mc
import glTools.utils.channelState
import glTools.utils.defaultAttrState
import glTools.utils.attribute
import glTools.utils.base
import glTools.utils.cleanup
import glTools.utils.colorize
import glTools.utils.component
import glTools.utils.connection
import glTools.uti... | StarcoderdataPython |
3222664 | <filename>OperatorsPrecedence.py
#@Author <NAME>
a = 20
b = 10
c = 15
d = 5
print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d) # (30) * (15/5)... | StarcoderdataPython |
96509 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 09:26:24 2019
@author: <NAME>
"""
import argparse
from pathlib import Path
import rpg_lib
import numpy as np
def main():
parser = argparse.ArgumentParser(prog='FRM4RADAR')
parser.add_argument(
"path",
type=Path,
... | StarcoderdataPython |
4841280 | import unittest
import os
from reactivexcomponent.configuration.api_configuration import APIConfiguration
class TestConfiguration(unittest.TestCase):
def setUp(self):
self.configuration = APIConfiguration(
os.path.join("tests", "unit", "data", "WebSocket_NewDevinetteApi_test.xcApi"))
de... | StarcoderdataPython |
3304827 | <reponame>Crossing-Minds/reco-api-benchmarks
from .amazonrecoapi import AmazonRecoApi
| StarcoderdataPython |
4808245 | import json
import logging
import platform
import re
from io import BytesIO
from subprocess import check_output, CalledProcessError
import time
import os
import yaml
from binstar_client import errors
from binstar_client.utils import get_server_api, store_token
from binstar_client.utils.notebook.inflection import para... | StarcoderdataPython |
1722973 | # =============================================================================
# Copyright 2020 NVIDIA. 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://ww... | StarcoderdataPython |
3391124 | <reponame>sirosen/temp-cli-test<gh_stars>10-100
from typing import Tuple
import click
from globus_cli.login_manager import LoginManager
from globus_cli.parsing import command, no_local_server_option
@command(
"consent",
short_help="Update your session with specific consents",
disable_options=["format", ... | StarcoderdataPython |
3316346 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-18 10:17
from __future__ import unicode_literals
from django.db import migrations
def store_last_status(apps, schema_editor):
VenueRequest = apps.get_model('froide_food', 'VenueRequest')
VenueRequestItem = apps.get_model('froide_food', 'VenueRe... | StarcoderdataPython |
50215 | <reponame>incident-reporter/incident-reporter
import datetime
from typing import Optional
import discord
from discord.ext import commands
from ..storage import Storage
from ..util import is_staff
class Config(commands.Cog):
@commands.command(help='Change the prefix of the bot.')
@commands.has_permissions(m... | StarcoderdataPython |
157993 | <filename>OPENAI/NER.py
import openai
openai.api_key = "<KEY>"
restart_sequence = "\n"
primer = open("primer.txt").read()
labels = ["person", "organisation", "location"]
labels = "".join([i + ", " for i in labels])
sentences = [
"Jacco is studying at Utrecht University.",
"Dan is an old friend from my time at... | StarcoderdataPython |
3364846 | '''
Functional tests for cassandra timeseries
'''
import time
import datetime
import os
import cql
from . import helpers
from .helpers import unittest, os, Timeseries
@unittest.skipUnless( os.environ.get('TEST_CASSANDRA','true').lower()=='true', 'skipping cassandra' )
class CassandraApiTest(helpers.ApiHelper):
de... | StarcoderdataPython |
1761757 | """
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
from azlmbr.entity import EntityId
from azlmbr.math import Vector3
from editor_python_test_tools.edi... | StarcoderdataPython |
1630811 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.views.generic.list_detail import object_list
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from models import Post
def posts(request, template='blog/posts.html'):
return object_list(request,
... | StarcoderdataPython |
3307959 | <filename>pywubi/constants.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from enum import IntEnum, unique
import os
import re
from pywubi import wubi_dict
# 单字拼音库
WUBI_86_DICT = wubi_dict.wubi_86_dict
# 利用环境变量控制不做copy操作, 以减少内存使用
if not os.environ.get('PYWUBI_NO_DICT_COPY'):
WUBI_86_DICT = WUBI_86_DICT.copy()... | StarcoderdataPython |
4841967 | IMAGE_CODE_EXPIRE = 300
| StarcoderdataPython |
1662240 | import subprocess
import os
import glob
import shutil
import sys
import optparse
import tempfile
TMP_OUT = tempfile.mkdtemp()
SECRETS = "secrets"
DISTINGUISHED_NAME = {"domain": "example.com",
"C": "US",
"ST": "Maryland",
"L": "Baltimore",
... | StarcoderdataPython |
3280320 | <filename>source/visualization/regression_bias_variance.py
import numpy as np
import matplotlib.pyplot as plt
num_points = 50
f = lambda x: np.sin(x)
x = np.linspace(-10, 10, num_points)
y = f(x) + np.random.normal(0,0.5, len(x)) # function of the curve with some normal noise added
plt.figure(figsize=(20,10))
plt.s... | StarcoderdataPython |
1728318 | #!/usr/bin/env python2
"""install.py
Webware for Python installer
FUTURE
* Look for an install.py in each component directory and run it
(there's not a strong need right now).
* Use distutils or setuptools instead of our own plugin concept.
"""
import os
import sys
from glob import glob
from operator impo... | StarcoderdataPython |
4827268 | """
Tests for the Finances API class.
"""
import unittest
import datetime
import mws
from mws.utils import clean_date
from .utils import CommonAPIRequestTools
class FinancesTestCase(CommonAPIRequestTools, unittest.TestCase):
"""Test cases for Finances."""
api_class = mws.Finances
# TODO: Add remaining ... | StarcoderdataPython |
1641782 | # -*- encoding:utf-8 -*-
import os
import numpy as np
import cPickle as pkl
import json
def pick_article(words):
difficulty_set = ["high"]
raw_data = "../data/RACE"
cnt = 0
avg_article_length = 0
avg_question_length = 0
avg_option_length = 0
avg_article_sentence_count = 0
max_article_se... | StarcoderdataPython |
3286824 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
1669745 | from dbsp_drp import coadding
def test_group_coadds():
fname_to_spats = {
'a1': [100, 200, 300],
'a2': [100, 200, 300],
'a3': [101, 199],
'a4': [99, 201, 303]
}
correct = [
{
'spats': [99, 100, 100, 101],
'fnames': ['a4', 'a1', 'a2', 'a3']
... | StarcoderdataPython |
73435 | <reponame>pyoor/distiller
import yaml
import os
import shutil
import sqlite3
import sys
class DistillerConfig:
def __init__(self, config_file, section):
self.config = read_config(config_file, section)
try:
self.project_name = self.config['name']
except KeyError:
ra... | StarcoderdataPython |
3364160 |
"""Configuration for a stack."""
# Copyright (C) 2015 <NAME>, <NAME> and <NAME>.
# Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd.
# Copyright (C) 2015--2019 The Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | StarcoderdataPython |
3209900 | <reponame>pnarsina/w251_chess_objectid_n_rl
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch
from gym_chess_env import ChessBoard_gym
from agent_chess_pytorch import DQN
import numpy as np
import math
import chess
# In[2]:
class Gen_Legal_move:
def __init__(self, model_weights="checkpoint.pth-4roo... | StarcoderdataPython |
113091 | <gh_stars>0
import math
from geopy.distance import vincenty
from geopy.point import Point
from os import path
from slayer import file_utils, constants
from datetime import datetime
from isodate import parse_datetime, parse_duration, datetime_isoformat
import pytz
import pandas as pd
def lat2y(a):
return 180.0 / m... | StarcoderdataPython |
1728241 | from gbmgeometry.utils.plotting.space_plot import animate_in_space, plot_in_space
from gbmgeometry import PositionInterpolator
from gbmgeometry.utils.plotting.sky_point import balrog_to_skypoints
from gbmgeometry.utils.package_utils import get_path_of_data_file
def test_space_plot(interpolator):
tmin, tmax = int... | StarcoderdataPython |
3355115 | <gh_stars>0
# coding=utf-8
# Copyright 2022 The Google Research 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... | StarcoderdataPython |
3396288 | from django.contrib import admin
from .models import Color
admin.site.register(Color)
| StarcoderdataPython |
1768417 | <reponame>azuline/hey-bro-check-log
"""This module contains the generation functions for dicts of to-match lines
when marking up log files.
"""
import html
import re
from heybrochecklog.shared import format_pattern as fmt_ptn
def eac_track_matches(translation):
"""Generate the list of to-match lines from transl... | StarcoderdataPython |
1668466 | <reponame>rdelosreyes/myctapipe
import sys
import argparse
from matplotlib import colors, pyplot as plt
import numpy as np
from ctapipe.io.hessio import hessio_event_source
from pyhessio import *
from ctapipe.core import Container
from ctapipe.io.containers import RawData, CalibratedCameraData
from ctapipe import visua... | StarcoderdataPython |
64481 | def fib(n):
"return nth term of Fibonacci sequence"
a, b = 0, 1
i = 0
while i<n:
a, b = b, a+b
i += 1
return b
def linear_recurrence(n, (a,b)=(2,0), (u0, u1)=(1,1)):
"""return nth term of the sequence defined by the
linear recurrence
u(n+2) = a*u(n+1) + b*u(n)"""
... | StarcoderdataPython |
3297968 | <gh_stars>0
from unittest import TestCase
from surfactant_example.contributed_ui.surfactant_contributed_ui import (
SURFACTANT_PLUGIN_ID
)
from surfactant_example.contributed_ui.templates import (
ExecutionLayerTemplate, IngredientTemplate)
from surfactant_example.data.gromacs_database import GromacsDatabase
... | StarcoderdataPython |
4801783 | <filename>renderer/__init__.py<gh_stars>10-100
__version__ = '0.1.3'
default_app_config = 'renderer.apps.RenderAppConfig'
| StarcoderdataPython |
54319 | <filename>czsc/utils/__init__.py<gh_stars>1-10
# coding: utf-8
from .echarts_plot import kline_pro, heat_map
from .ta import KDJ, MACD, EMA, SMA
from .io import read_pkl, save_pkl, read_json, save_json
from .log import create_logger
from .word_writer import WordWriter
def x_round(x: [float, int], digit=4):
"""用去... | StarcoderdataPython |
95131 | <filename>niftynet/layer/rand_flip.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import warnings
import numpy as np
from niftynet.layer.base_layer import RandomisedLayer
warnings.simplefilter("ignore", UserWarning)
warnings.simplefilter("ignore", RuntimeWarning)
class RandomFli... | StarcoderdataPython |
1795728 | <filename>microsim/utilities.py
# Contains some useful utility functionality
import os
from urllib.request import urlopen
import requests
import tarfile
import pandas as pd
from typing import List
from tqdm import tqdm
from microsim.column_names import ColumnNames
class Optimise:
"""
Functions to optimise th... | StarcoderdataPython |
1606964 | <reponame>line-mind/error_solver
import os
import time
import pytest
from ..data import get_file_path
from .error_solver import *
def test_repr():
path = get_file_path('wire_load.ef')
solver = ErrorSolver.from_file(path)
repr(solver)
def test_from_file():
path = get_file_path('wire_load.ef')
sol... | StarcoderdataPython |
86686 | import logging
import requests
import json
from itertools import chain, islice
from datetime import datetime
from google.cloud import datastore
from flask import Flask, request
from requests_oauthlib import OAuth1Session
from collections import namedtuple
app = Flask(__name__)
log = logging.getLogger('werkzeug')
Sen... | StarcoderdataPython |
1678807 | <reponame>goomhow/stock-manage-xgboost
import pandas as pd
from sklearn import metrics
from sklearn.externals import joblib
from xgboost.sklearn import XGBClassifier
import os
import time
from datetime import datetime
rm_col= ['ACC_TYPE',
'ACT_FLAG',
'AVG_MON_AMT_A',
'AVG_MON_AMT_B',
'AVG_MON_AMT_C',
'BILL_OWE_AM... | StarcoderdataPython |
1636148 | from .base import X11BaseRecipe
class LibSMRecipe(X11BaseRecipe):
def __init__(self, *args, **kwargs):
super(LibSMRecipe, self).__init__(*args, **kwargs)
self.sha256 = '0baca8c9f5d934450a70896c4ad38d06' \
'475521255ca63b717a6510fdb6e287bd'
self.name = 'libSM'
... | StarcoderdataPython |
1662367 | <reponame>daniilstudent/lab_6
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Условие задачи: Использовать словарь, содержащий следующие ключи: фамилия, имя; номер телефона;
#дата рождения (список из трех чисел). Написать программу, выполняющую следующие
#действия: ввод с клавиатуры данных в список, состоящий из сло... | StarcoderdataPython |
3238204 | <reponame>vidkidz/crossbridge
import overload_extendc
f = overload_extendc.Foo()
if f.test(3) != 1:
raise RuntimeError
if f.test("hello") != 2:
raise RuntimeError
if f.test(3.5,2.5) != 3:
raise RuntimeError
if f.test("hello",20) != 1020:
raise RuntimeError
if f.test("hello",20,100) != 120:
raise Ru... | StarcoderdataPython |
1618522 | import datetime
import bson
from fastapi_mongodb.helpers import AsyncTestCase
from fastapi_mongodb.models import BaseCreatedUpdatedModel, BaseDBModel
class TestBaseDBModel(AsyncTestCase):
class TestCreatedUpdatedModel(BaseDBModel, BaseCreatedUpdatedModel):
test: str
class TestModel(BaseDBModel):
... | StarcoderdataPython |
3380928 | <reponame>RaoniSilvestre/Exercicios-Python<gh_stars>1-10
print('\033[31m=-'*20)
print(' CALCULADOR DE P.A.')
print('=-'*20)
print('')
print('Esse programa vai mostrar os 10 primeiros\nvalores da Progressão Aritimétrica que \nvocê escolher >:D')
print('')
primeiro = int(input('Primeiro termo: '))
razao = int(... | StarcoderdataPython |
7166 | # -*- coding: utf-8 -*-
# flake8: noqa
from flask import Flask
from flask_themes2 import Themes
import config
from util.auth import is_admin
from util.converter import RegexConverter
from util.csrf import generate_csrf_token
app = Flask(__name__.split('.')[0])
app.secret_key = config.SECRET_KEY
app.url_map.converter... | StarcoderdataPython |
103782 | # LCD via i2c driver for MicroPython (on ESP8266)
# Copyright (c) 2016 Dries007
# License: MIT
#
# Only tested with PCF8574T and a 16*2 LCD
import time
_BIT0 = const(1 << 0)
_BIT1 = const(1 << 1)
_BIT2 = const(1 << 2)
_BIT3 = const(1 << 3)
_BIT4 = const(1 << 4)
_BIT5 = const(1 << 5)
_BIT6 = const(1 << 6)
_BIT7 = cons... | StarcoderdataPython |
161278 | import numpy as np
import cv2
import tensorflow as tf
from scipy import ndimage
import sys
import os
import math
def getBestShift(img):
"""
params - image to get shifts of
returns - finds the best shifts to do on the image and returns the x and y coordinates of shifts
"""
cy,cx = ndimage.measuremen... | StarcoderdataPython |
3213398 | <filename>keybaseclient/raw_api.py
import base64
import binascii
import hashlib
import hmac
import requests
import scrypt
class InvalidRequestException(Exception):
"""Exception containing information about failed request."""
def __init__(self, message, status=None):
"""Instantiate exception with mess... | StarcoderdataPython |
4803943 | <gh_stars>0
# Copyright 2021 <NAME> <<EMAIL>>. All Rights Reserved.
# Author: <NAME> <<EMAIL>>
#
# 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... | StarcoderdataPython |
88893 | # Copyright (c) 2014, Vienna University of Technology (TU Wien), Department
# of Geodesy and Geoinformation (GEO).
# 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 co... | StarcoderdataPython |
1765536 | # Copyright 2014 Deutsche Telekom AG
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | StarcoderdataPython |
1677402 | # Test Conan package
# <NAME>, Odant 2019 - 2020
from conans import ConanFile, CMake
class PackageTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
requires = "ninja/1.9.0"
def imports(self):
self.copy("*.pdb", dst="bin", src="bin")
self.co... | StarcoderdataPython |
3327434 | from .attributes import *
from .image import svg_content
from .primitives import *
| StarcoderdataPython |
4805574 | # -*- coding: utf-8 -*-
# Author:D4Vinci
# Don't touch my code, it's art :D
from __future__ import print_function
import sys, argparse
try: # Instead of using sys to detect python version
input = raw_input
except:
pass
def my_map(fuck,asses):
#Because map behaves differently in python 2 and 3, I decided to write m... | StarcoderdataPython |
3383339 | import numpy as np
from typing import List, Tuple
from mph import GradedMatrix, groebner_bases, presentation_FIrep
def choose_graded_subbasis(matrix: List[List[Tuple[int, int]]], column_grades: List[List[int]], row_grades: List[List[int]]):
dense_matrix = np.zeros(shape=(len(row_grades), len(column_grades)), dtype=n... | StarcoderdataPython |
1665093 | <gh_stars>0
# Generated by Django 2.1.7 on 2019-04-01 00:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Permission',
fields=[
... | StarcoderdataPython |
3214920 | import pandas as pd
import numpy as np
import os
master_data = pd.DataFrame()
for file in os.listdir('../clean/'):
if(file == 'macro' or file == 'all_clean_data.csv'):
print("Not a file to be appended.")
continue
print("Appending",file)
data = pd.read_csv('../clean/{}'.format(file),encoding='utf-8',index_col=F... | StarcoderdataPython |
1717233 | import os
import glob
import time
import sys
import datetime
from influxdb import InfluxDBClient
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
host = ""
port = 8086
user = ""
password = ""
dbname = ""
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device... | StarcoderdataPython |
68806 | # -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: <NAME> <<EMAIL>>
#
# 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
#
# Un... | StarcoderdataPython |
1678794 | from subprocess import check_call
import os
import shutil as sh
from glob import glob
import nbformat as nbf
from nbclean import NotebookCleaner
from tqdm import tqdm
import numpy as np
SITE_ROOT = os.path.expanduser('~/github/forks/python/teaching/dsep/jupyterhub-for-education-template')
SITE_NAVIGATION = os.path.joi... | StarcoderdataPython |
1727303 | from django import forms
from categories.models import Category
from django.conf import settings
class CategoryForm(forms.ModelForm):
cat_type = forms.ChoiceField(choices=settings.TR_TYPES, required=False, label='Category type')
name = forms.CharField(required=False, label='Name')
class Meta:
mod... | StarcoderdataPython |
3378829 | <reponame>maximilianschaller/genforce
# python3.7
"""Defines loss functions."""
import os
import torch
import numpy as np
import torch.nn.functional as F
import sys
sys.path.append(os.getcwd())
from fourier import fourier_dissimilarity
__all__ = ['FourierRegularizedLogisticGANLoss']
apply_loss_scaling = lambda x: x ... | StarcoderdataPython |
1629073 | # Generated by Django 3.2.6 on 2021-09-05 20:44
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | StarcoderdataPython |
3372965 | import unittest
from app.utilities.factory import Factory
class TestClassA(object):
pass
class TestClassB(object):
pass
class TestFactory(unittest.TestCase):
def test_register(self):
factory = Factory()
factory.register("test", TestClassA)
self.assertIsInstance(factory.creat... | StarcoderdataPython |
3225550 | <gh_stars>10-100
##########################################################
## Define variables
##########################################################
num_of_stages_inv = 383
num_of_stages_nand4 = 127
num_of_stages_NOR3 = 127
##########################################################
## hvt NOR3
#################... | StarcoderdataPython |
3399361 | <reponame>cschmidat/cleartext
from .encoder_decoder import EncoderDecoder
| StarcoderdataPython |
1721812 | <gh_stars>0
#!/Users/Jonman/anaconda/bin/python3
import asyncio as snc
@snc.coroutine
def handle_echo( reader, writer):
data = yield from reader.read( 100)
msg = data.decode()
peer = writer.get_extra_info( 'peername' )
print( "Received {} from {}".format( msg, peer))
print( "Send: {}".format(... | StarcoderdataPython |
3274139 | import csv
import json
import time
#turns the csv into a list of lists [[x, y, z,], [a, b, c]
exampleFile = open('repoffinput.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
#variable to hold the data we care about
cleanData = []
#removes header row
del exampleData[0]
#pull the dat... | StarcoderdataPython |
1777699 | <reponame>ethansaxenian/RosettaDecode
line = my_file.readline() # returns a line from the file
lines = my_file.readlines() # returns a list of the rest of the lines from the file
| StarcoderdataPython |
3209444 | <filename>gc.py<gh_stars>0
#!/usr/bin/env python3
# Write a program that computes the GC% of a DNA sequence
# Format the output for 2 decimal places
# Use all three formatting methods
dna = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' # feel free to change
gc = 0
for i in range(0, len(dna)):
if dna[i] == 'G' or dna[i] == '... | StarcoderdataPython |
1619295 | <filename>pystachio/container.py<gh_stars>10-100
import copy
from collections import Iterable, Mapping, Sequence
from inspect import isclass
from .base import Object
from .naming import Namable, frozendict
from .typing import Type, TypeCheck, TypeFactory, TypeMetaclass
class ListFactory(TypeFactory):
PROVIDES = 'L... | StarcoderdataPython |
137155 | ## <NAME>
# By <NAME>
# Noice ca (by Senku)
# add des commandes de fun
import os
import discord
from typing import Optional
from discord.ext import commands
from discord import File
#from PIL import Image, ImageSequence
import asyncio
import json
import random
os.chdir('.')
token = 'the token'
def wrapper(ctx, emoj... | StarcoderdataPython |
1736835 | import pandas as pd
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import LabelEncoder
import Dataset
import text_normalization
from pickle import dump, load
from sklearn.model_selection import train_test_split
def loadTrainValData(batchsize=16, num_worker=2, pretraine_path="bert-base-unca... | StarcoderdataPython |
3240076 | <reponame>HrushikeshShukla/multilingual_chatbot
#!/usr/bin/python3 # This is client.py file
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on ... | StarcoderdataPython |
1604382 | <filename>Miniprojekt och Studio/Mini3/mini3Flash.py
import numpy as np
import matplotlib.pyplot as plt
from VLE import *
P = 1520 # mmHg
T = 87 # C
Xf = 0.35
tol = 0.001
Tb_m = 64.7
Tb_e = 77.1
A1 = 7.87863
B1 = 1473.11
C1 = 230.0
A2 = 7.09803
B2 = 1238.71
C2 = 217.0
ABC1 = [A1, B1, C1]
ABC2 = [A2, B2, C2]
Lambd... | StarcoderdataPython |
3263097 | <filename>scripts/x_model_gen.py
"""
This is a small script for generating the initial Go model from the
olca-schema yaml files. To run this script you need to have PyYAML
installed:
pip install pyyaml
You also have to configure the YAML_DIR in this script to point to
the directory where the YAML files are ... | StarcoderdataPython |
100070 | <reponame>rackerlabs/daemonx
# Copyright (c) 2013 <NAME>
#
# 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 la... | StarcoderdataPython |
1647940 | import os
import sys
sys.path.append(os.getcwd())
import pickle
import pandas as pd
from hpo.utils import *
from hpo.helpers import *
from hpo.task2vec.task2vec import Task2Vec
from hpo.task2vec.models import get_model
import hpo.task2vec.task_similarity as task_similarity
def calculate_dataset_x_augmentation_embed... | StarcoderdataPython |
4832895 | from django.contrib import admin
from .models import PageView
# Register your models here.
class PageViewAdmin(admin.ModelAdmin):
list_display = ['hostname', 'timestamp']
admin.site.register(PageView, PageViewAdmin)
| StarcoderdataPython |
3219725 | #
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# 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 li... | StarcoderdataPython |
91048 | <reponame>aristoteleo/scribe-py
from . import settings
from datetime import datetime
from time import time as get_time
from platform import python_version
_VERBOSITY_LEVELS_FROM_STRINGS = {'error': 0, 'warn': 1, 'info': 2, 'hint': 3}
def info(*args, **kwargs):
return msg(*args, v='info', **kwargs)
def error(*a... | StarcoderdataPython |
4869 | import numpy as np
def normalize(x):
return x / np.linalg.norm(x)
def norm_sq(v):
return np.dot(v,v)
def norm(v):
return np.linalg.norm(v)
def get_sub_keys(v):
if type(v) is not tuple and type(v) is not list:
return []
return [k for k in v if type(k) is str]
def to_vec3(v):
if isinstance(v, (float, int)):
... | StarcoderdataPython |
1667593 | from django.db import models
from django_extensions.db.models import TimeStampedModel
from instance_selector.edit_handlers import InstanceSelectorPanel
from wagtail.admin.edit_handlers import FieldRowPanel, MultiFieldPanel, FieldPanel
from wagtail.images.edit_handlers import ImageChooserPanel
class Employee(TimeStamp... | StarcoderdataPython |
3383519 | <reponame>TahaEntezari/ramstk
# -*- coding: utf-8 -*-
#
# ramstk.views.gtk3.program_status.panel.py is part of the RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""GTK3 Program Status Panels."""
# Standard Library Imports
from typ... | StarcoderdataPython |
4831250 | from rx import from_
def print_number(x):
print('The number is {}'.format(x))
from_(range(10)).subscribe(print_number) | StarcoderdataPython |
3295572 | import os
import random
from typing import Callable, List, Tuple
from PySide2.QtCore import QObject, QRunnable, QSize, Qt, QThreadPool, Signal, Slot
from PySide2.QtGui import QIcon
from PySide2.QtWidgets import QComboBox, QGridLayout, QLabel, QListWidget, QListWidgetItem, QWidget
from ..data import get_file_metadata,... | StarcoderdataPython |
3344378 | from .NNMetricFactory import *
from typing import List, Dict, DefaultDict
import numpy as np
import torch
from collections import defaultdict
from torch.utils.tensorboard import SummaryWriter
from typing import Union
import sys
class RunNNMetrics( object ):
"""
A class for running and writing NNSimpleMetrics... | StarcoderdataPython |
141174 | #! /usr/bin/python2
# -*- coding: utf8 -*-
import pykka
import time
from Manager import Manager
class Big_Brother(pykka.ThreadingActor):
def __init__(self):
super(Big_Brother, self).__init__()
self.pool = {'managers':[]}
def start_manager(self, token):
self.pool['managers'].append(Man... | StarcoderdataPython |
166629 | <reponame>xyz1396/Projects
#!/usr/bin/python
import sys, getopt, warnings, os, re
def getConfigMasterKeyValue (sMasterKey, dictConfigKeyValues) :
dictKeyValueSet = {}
for currentKey, currentValue in dictConfigKeyValues.items() :
if( currentKey.startswith(sMasterKey+"{") and currentKey.endswith("}") and ((len(sM... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.