id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3301262 | #!/usr/local/bin/python3
###!/Users/zhiyang/anaconda3/bin/python3
"""
This is written by <NAME> to test the automatically generated
filename to store experimental data/results from running
experiments/simulations, and/or automated software regression
testing and hardware regression verification.
Synopsis:
... | StarcoderdataPython |
1770283 | from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func
# Database user model
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(150), unique=True)
username = db.Column(db.String(150), unique=True)
password = d... | StarcoderdataPython |
1620032 | <reponame>hydroshare/hydroshare
from rest_framework.decorators import api_view
from rest_framework.views import APIView
from rest_framework.response import Response
from theme.models import UserProfile
class UserInfo(APIView):
def get(self, request):
if not request.user.is_authenticated():
re... | StarcoderdataPython |
1672820 | from __future__ import absolute_import
from __future__ import unicode_literals
# -*- coding: utf-8 -*-
from django.conf import settings as django_settings
SLUG = 'macros'
APP_LABEL = 'wiki'
METHODS = getattr(
django_settings,
'WIKI_PLUGINS_METHODS',
('article_list',
'toc',
))
| StarcoderdataPython |
184168 | <filename>fun_network.py
import h5py
import numpy as np
import tensorflow as tf
print(tf.version.VERSION)
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_process_gpu_memory_fraction = 0.7
sess= tf.compat.v1.Session(config=config)
import tensorflow.keras as keras
imp... | StarcoderdataPython |
3267778 |
class WayRelationIndex():
"""
A class containing an index of WayRelations by node ids of internal nodes and edge nodes.
"""
def __init__(self, way_relations):
self._edge_nodes_index_dict = {}
self._full_nodes_index_dict = {}
for wr in way_relations:
self.add(wr)
def add(self, way_relatio... | StarcoderdataPython |
1786346 | import click
import beersmith
import pathlib
def lbs_oz(ozs):
return divmod(ozs, 16)
@click.command(help="beersmith dump command, dump grain and hop")
@click.option(
"-f",
"--file",
default="/Users/pquiring/Documents/BeerSmith2/Recipe.bsmx",
help="path name to recipe file",
)
@click.option("-n",... | StarcoderdataPython |
1780305 | """ Dictionary-to-filetree functions, to create test files for testing.
http://nedbatchelder.com/code/cog
Copyright 2004-2012, <NAME>.
"""
from __future__ import absolute_import
import os.path
from .whiteutils import reindentBlock
from .backward import string_types, bytes_types
__version__ = '1.0.20040126'
_... | StarcoderdataPython |
3391721 | """
Created on Wed October 15 2020
@author: <NAME>
GitHub username: esgomezm
"""
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, MaxPooling2D, Dropout, UpSampling2D, Activation, Concatenate
from tensorflow.keras.losses import Spar... | StarcoderdataPython |
77767 | <reponame>madmis/wexapi<gh_stars>1-10
#!/usr/bin/env python
import wexapi
attrs = ('high', 'low', 'avg', 'vol', 'vol_cur', 'last', 'buy', 'sell', 'updated')
print("Tickers:")
connection = wexapi.common.WexConnection()
info = wexapi.public.InfoApi(connection)
api = wexapi.public.PublicApi(connection)
for pair in info.... | StarcoderdataPython |
149133 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="pyske",
version="0.5",
author="<NAME>",
author_email="<EMAIL>",
description="The Python Skeleton Library",
long_description=long_description,
long_description_con... | StarcoderdataPython |
3215383 | <filename>examples/glyph-alpha.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011-2015 <NAME>
# Distributed under the terms of the new BSD license.
#
# ------------------------------------... | StarcoderdataPython |
1710475 | <reponame>aida-ugent/FIPR<filename>src/utils/data_split_util.py
import numpy as np
import networkx as nx
from scipy.sparse import triu, tril
from scipy.sparse.csgraph import depth_first_tree
# TODO: some optimisations may be possible now that nodes are always integer-indexed.
def leave_fraction_out(data, test_set_f... | StarcoderdataPython |
31338 | from django.apps import AppConfig
class SentryConfig(AppConfig):
name = 'sentry'
| StarcoderdataPython |
149173 | # -*- coding: utf-8 -*-
""" ラベルを定義 """
NAME = "name"
MYNAME = "myname"
| StarcoderdataPython |
84835 | <gh_stars>1-10
import numpy as np
from pokerl import Game, eval_hand
from pokerl.envs import PokerGameEnv
from pokerl.agents import RandomAgent
from pokerl.enums import PokerMoves, HandRanking
# Set numpy print options
np.set_printoptions(precision=3, suppress=True, linewidth=np.inf)
# Define the softmax function
def... | StarcoderdataPython |
1778025 | <gh_stars>0
from .. import db
from datetime import datetime
from flask_security import UserMixin
from flask_security import RoleMixin | StarcoderdataPython |
3206006 | import pytest
from doltpy.etl.sql_sync.tests.helpers.tools import validate_get_target_writer, validate_drop_primary_keys
from doltpy.etl.sql_sync.oracle import get_target_writer
@pytest.mark.sql_sync
def test_write_to_table(oracle_with_table):
engine, table = oracle_with_table
validate_get_target_writer(engin... | StarcoderdataPython |
1724845 | <reponame>eande-jasonc1025/RoboQuest-RnD-FlaskVideoStream_MiguelGrinberg_GpioZero-RPi
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# jwc from: ~/01-Jwc/03t-StsPilot-MarkOrion/STS-PiLot
"""
Created on Wed Mar 15 11:56:25 2017
@author: <NAME>
"""
import explorerhat as xhat
explorerhat = True
# Inputs: Digital
de... | StarcoderdataPython |
1603114 | <reponame>wanguinjoka/The-Gram
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name =... | StarcoderdataPython |
114877 | <reponame>nsankar/AutoTS<filename>autots/datasets/_base.py
"""Loading example datasets."""
from os.path import dirname, join
import pandas as pd
def load_daily(long: bool = True):
"""2020 Covid, Air Pollution, and Economic Data.
Sources: Covid Tracking Project, EPA, and FRED
Args:
long (bool): i... | StarcoderdataPython |
3239830 | import os
import torch
from collections import OrderedDict
class BaseModel():
def name(self):
return 'BaseModel'
def initialize(self, opt):
self.opt = opt
self.gpu_ids = opt.gpu_ids
self.isTrain = opt.isTrain
self.Tensor = torch.cuda.FloatTensor if self.gpu_ids else to... | StarcoderdataPython |
1741083 | <filename>server.py
#!/usr/bin/env python
# coding:utf-8
import socket
import struct
import sys
from collections import namedtuple
FullCone = "Full Cone" # 0
RestrictNAT = "Restrict NAT" # 1
RestrictPortNAT = "Restrict Port NAT" # 2
SymmetricNAT = "Symmetric NAT" # 3
UnknownNAT = "Unknown NAT" # 4
NATTYPE = (FullCo... | StarcoderdataPython |
179554 | <reponame>bergmannf/org-foundry-sync
#!/usr/bin/env python3
import dataclasses
from enum import Enum
import glob
import json
import logging
import pathlib
import re
import os
from typing import Any, Dict, Optional, List, Union, Tuple
from playwright.async_api import Browser
import pypandoc
logger = logging.getLogger... | StarcoderdataPython |
1745731 | # Imports
import sqlite3
import os
import pandas as pd
import numpy as np
# Create filepath to csv file
DATABASE_FILEPATH = os.path.join(os.path.dirname(__file__), "buddymove_holidayiq.csv")
# Read in csv file to dataframe
place_review_df = pd.read_csv(DATABASE_FILEPATH)
# Basic dataframe exploration
print(place_rev... | StarcoderdataPython |
3386775 | <reponame>wdempsey/sense2stop-lvm
# %%
import numpy as np
# %%
class Tree:
def __init__(self, data = None):
self.data = data
def GrowTree(self, depth):
if depth==1:
self.data = list([0,1])
return self
elif depth > 1:
curr_level = 1
s... | StarcoderdataPython |
4838316 | import re
from botoy import GroupMsg, S
from botoy import async_decorators as deco
__doc__ = """把B站小程序转成链接"""
dont_Send_miniProgram_Base64PIC = r"""
<KEY>
UUUBRRRQFFFFAUUUUBRRRQFFFFAUUUUBRRRQFFFFAUUUUBRRRQFFFFAUUUUBRRRQFFFFAUUUUBRR
RQFFFFAUUUUH/9k=
"""
@deco.ignore_botself
@deco.these_msgtypes("XmlMsg")
async def ... | StarcoderdataPython |
3209932 | """
The :mod:`paddy.exceptions` module contains the error classes
and custom warning messages used in paddy.
"""
# Authors: <NAME> & <NAME>
# License: BSD
RANGE_LIMIT_ERROR = 'param_range values must be within defined limits'
EQUAL_LIMIT_ERROR = 'limits cannot be equal to eachother'
LIMIT_ORDER_ERROR = 'limits mus... | StarcoderdataPython |
1666046 | <gh_stars>100-1000
from argparse import Namespace
import torch
import numpy as np
import cv2
from third_party.caps.CAPS.network import CAPSNet
from immatch.utils.data_io import load_im_tensor
from .base import FeatureDetection, Matching
from .superpoint import SuperPoint
from .sift import SIFT
class CAPS(FeatureDetec... | StarcoderdataPython |
1636346 | <gh_stars>0
"""Module to validate for json request"""
from functools import wraps
from flask import request
from src.utilities.messages.error_messages import serialization_errors
def validate_json_request(func):
"""Decorator function to check for json content type in request"""
@wraps(func)
def decorate... | StarcoderdataPython |
4802754 | <reponame>BaptisteRubino/profit
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 4 08:34:52 2019
@author: <NAME>
"""
import numpy as np
def shape():
return 1
def get_output():
data = np.loadtxt('mockup.out')
return data
| StarcoderdataPython |
3321709 | # -*- coding: utf-8 -*-
# This script modifies indexes from mirdata <= 0.3.0b0 to support versions, and to check integrity of
# tracks, multitracks, metadata and tables. The structure of indexes will now be:
#
# index = {
# 'version': ...,
# 'tracks': {
# ...
# },
# 'records': {
# ...
# },
... | StarcoderdataPython |
42075 | <reponame>jcwon0/BlurHPE
import torch
from mmpose.models.backbones import AlexNet
def test_alexnet_backbone():
"""Test alexnet backbone."""
model = AlexNet(-1)
model.train()
imgs = torch.randn(1, 3, 256, 192)
feat = model(imgs)
assert feat.shape == (1, 256, 7, 5)
model = A... | StarcoderdataPython |
1649951 | <filename>src-py2/money/tests/__init__.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Money unittests
Run with:
$ python -m unittest
""" | StarcoderdataPython |
155473 | from invoke import task
@task()
def precommit(c):
format(c)
test(c)
@task()
def format(c):
c.run("black src tests setup.py tasks.py")
@task()
def test(c):
c.run("pytest tests")
c.run("pytest --nbval-lax notebooks/*.ipynb")
| StarcoderdataPython |
5372 | <gh_stars>0
# Copyright 2021 MosaicML. All Rights Reserved.
"""Performance profiling tools.
The profiler gathers performance metrics during a training run that can be used to diagnose bottlenecks and
facilitate model development.
The metrics gathered include:
* Duration of each :class:`.Event` during training
* Tim... | StarcoderdataPython |
3308079 | import re as _re
from mp.core.expression import Expression as Exp
class EventUnit:
def __init__(self, event_name: str, method, unique, fixed, hidden, is_regex: bool = False):
self._event_name = event_name
self._event_name_compiled = _re.compile(self._event_name) if is_regex else None
self... | StarcoderdataPython |
1720535 | """Dataset class handler for TREC Relevancy 2010 data."""
import os
import pandas as pd
from psych_metric.datasets.base_dataset import BaseDataset
try:
ROOT = os.environ['ROOT']
HERE = os.path.join(ROOT, 'psych_metric/datasets/trec_relevancy_2010/trec_relevancy_2010_data/')
except:
HERE = None
class TRE... | StarcoderdataPython |
3267820 | # AUTOGENERATED! DO NOT EDIT! File to edit: data_helper.ipynb (unless otherwise specified).
__all__ = ['download_data_files']
# Cell
import logging
from google_drive_downloader import GoogleDriveDownloader as gdd
def download_data_files(data_dir : str = "data", overwrite=False, progbar=True, use_int32=True):
"""
... | StarcoderdataPython |
138237 | import argparse
import sys
def get_args():
parser = argparse.ArgumentParser('Interface for Inductive Dynamic Representation Learning for Link Prediction on Temporal Graphs')
# select dataset and training mode
parser.add_argument('-d', '--data', type=str, help='data sources to use, try wikipedia or reddit',
... | StarcoderdataPython |
1797316 | # coding: utf-8
from django.conf.urls import url
from tests.views import ViewFabric
def get_test_urlpatterns():
url_list, urlpatterns = [], []
for idx, (view, _) in enumerate(ViewFabric()):
url_part = r'^test_view_{0}'.format(idx)
url_name = url_part.strip('^')
urlpatterns.append(ur... | StarcoderdataPython |
60064 | import subprocess
import json
import os
import csv
import numpy as np
import pandas as pd
import pysam
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
def get_orf(input_genome, output_genome, orf):
orf = int(orf)
record = SeqIO.read(input_genome, 'fasta')
record.seq = re... | StarcoderdataPython |
1790793 | <reponame>paulbodean88/qa-chatbot
"""
Parser of the standard startup file and also of the aiml ones
"""
import xml.etree.ElementTree as ET
import os
class AIMLParser:
def __init__(self):
self._public_path = os.getcwd().split("src")[0] + "/public/"
def get_root(self, file_name):
tree = ET.par... | StarcoderdataPython |
3394353 | from .ad import Ad
from .filter import Filter
| StarcoderdataPython |
1633702 | <filename>purchasing/users/forms.py
# -*- coding: utf-8 -*-
import re
from flask_wtf import FlaskForm
from wtforms.fields import TextField
from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField
from purchasing.users.models import Department
from flask_security.forms import RegisterForm
f... | StarcoderdataPython |
1679232 | <filename>acceptance/python/src/test_multiple_owners.py
# Copyright © 2020 Interplanetary Database Association e.V.,
# Planetmint and IPDB software contributors.
# SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
# Code is Apache-2.0 and docs are CC-BY-4.0
# # Multiple owners integration testing
# This test checks ... | StarcoderdataPython |
162448 | from datetime import date, datetime
from django.test import TestCase, RequestFactory
from django.utils import timezone
from example.views.views import ListDataModelView
from example.views.models import ListData
class TestViewSet(TestCase):
def setUp(self):
pass
def test_viewset_urls(self):
... | StarcoderdataPython |
64491 | path = input().split("\\")
file = path[-1].split(".")
print(f"File name: {file[0]}\nFile extension: {file[1]}")
| StarcoderdataPython |
3264172 | # Bep Marketplace ELE
# Copyright (c) 2016-2021 Kolibri Solutions
# License: See LICENSE file or https://github.com/KolibriSolutions/BepMarketplace/blob/master/LICENSE
#
from django import forms
from templates import widgets
class AutomaticDistributionOptionForm(forms.Form):
"""
Form to set options for aut... | StarcoderdataPython |
1740271 | <reponame>CncealDVRflectN/vuabl
import pkg_resources
def get_version() -> str:
return pkg_resources.get_distribution("vuabl").version
| StarcoderdataPython |
3205079 | <reponame>rystrauss/advent-of-code
def padded_binary(num, length=36):
binary_value = bin(num).removeprefix("0b")
return "0" * (length - len(binary_value)) + binary_value
class Memory:
def __init__(self):
self._mask = "X" * 36
self._data = dict()
def __setitem__(self, key, value):
... | StarcoderdataPython |
3257699 | # -*- coding: utf-8 -*-
import logging
import os
import random
import math
from environment import WebBotEnv, Utils
# Hill climbing algorithm
class HillClimbing:
def __init__(self, n_episodes=100, data_dir=None, log_dir=None, model_dir=None, **kwargs):
self.logger = logging.getLogger("HillCli... | StarcoderdataPython |
3388563 | <gh_stars>0
from aocd import data
from aoc.utils import rows
DIRECTIONS = {'E': (1, 0), "S": (0, 1), "W": (-1, 0), "N": (0, -1)}
class Ship:
def __init__(self):
self.x, self.y = (0, 0)
self.direction = 'E'
def run(self):
for row in rows(data):
instruction = row[0]
... | StarcoderdataPython |
1766560 | <reponame>helderlgoliveira/controle-colaboradores-api<gh_stars>1-10
# Generated by Django 3.2.7 on 2021-10-16 22:36
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('per... | StarcoderdataPython |
43136 | import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Input, Dense, Flatten, Conv2D, BatchNormalization, Lambda, Concatenate, Conv2DTranspose, Reshape, ReLU
from tensorflow.keras.applications import DenseNet121
# tf.config.experimental_run_functions_eagerly(True)
# with tf.dev... | StarcoderdataPython |
3291096 | from __future__ import absolute_import
import os
import os.path as osp
from torch.utils.data import DataLoader, Dataset
import numpy as np
import random
import math
from PIL import Image
import torch
import pdb
import scipy.io
from ...models.layers.adain import adaptive_instance_normalization_v2
class Preprocessor(Da... | StarcoderdataPython |
1797461 | <reponame>qwc-services/sogis-config-generator<gh_stars>0
import html
import os
import re
from urllib.parse import urlparse, parse_qs
import uuid
import requests
from copy import deepcopy
from flask import json, jsonify
from jinja2 import Template
from xml.dom.minidom import parseString
from sqlalchemy.exc import Oper... | StarcoderdataPython |
138943 | from collections import OrderedDict
from daops.utils import fixer, is_characterised
from daops.utils.normalise import ResultSet
from pywps.app.exceptions import ProcessError
from roocs_utils.project_utils import get_project_name
from roocs_utils.utils.file_utils import FileMapper
from rook import CONFIG
from roocs_ut... | StarcoderdataPython |
3258772 | from general.utils import *
class Motion:
"""
Motion model considers that any motion can be generated from three basic movements:
a rotation, a translation and a second rotation
The propagation of motion will be based on this assumption. In order to prevent sample impoverishment, noise should be ... | StarcoderdataPython |
4829043 | # Concord
#
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
#
# This product is licensed to you under the Apache 2.0 license (the "License").
# You may not use this product except in compliance with the Apache 2.0 License.
#
# This product may include a number of subcomponents with separate copyright
# notices a... | StarcoderdataPython |
3355434 | <filename>python/famed/version.py
# Version number kept here
__version__ = "0.0.1"
| StarcoderdataPython |
1669091 | num1 = int(input("First number: "))
num2 = int(input("Second number: "))
print(num1, " + ", num2, " = ", num1+num2)
## Extra stuff starts here ##
def cal(num_a,num_b,op):
if op == "+":
return num_a + num_b
elif op == "-":
return num_a - num_b
elif op == "*":
return num_a * num_b
elif op == "/":
re... | StarcoderdataPython |
1760928 | #!/usr/bin/env python
import MySQLdb
import os
import sys
import wpmu
home = os.getenv('HOME')
daily_filename = '%s/Desktop/daily.txt' % (home)
total_filename = '%s/Desktop/total.txt' % (home)
daily_users_filename = '%s/Desktop/daily_users.txt' % (home)
total_users_filename = '%s/Desktop/total_users.txt' % (home)
... | StarcoderdataPython |
34441 | <reponame>AI-tist/NlpDeeplearning<filename>deep_NLP.py
import pandas as pd
import numpy as np
import xgboost as xgb
from tqdm import tqdm
from sklearn.svm import SVC
from keras.models import Sequential
from keras.layers.recurrent import LSTM, GRU
from keras.layers.core import Dense, Activation, Dropout
from keras.layer... | StarcoderdataPython |
75132 | <gh_stars>0
print('Conversor de números\n')
while True:
n = input('Digite um número inteiro: ')
if n.isnumeric():
print('Escolha uma opção para conversão: \n[1] para binário \n[2] para octal \n[3] para hexadeximal')
break
else:
print('Digite uma opção válida!')
while True:
o = input('Digite uma opção para con... | StarcoderdataPython |
1729954 | import sys
import os
import argparse
import logging
import json
import time
import numpy as np
import openslide
import PIL
import cv2
import matplotlib.pyplot as plt
from scipy import ndimage
from torch.utils.data import DataLoader
import math
import json
import logging
import time
import tensorflow as tf
from tensorfl... | StarcoderdataPython |
3370391 | <reponame>mayankchauhan96/Travel-Blogging-website
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpattern... | StarcoderdataPython |
1710708 | <reponame>typhoon-data-org/typhoon-orchestrator<filename>typhoon/deployment/packaging.py
import os
import re
import subprocess
import sys
import tempfile
from datetime import datetime
from distutils.dir_util import copy_tree
from distutils.errors import DistutilsFileError
from pathlib import Path
from shutil import cop... | StarcoderdataPython |
1764636 | import unittest
from unittest.mock import *
from src.sample.CarClass import Car
class TestCar(unittest.TestCase):
def test_needs_fuel(self):
car = Car()
car.needsFuel = Mock(name = "needsFuel")
car.needsFuel.return_value = True
self.assertEqual(car.needsFuel(), True)
def... | StarcoderdataPython |
3294656 | <filename>sniffersapp/timesheet/apps.py
from django.apps import AppConfig
class TimesheetConfig(AppConfig):
name = 'timesheet'
| StarcoderdataPython |
135261 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from config import gLocalIP
from config import gLocalPort
from config import gSaveDataFileFullName
from config import gFlyerInitDoneStr
from config import gKeyAcceletorPidStep
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.... | StarcoderdataPython |
1657856 | # def reverseVowels(s: str) -> str:
# vowel = 'AEIOUaeiou'
# s = list(s)
# p1, p2 = 0, len(s) - 1
#
# while p1 < p2:
# while s[p1] not in vowel and p1 < p2:
# p1 = p1 + 1
# while s[p2] not in vowel and p1 < p2:
# p2 = p2 - 1
# s[p1], s[p2] = s[p2], s[p1]
#... | StarcoderdataPython |
1797864 | <gh_stars>0
from django import forms
from .models import *
class ProductCategoryCreateForm(forms.ModelForm):
class Meta:
model = ProductCategory
fields = "__all__"
class ProductCreateForm(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'novalidate ': 'novalidate '}))
... | StarcoderdataPython |
1725088 | from django.contrib.auth.models import AbstractUser
from django.db import models
class UserProfile(AbstractUser):
"""
用户表,新增字段如下
"""
GENDER_CHOICES = (
("1", "男"),
("0", "女")
)
gender = models.IntegerField(choices=GENDER_CHOICES, default="0", verbose_name="性别")
class Meta... | StarcoderdataPython |
149780 | from milkman import *
from testapp.models import *
import unittest
import types
from django.db import models
MODELS = [Root, Child]
class ModelTest(unittest.TestCase):
def tearDown(self):
for m in MODELS:
m._default_manager.all().delete()
def test_create(self):
r = milkman.de... | StarcoderdataPython |
4826022 | """Constants for the Passive BLE monitor integration."""
from __future__ import annotations
from dataclasses import dataclass
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntityDescription,
)
from homeassistant.components.sensor import (
SensorDeviceClass,
... | StarcoderdataPython |
3216763 | import datetime
from unittest import mock
from django.db import (
IntegrityError, NotSupportedError, connection, transaction,
)
from django.db.models import (
CheckConstraint, Deferrable, F, Func, Q, UniqueConstraint,
)
from django.db.models.fields.json import KeyTextTransform
from django.db.models.functions i... | StarcoderdataPython |
86462 | <reponame>FaMiFisH/ProjectEuler<gh_stars>0
def even(n):
return n/2
def odd(n):
return (3*n)+1
if __name__ == '__main__':
appeared = []
z = 0
x = 0
for i in range(1,1000000):
y = 0
a = i
while a != 1:
if i not in appeared:
if ... | StarcoderdataPython |
4842213 | # Generated by Django 3.1.3 on 2020-11-21 22:36
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name... | StarcoderdataPython |
94526 | #------------------------------------------------------------------------------
# Copyright (c) 2007, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
# However, when used with the GPL version of PyQt the additional terms described in ... | StarcoderdataPython |
4802871 | <filename>fonts/font7mono.py
# Code generated by cfonts_to_trans_py.py
import TFTfont
_font7mono = (b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x20\x40\x81\x02\x04\x08\x00\x20\x00\x00\x00'
b'\x00\x50\xa1\x40\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x50\xa1\x47\xc5\x14\x7c\x50\xa0\x00\x00\x00'
b'\x10\x71\x... | StarcoderdataPython |
109424 | """ Hello world in python
"""
def helloworld():
""" print hello world to screen
"""
print "Hello world!"
if __name__ == '__main__':
helloworld()
| StarcoderdataPython |
121961 | <filename>staeon/utils.py
from __future__ import print_function
from staeon.consensus import get_epoch_range
from staeon.emission import emission, total_supply_at
def make_emission_table(to_epoch=100000, accurate=False):
"""
Make emission table including completely accurate supply.
"""
cumm = 0
la... | StarcoderdataPython |
3389031 | <gh_stars>1-10
import collections
import logging
from telnetlib3.telsh import Telsh, TelnetShellStream
def telnet2cmd(func):
def wrapped(*args):
return func(' '.join(args))
return wrapped
class BoundStream():
def __init__(self, stream):
self.stream = stream
def __getattr__(self, i... | StarcoderdataPython |
4832181 | <filename>openmdao/core/tests/test_varsets_simple.py
from __future__ import division
import numpy as np
import unittest
from openmdao.api import Problem, ExplicitComponent, Group, DefaultVector
from openmdao.devtools.testutil import assert_rel_error
try:
from openmdao.parallel_api import PETScVector
except Import... | StarcoderdataPython |
197649 | import json
from time import sleep
from typing import Optional, Tuple, List
from google_play_scraper import Sort
from google_play_scraper.constants.element import ElementSpecs
from google_play_scraper.constants.regex import Regex
from google_play_scraper.constants.request import Formats
from google_play_scraper.utils... | StarcoderdataPython |
181735 | <gh_stars>0
from pprint import pprint
from collections import OrderedDict
from vsr.common.helpers import dom,index,logger
from vsr.common.helpers.extras import merge_params
from xml.dom import minidom
import ConfigParser
import cPickle as pickle
import csv
import logging as log
import os
import sys
def run(override_p... | StarcoderdataPython |
3358106 | <filename>esphome/components/partition/light.py<gh_stars>100-1000
import esphome.codegen as cg
import esphome.config_validation as cv
import esphome.final_validate as fv
from esphome.components import light
from esphome.const import (
CONF_ADDRESSABLE_LIGHT_ID,
CONF_FROM,
CONF_ID,
CONF_LIGHT_ID,
CON... | StarcoderdataPython |
82888 | # Generated by Django 3.0.5 on 2020-04-25 20:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('critters', '0006_auto_20200419_1200'),
]
operations = [
migrations.AddField(
model_name='bug',
... | StarcoderdataPython |
3263963 | #!/usr/bin/env python3
from setuptools import setup, find_packages
test_requirements = [
'pytest-cov',
'pytest'
]
setup(
name='prosodia',
version='0.5.3',
author='macbeth322',
author_email='<EMAIL>',
package_dir={'': 'src'},
packages=find_packages('src'),
install_requires=[
... | StarcoderdataPython |
3214048 | <gh_stars>0
import numpy as np
import os
import cubeventure as cv
visu_name = 'firework'
i_grid = 7
mid = np.floor(i_grid/2).astype(np.int)
data_matrix = np.zeros((i_grid, i_grid, i_grid, 30))
# define a falling drop
def make_drop_mat(mat, x, y, t):
drop_mat = np.zeros((i_grid, i_grid, i_grid, i_grid))
for i... | StarcoderdataPython |
86656 | <reponame>CognitiveComputationLab/mptpy
""" Data structure for Multinomial Processing Trees (MPTs).
"""
from mptpy.mpt_word import MPTWord
import mptpy.tools.transformations as trans # pylint: disable=import-error
from mptpy.visualization.visualize_mpt import cmd_draw # pylint: disable=import-error
from mptpy.tools... | StarcoderdataPython |
145983 | <reponame>jlin27/ClassyVision-1
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict
import torch.nn as nn
class ClassyLoss(nn.Module):
... | StarcoderdataPython |
3279547 | from .anchor_head_multi import AnchorHeadMulti
from .anchor_head_single import AnchorHeadSingle
from .anchor_head_single_trias import AnchorHeadSingle_trias
from .anchor_head_template import AnchorHeadTemplate
from .point_head_box import PointHeadBox
from .point_head_simple import PointHeadSimple
from .point_intra_part... | StarcoderdataPython |
23678 | <filename>functions/dissectData/lambda_handler.py<gh_stars>1-10
from data_dissector import DataDissector
def handler(event, _):
switchpoint_trio = DataDissector.dissect_data(data=event['data'])
return {
"switchpoint": switchpoint_trio.switchpoint,
"preSwitchAverage": switchpoint_trio.pre_... | StarcoderdataPython |
1750628 | # Import required libraries
import cv2
import numpy as np
import dlib
# Pc ye bağlı kamerayı çalıştırma
cap = cv2.VideoCapture(0)
# Kordinatları Yakala
detector = dlib.get_frontal_face_detector()
# Yüzde Kare Oluştur
while True:
# Kare kare Yakalama
ret, frame = cap.read()
f... | StarcoderdataPython |
187666 | <filename>dataset/h_time_series/create_gif_from_stack.py
import xarray as xr
import pyddem.fit_tools as ft
import numpy as np
import matplotlib
matplotlib.use('Agg')
#!!this requires cartopy 0.18
# fn_stack='/home/atom/ongoing/work_worldwide/figures/esapolar/N63W020_final.nc'
# fn_shp = '/home/atom/data/inventory_pro... | StarcoderdataPython |
4812962 | # Find the greatest common denominator of two numbers
# using Euclid's algorithm
def gcd(a, b):
while (b != 0):
t = a # set aside the value of a
a = b # set a equal to b
b = t % b # divide t (which is a) by b
return a
# try out the function with a few examples
print(gc... | StarcoderdataPython |
168561 | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
In order to accomodate 100x100 flores performance tags,
we need to increase the size of metadata_json.
"""
from yoyo import step
__depend... | StarcoderdataPython |
842 | <filename>ir_datasets/formats/trec.py
import io
import codecs
import tarfile
import re
import gzip
import xml.etree.ElementTree as ET
from fnmatch import fnmatch
from pathlib import Path
from typing import NamedTuple
import ir_datasets
from ir_datasets.indices import PickleLz4FullStore
from .base import GenericDoc, Gen... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.