id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
23607 | import sys
from ctypes import *
def test_getattr():
class Stuff(Union):
_fields_ = [('x', c_char), ('y', c_int)]
stuff = Stuff()
stuff.y = ord('x') | (ord('z') << 24)
if sys.byteorder == 'little':
assert stuff.x == b'x'
else:
assert stuff.x == b'z'
def test_union_of_struct... | StarcoderdataPython |
3334717 | <reponame>gabrielaleal/pokebattle<gh_stars>1-10
from rest_framework.permissions import BasePermission, IsAuthenticated
from battles.models import Battle
class IsInBattle(BasePermission):
def has_object_permission(self, request, view, obj):
return request.user in [obj.creator, obj.opponent]
class IsBatt... | StarcoderdataPython |
1792994 | <gh_stars>0
# Generated by Django 3.0.4 on 2020-03-06 06:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('finance', '0004_auto_20200304_1242'),
]
operations = [
migrations.CreateModel(
name='Transaction',
field... | StarcoderdataPython |
1771991 | from django.conf import settings
import json
def is_json(storage_field):
try:
_ = json.loads(storage_field)
return True
except:
return False
class UserFieldMixin:
"""Mixin that adds the necessary data retrieval and storage
functions to an object storing data from extra field... | StarcoderdataPython |
108136 | <gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
from autonetkit.compilers.device.router_base import RouterCompiler
from autonetkit.nidb import config_stanza
class QuaggaCompiler(RouterCompiler):
"""Base Quagga compiler"""
lo_interface = 'lo:1'
def compile(self, node):
super(QuaggaCompi... | StarcoderdataPython |
3250424 | """client.py - client for wikitweets"""
import os
import re
import sys
import random
import getopt
import logging
import logging.config
import ConfigParser
import twitter # pip install python-twitter
from twisted.words.protocols import irc
from twisted.internet import reactor, protocol
from twisted.python import log a... | StarcoderdataPython |
57298 | <filename>exs/mundo_3/python/089.py
"""
Desafio 089
Problema: Crie um programa que leia nome e duas notas de vários alunos
e guarde tudo em uma lista composta. No final, mostre um
boletim contendo a média de cada um e permita que o usuário
possa mostrar as notas de cada aluno individualme... | StarcoderdataPython |
1716835 | import base64
class FileReader(object):
def __init__(self, file_path):
with open(file_path, 'rb') as filedata:
self.raw_data = base64.b64encode(filedata.read())
self.raw_data = self.raw_data.replace("=", "")
def sanitize(self, char):
my_ord = ord(char)
return str(my_ord).zfill(3)
def read(self, chu... | StarcoderdataPython |
1658441 | import sys
sys.path.insert(0, '../utils')
import ioManager
import new
sys.path.insert(0, '../connectors')
import transport
sys.path.insert(0,'../sequential')
import ff
inputS = transport.wires(1)
inputR = transport.wires(1)
out = transport.wires(2)
clock = transport.wires(1)
hware = ff.SRFlipFlop(inputS,inputR,out,clo... | StarcoderdataPython |
3320237 | <gh_stars>10-100
"""
#Create set of pulses for single qubit randomized benchmarking sequence.
Created on Tue Feb 07 15:01:37 2012
@authors: <NAME>, <NAME>, and <NAME>
"""
import numpy as np
from scipy.linalg import expm
from scipy.constants import pi
from functools import reduce
from itertools import permutations
f... | StarcoderdataPython |
3257777 | <gh_stars>1-10
# coding=utf-8
import modelscript.scripts.demo.parser
import modelscript.scripts.demo.printer
| StarcoderdataPython |
1626939 | <reponame>kaixin-bai/walle
"""Tests for the Orientation class.
"""
import numpy as np
import pytest
from walle.core import Orientation, UnitQuaternion, Quaternion
class TestOrientation(object):
def axis_angle_vector(self, deg):
theta = np.deg2rad(deg)
unit_vec = np.array([0, 0, 1])
return unit_vec, th... | StarcoderdataPython |
3298071 | DATABASE_NAME = '{{cookiecutter.project_name}}'
DATABASE_USER = 'user'
DATABASE_PASSWORD = 'password'
DATABASE_HOST = 'database'
DEBUG = True
| StarcoderdataPython |
1753332 | cts = [
'<KEY>',
'<KEY>',
'32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb',
'32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef... | StarcoderdataPython |
3255722 | <filename>src/code/db/analytics/index_feat.py
#!/usr/bin/env python
from collections import OrderedDict
from json import dump
from nltk import pos_tag
from nltk.corpus import stopwords
from context import *
from settings.filemgmt import fileManager
from settings.paths import ADJECTIVES, BOW, CURSE_RAW, CURSES, NOUNS... | StarcoderdataPython |
66406 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
3284424 | <reponame>BlairMar/Pintrest-webscraping-project
from typing import Union, List, Set
from pandas.core.frame import DataFrame
from selenium import webdriver
from time import sleep
import urllib.request
import os
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selen... | StarcoderdataPython |
3369746 | <reponame>dmm34/voteapp
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-08 16:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('voteapp', '0001_initial'),
]
operations = [
migrati... | StarcoderdataPython |
1604385 | from abc import ABCMeta, abstractmethod
class Action:
__metaclass__ = ABCMeta
def __init__(self, scraper):
self._scraper = scraper
self._web_driver = scraper.web_driver
@abstractmethod
def do(self): raise NotImplementedError
@abstractmethod
def on_fail(self): raise NotImplem... | StarcoderdataPython |
4837975 | <gh_stars>0
import json
import os
from data_import.profile_information import ProfileInfo
from data_import.api import WebImporter
def download_activities_from_api(
profile: ProfileInfo,
save_path: str,
file_name: str = 'activities'
):
# download activities
importer = WebImporter(profile.client... | StarcoderdataPython |
3323791 | <reponame>SafeBreach-Labs/hAFL2<gh_stars>100-1000
# Copyright 2017-2019 <NAME>, <NAME>, <NAME>
# Copyright 2019-2020 Intel Corporation
#
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Fuzz inputs are managed as nodes in a queue. Any persistent metadata is stored here as node attributes.
"""
import lz4.frame
import ... | StarcoderdataPython |
3217874 | import pybamm
import unittest
import numpy as np
class TestQuickPlot(unittest.TestCase):
def test_simple_ode_model(self):
model = pybamm.lithium_ion.BaseModel(name="Simple ODE Model")
whole_cell = ["negative electrode", "separator", "positive electrode"]
# Create variables: domain is expl... | StarcoderdataPython |
3224757 | <filename>gsoc/anand/pipeline_3/utility/vocab_extractor_from_model/embedding_extractor.py
from __future__ import print_function
import tensorflow as tf
import numpy as np
"""
- The following code when run with proper model location is capable of extracting the trained embeddings of a given model.
- The embeddings are p... | StarcoderdataPython |
3283130 | <filename>noxfile.py<gh_stars>1-10
import nox
@nox.session
def lint(session):
session.install('pytest>=5.3.5', 'setuptools>=45.2',
'wheel>=0.34.2', 'flake8>=3.7.9',
'numpy==1.18.1', 'pandas==1.1.4')
session.install('.')
session.run('flake8', 'sklearn_pandas/', 'tests... | StarcoderdataPython |
1687084 | import os
API_KEY = os.environ['DATA_GOV_API_KEY']
CURR_PATH = os.getcwd()
RAW_PATH = os.path.join(CURR_PATH, 'raw')
if not os.path.exists(RAW_PATH):
os.mkdir(RAW_PATH)
MIN_YEAR = 1985
MAX_YEAR = 2018
MAX_WORKERS = 2
# URLS
ORI_URL = f'https://api.usa.gov/crime/fbi/sapi/api/agencies?api_key={API_KEY}'
# Col... | StarcoderdataPython |
4813572 | <gh_stars>0
from pytorchisland import *
| StarcoderdataPython |
129146 | <gh_stars>0
from unittest import TestCase
from afrigis.url_creator import create_full_url
class TestUrlCreator(TestCase):
def setUp(self):
pass
def test_url_creator_returns_correct_url(self):
# Pre-generated url for testing purposes
correct_url = 'http://example.rest/api/service.stu... | StarcoderdataPython |
3359577 | <filename>windyquery/tests/test_delete.py<gh_stars>10-100
import asyncio
from windyquery import DB
loop = asyncio.get_event_loop()
def test_delete(db: DB):
rows = loop.run_until_complete(db.table('users').insert(
{'email': '<EMAIL>', 'password': '<PASSWORD>'}).returning())
assert rows[0]['email'] ==... | StarcoderdataPython |
176999 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.CreateModel(
name... | StarcoderdataPython |
4827916 | <gh_stars>10-100
import copy
import pathlib
import sys
from typing import Any
from typing import Optional
import attr
from sqlalchemy.engine import Engine
import toml
from .types.namespace import namespace
from .utils.cast import CastError
from .utils.cast import cast
DEFAULT = {
'DEBUG': False,
'RECEIVE_... | StarcoderdataPython |
3286122 | <reponame>kjappelbaum/pymatgen
#!/usr/bin/env python
__author__ = "waroquiers"
import json
import os
import shutil
import unittest
import numpy as np
from pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies import (
AngleNbSetWeight,
CNBiasNbSetWeight,
DeltaCSMNbSetWeight,
Distan... | StarcoderdataPython |
67756 | import logging
from simuvex.s_format import FormatParser
l = logging.getLogger("simuvex.procedures.snprintf")
######################################
# snprintf
######################################
class snprintf(FormatParser):
def run(self, dst_ptr, size): # pylint:disable=arguments-differ,unused-argument
... | StarcoderdataPython |
120739 | <filename>biomagicbox/expasy.py<gh_stars>0
import requests
import re,os,sqlite3
import threading
class ProtParam():
def __init__(self,dbname,tablename):
self.dbname=dbname
self.tablename=tablename
self.finish_num=0
self.url='https://web.expasy.org/cgi-bin/protparam/protparam'
... | StarcoderdataPython |
16389 | <reponame>ngupta23/more
# For Time Logging
import time
from contextlib import contextmanager
import logging
@contextmanager
# Timing Function
def time_usage(name=""):
"""
log the time usage in a code block
"""
# print ("In time_usage runID = {}".format(runID))
start = time.time()
yield
end... | StarcoderdataPython |
4804865 | from torch.utils.data import Dataset
import torch
import os
class HANDataset(Dataset):
"""
A PyTorch Dataset class to be used in a PyTorch DataLoader to create batches.
"""
def __init__(self, data_folder, split):
"""
:param data_folder: folder where data files are stored
:param... | StarcoderdataPython |
3247878 | <gh_stars>1-10
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
"""Utilities to train a surrogate model from teacher."""
import numpy as np
from scipy.sparse import issparse, isspmatrix_c... | StarcoderdataPython |
3269537 | <reponame>HoboJoe2/rps101
class Weapon():
def __init__(self, **kwargs):
self.__dict__.update(**kwargs)
| StarcoderdataPython |
15891 | <filename>lang/Python/terminal-control-cursor-positioning-1.py
print("\033[6;3HHello")
| StarcoderdataPython |
3238023 | import urllib2
import json
import interface
class Poloniex(interface.MarketExplorer):
def __init__(self):
pass
def exchange_name(self):
return 'poloniex'
def markets(self):
req = urllib2.urlopen('https://poloniex.com/public?command=returnTicker')
js = json.loads(req.read(... | StarcoderdataPython |
157014 | import logging
import time
import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
from tweets_crawler import db as DB
def doSummary(candidates):
while True:
msg = "\nSummary:\n"
db = DB.DB()
total = 0
for cand in candidates:
cand = cand.strip()
... | StarcoderdataPython |
3232023 | <filename>pupper/ServoCalibration.py
# WARNING: This file is machine generated. Edit at your own risk.
import numpy as np
MICROS_PER_RAD = 11.333 * 180.0 / np.pi
NEUTRAL_ANGLE_DEGREES = np.array(
[[ 0., 0., 0., 0.],
[ 45., 45., 45., 45.],
[-45.,-45.,-45.,-45.]]
)
| StarcoderdataPython |
3347937 | <reponame>T4rk1n/precept
import pytest
from precept import ImmutableDict
from precept.errors import ImmutableError
def test_immutable_dict():
data = ImmutableDict(foo='bar', bar='foo', n=1)
assert 'foo' in data
assert data.get('bar') == 'foo'
assert data.foo == 'bar'
assert data['n'] == 1
ass... | StarcoderdataPython |
1725447 | <filename>starter/starter_PubRouterDeposit.py
import json
from starter.starter_helper import NullRequiredDataException
from starter.objects import Starter, default_workflow_params
from provider import utils
"""
Amazon SWF PubRouterDeposit starter
"""
class starter_PubRouterDeposit(Starter):
def __init__(self, se... | StarcoderdataPython |
1601795 | <filename>BACKEND_POC/app/migrations/0001_initial.py<gh_stars>1-10
# Generated by Django 3.1.1 on 2020-09-17 09:41
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Cr... | StarcoderdataPython |
3281944 | <reponame>DaeunYim/pgtoolsservice
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ----------------------------------... | StarcoderdataPython |
131123 | <reponame>theodumont/pytorch-lightning
# Copyright The PyTorch Lightning team.
#
# 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 re... | StarcoderdataPython |
3372893 |
from pycket import config
if config.hidden_classes:
from pycket.impersonators.hidden_classes import *
else:
from pycket.impersonators.baseline import *
| StarcoderdataPython |
3332025 | from output.models.nist_data.atomic.int_pkg.schema_instance.nistschema_sv_iv_atomic_int_max_exclusive_1_xsd.nistschema_sv_iv_atomic_int_max_exclusive_1 import NistschemaSvIvAtomicIntMaxExclusive1
__all__ = [
"NistschemaSvIvAtomicIntMaxExclusive1",
]
| StarcoderdataPython |
3279887 | <reponame>hritools/text-to-speech<gh_stars>0
import setuptools
VERSION = '0.1'
with open('README.md', 'r') as f:
long_description = f.read()
with open('requirements.txt') as f:
required = f.read().splitlines()
setuptools.setup(
name='TextToSpeech-Ru',
python_requires='~=3.7',
version=VERSION... | StarcoderdataPython |
1677211 | <filename>packages/mccomponents/python/mccomponents/sample/DebyeTemp.py
# -*- Python -*-
"""
Debye temperature of elements
"""
def getT(element, default=None):
return table.get(element, default)
table = dict(
Li=344, Be=1440, C=2230, Ne=75,
Na=158, Mg=400, Al=428, Si=645, Ar=92,
K=91, Ca=230, Sc=360... | StarcoderdataPython |
3218831 | <reponame>UrbanDave/core
"""Test for Sensibo component Init."""
from __future__ import annotations
from unittest.mock import patch
from homeassistant import config_entries
from homeassistant.components.sensibo.const import DOMAIN
from homeassistant.components.sensibo.util import NoUsernameError
from homeassistant.con... | StarcoderdataPython |
135281 | # uncompyle6 version 3.5.0
# Python bytecode 2.7
# Decompiled from: Python 2.7.17 (default, Oct 23 2019, 08:25:46)
# [GCC 4.2.1 Compatible Android (5220042 based on r346389c) Clang 8.0.7 (https://
# Embedded file name: <JustAHacker>
whoknow = 'ohiabuebmpoeomqk'
import os, sys, time, datetime, random, hashlib, re, thre... | StarcoderdataPython |
3214674 | import torch
import os
import numpy as np
import cv2
from PIL import Image
from csr_model import csr_network
import torchvision.transforms.functional as TF
import matplotlib.pyplot as plt
def csr_retouch(path_to_model_state, path_to_old_images, path_to_new_images):
cuda = torch.cuda.is_available()
Tensor = to... | StarcoderdataPython |
1630949 | # Generated by Django 2.2 on 2021-04-06 12:58
from django.db import migrations
def add_priorities(apps, schema_editor):
Priority = apps.get_model("todolist_app", "Priority")
data = [
('Critical', 1),
('High', 2),
('Medium', 3),
('Low', 4),
('Trivial', 5),
]
for... | StarcoderdataPython |
3335012 | <gh_stars>0
from utah import Utah
from mesowest import MesoWest
import pandas as pd
from datetime import datetime as dt
state_sensors = Utah.request_data()
import os
outdir = './data'
if not os.path.exists(outdir):
os.mkdir(outdir)
for i in list(state_sensors.keys()):
dict = {}
outname = "sensors_{}.csv"... | StarcoderdataPython |
1790156 | <gh_stars>1-10
import pytest
from meltano.core.db import project_engine
from meltano.api.models import db
class TestApp:
@pytest.fixture
def session(self):
# disable the `session` fixture not to override
# the `db.session`
pass
def test_core_registered(self, engine_sessionmaker, a... | StarcoderdataPython |
3365634 | from sqlalchemy import Column, Integer, String, Text, DateTime, Float, Boolean, PickleType
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class SubCategory(Base):
'''This is SubCategory sample Data model class.'''
__tablename__ = "tSubCategories"
__table_args__ = {"... | StarcoderdataPython |
1671476 | <gh_stars>1-10
#!/usr/bin/python
# Copyright (C) International Business Machines Corp., 2005
# Author: <NAME> <<EMAIL>>
# Negative Test: attempt list of non-existent domain
... | StarcoderdataPython |
1631363 | from lib.pyapp import Pyapp
from lib.appController import drivers_queue
from conf.settings import logger
import threading
local = threading.local()
class BasePage():
def __init__(self,driver=None):
if not driver:
try:
local.driver = drivers_queue.get()
local.py... | StarcoderdataPython |
3331506 | <gh_stars>0
# Generated by Django 2.0.8 on 2018-09-06 14:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fullcalendar', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='calendarevent',
name='... | StarcoderdataPython |
1679334 | <reponame>timgates42/balanced-python
import balanced
balanced.configure('<KEY>')
accounts = balanced.Account.query | StarcoderdataPython |
1719734 | """ Tests for filter query builder """
import unittest
from werkzeug.datastructures import ImmutableMultiDict
from app.builders.filter_query_builder import FilterQueryBuilder
class FilterQueryBuilderTestCase(unittest.TestCase):
def test_build_with_null_arguments_return_empty_filters(self):
# arrange
... | StarcoderdataPython |
1664079 | <reponame>samlet/stack
import json
import graphene
from sagas.ofbiz.schema_queries_g import *
from sagas.ofbiz.schema_mutations_g import Mutations
from py4j.java_gateway import java_import
from sagas.ofbiz.runtime_context import platform
oc = platform.oc
finder = platform.finder
helper = platform.helper
java_import(... | StarcoderdataPython |
3342013 | import datetime
from mongoengine import StringField, DictField, DateTimeField, Document, BooleanField, IntField
class ValidationStatus(object):
NEW = "New"
IN_PROGRESS = "In progress"
CANCELATION_IN_PROGRESS = "Cancelation in progress"
CANCELED = "Canceled"
APPROVED = "Approved"
REJECTED = "R... | StarcoderdataPython |
3318572 | <reponame>clouserw/olympia
import logging
from django.conf import settings
from django.db import models
import amo.models
log = logging.getLogger('z.perf')
class PerformanceAppVersions(amo.models.ModelBase):
"""
Add-on performance appversions. This table is pretty much the same as
`appversions` but i... | StarcoderdataPython |
104805 | try:
from conf import Conf
except ImportError:
from ..conf import Conf
import os
def setup_fixture():
# Clean the map db from MongoDb
if Conf.Instance().APP_MODE == "Test_Aws":
os.system('service mongod stop')
os.system('rm -Rf /data-mongodb/rs0-1/*')
os.system('rm -Rf /data-m... | StarcoderdataPython |
1789331 | <gh_stars>1-10
import binascii
import pprint
import sys
from hmac_drbg import *
def parse_entry(line):
key, val = line.split('=')
key = key.strip()
val = val.strip()
if val == 'True':
val = True
elif val == 'False':
val = False
elif val.isdigit():
val = int(val)
ret... | StarcoderdataPython |
1786259 | <reponame>lwerdna/keypatch_binja<gh_stars>1-10
try:
from binaryninjaui import (UIAction, UIActionHandler, Menu)
from . import keypatch
UIAction.registerAction("KEYPATCH")
UIActionHandler.globalActions().bindAction("KEYPATCH", UIAction(keypatch.launch_keypatch))
Menu.mainMenu("Tools").addAction("KEYPATCH", "KEYPA... | StarcoderdataPython |
1783158 | <reponame>pmathewjacob/insightface-attendance
import tensorflow as tf
__weights_dict = dict()
is_train = False
def load_weights(weight_file):
import numpy as np
if weight_file == None:
return
try:
weights_dict = np.load(weight_file).item()
except:
weights_dict = np.load(weig... | StarcoderdataPython |
1673447 | # age: int
# name: str
# height: float
# is_human: bool
def police_check(age: int) -> bool:
if age > 18:
can_drive = True
else:
can_drive = False
return "string"
if police_check("twelve"):
print("You may pass.")
else:
print("Pay a fine.") | StarcoderdataPython |
182470 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
requires = [
'awscli>=1.16.211',
'boto3>=1.9.200',
'click>=7.1.1',
'pytest>=3.5.1',
'requests>=2.23.0',
'tabulate>=0.8.7'
]
setuptools.setup(
name="undmainchain",
packages=['undmainchain'],
versi... | StarcoderdataPython |
162014 | <filename>uta_rest/django_secret_key.py<gh_stars>1-10
import os
import random
from base64 import urlsafe_b64encode as b64encode
random.seed()
def generate_key(max_length, seed_length):
"""
Generate a Base64-encoded 'random' key by hashing the data.
data is a tuple of seeding values. Pass arbitrary encode... | StarcoderdataPython |
80583 | from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import os
class Memory(object):
"""
An implementation of the replay memory. This is essential when dealing with DRL algorithms that are not
multi-threaded as in A3C.
"""
... | StarcoderdataPython |
73494 | from ..ops import *
class Translator(object):
"""
A translator wraps a physical operator and provides the compilation logic.
It follows the producer/consumer model.
It also contains information about the lineage it needs to capture.
"""
_id = 0
def __init__(self, op):
self.id = Translator._id
T... | StarcoderdataPython |
199596 | # Conway's game of life
# uses pygamezero frame work
#
# See key event at end for commands
#
import random
ROWS = 50
COLS = 70
CELL_SIZE = 10
HEIGHT = (ROWS * CELL_SIZE)
WIDTH = (COLS * CELL_SIZE)
BACK_COLOR = (0, 0, 127)
CELL_COLOR = (0, 200, 0)
g_changed = False
g_running = True
g_step = False
def grid_build(row... | StarcoderdataPython |
3311049 | #!/usr/bin/python3
# music_blueprint.py
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import youtube_dl
from auth import authenticate
from errors_blueprint import *
from config import MUSIC_LOCATION
from flask import Blueprint, render_template, safe_join, request, re... | StarcoderdataPython |
176715 | <reponame>specialforcea/labscript_suite
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'chipfpga.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
excep... | StarcoderdataPython |
1653285 | import json
import boto3
from time import sleep
from itertools import chain
client = boto3.client('ec2')
def list_instances(tags=None):
if tags is not None:
response = client.describe_instances(
Filters=[
{
'Name': 'tag:SubSystem',
'Value... | StarcoderdataPython |
1737011 | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | StarcoderdataPython |
1674168 | <gh_stars>0
import subprocess
import pytest
import virtualenv
from editables import build_editable
def make_venv(name):
return virtualenv.cli_run([str(name), "--without-pip"])
def run(*args):
return subprocess.run(
[str(a) for a in args],
stdout=subprocess.PIPE,
stderr=subprocess.P... | StarcoderdataPython |
112843 | <filename>rnaindel/analysis/preprocessor.py
import os
import csv
import pysam
import pandas as pd
from functools import partial
from multiprocessing import Pool
from indelpost import Variant, VariantAlignment
from .callset_formatter import format_callset
from .coding_indel import annotate_coding_info
from .transcript... | StarcoderdataPython |
1759731 | <reponame>Sokrates80/air-py
"""
airPy is a flight controller based on pyboard and written in micropython.
The MIT License (MIT)
Copyright (c) 2016 <NAME>, <EMAIL>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
i... | StarcoderdataPython |
4830297 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette.by import By
from gaiatest import GaiaTestCase
from gaiatest.apps.homescreen.app import Homescreen
MAN... | StarcoderdataPython |
150464 | #!/usr/bin/env python3
import sys
import click
import check_entry_mariadb
import delete_old_entries
import detect_ldap_problems
import fix_wrong_format
import update_password_fields
import delete_userpassword_cram
from config_loader import load_config
from common import LOGGER
@click.group()
def cli():
"""CLI ... | StarcoderdataPython |
85964 | <reponame>Cray-HPE/hms-capmc<filename>test/python/test_getXnameStatusByCLIBad.py
#!/usr/bin/python3
# MIT License
#
# (C) Copyright [2019-2021] Hewlett Packard Enterprise Development LP
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation f... | StarcoderdataPython |
3223272 | """Example of using a custom model with batch norm."""
import argparse
import ray
from ray import tune
from ray.rllib.models import ModelCatalog
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.utils... | StarcoderdataPython |
1729790 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-07-19 01:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webapp', '0002_auto_20160719_0131'),
]
operations = [
migrations.CreateModel... | StarcoderdataPython |
3312863 | #
# Code by <NAME> and under the MIT license
#
#
# python grenade.py [speed [gravity]]
#
# Throws a grenade with the specified speed in m/s (default: 15) and specified
# gravitational acceleration (default: earth) in m/s^2 or given by listing a planet,
# sun, moon or pluto.
#
from mine import *
from vehi... | StarcoderdataPython |
1713003 | from PyQt4 import QtGui
import sys
from views import base
class ExampleApp(QtGui.QMainWindow, base.Ui_MainWindow):
def __init__(self, parent=None):
super(ExampleApp, self).__init__(parent)
self.setupUi(self)
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show... | StarcoderdataPython |
1640440 | from django.test import SimpleTestCase
from cpu.random import Random
from game.transforms import Board
def sample_input():
return [
'x', 'x', ' ',
'o', ' ', ' ',
'o', ' ', 'x',
]
class RandomAiTest(SimpleTestCase):
def test_picks_random(self):
data = sample_input()
... | StarcoderdataPython |
3382818 | """example URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... | StarcoderdataPython |
4809366 | #!/usr/bin/env python
# encoding: utf-8
"""
first_level_control.py
If used, please cite:
<NAME>., <NAME>., <NAME>. & <NAME>.
Task-evoked pupil responses reflect internal belief states. Scientific Reports 8, 13702 (2018).
"""
import os, sys, datetime
import subprocess, logging
import scipy as sp
import scipy.stats as... | StarcoderdataPython |
119269 | <filename>confused_stud/trash.py
# NOTE this is what they did for the students dataset
# Some nonsense to help you select features that will best predict the label
# y=pd.get_dummies(df['user-definedlabeln'])
# mi_score=mutual_info_classif(df.drop('user-definedlabeln',axis=1),df['user-definedlabeln'])
# mi_score=pd.Se... | StarcoderdataPython |
184565 | from tr import tr
with open('ciphertext.txt') as file:
data = file.read()
alpha = {
'a': 0,
'b': 0,
'c': 0,
'd': 0,
'e': 0,
'f': 0,
'g': 0,
'h': 0,
'i': 0,
'j': 0,
'k': 0,
'l': 0,
'm': 0,
'n': 0,
'o': 0,
'p': 0,
'q': 0,
'r': 0,
's': 0,
... | StarcoderdataPython |
3260662 | from typing import List
from xml.etree import ElementTree
import requests
import config
def section_create(section: str) -> None:
address = config.PLEX_SERVER_ADDRESS + '/library/sections'
headers = {
'X-Plex-Token': config.PLEX_TOKEN,
}
params = {
'name': section,
... | StarcoderdataPython |
88937 | <filename>tools/mergeneighboursinlabelimage/mergeneighboursinlabelimage.py
import argparse
import sys
import skimage.io
import skimage.util
from skimage.measure import regionprops
import scipy.spatial.distance
import numpy as np
import warnings
def merge_n(img, dist=50):
props = regionprops(img)
found = False... | StarcoderdataPython |
150775 | <reponame>solider245/OpenData
# encoding: UTF-8
def remove_chinese(str):
s = ""
for w in str:
if w >= u'\u4e00' and w <= u'\u9fa5':
continue
s += w
return s
def remove_non_numerical(s):
f = ''
for i in range(len(s)):
try:
f = float(s[:i+1])
e... | StarcoderdataPython |
138580 | #
# SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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... | StarcoderdataPython |
1615693 | """
Entities containing shapes
.. automodule:: ote_sdk.entities.shapes.rectangle
:members:
:undoc-members:
.. automodule:: ote_sdk.entities.shapes.circle
:members:
:undoc-members:
.. automodule:: ote_sdk.entities.shapes.polygon
:members:
:undoc-members:
.. automodule:: ote_sdk.entities.shapes.shap... | StarcoderdataPython |
135234 | #------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.