id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3291283 | from .lib_utils import load_lib
from .histogram import get_bins_maps
from .gbdtmo import GBDTSingle, GBDTMulti
from .plotting import create_graph
__all__ = ["load_lib", "create_graph", "get_bins_maps", "GBDTSingle", "GBDTMulti"]
| StarcoderdataPython |
3371708 | # beta_plot.py
import numpy as np
from scipy.stats import beta
import matplotlib.pyplot as plt
import seaborn as sns
if __name__ == "__main__":
sns.set_palette("deep", desat=.6)
sns.set_context(rc={"figure.figsize": (8, 4)})
x = np.linspace(0, 1, 100)
params = [
(0.5, 0.5),
(1.0, 1.0)... | StarcoderdataPython |
3210835 | from time import time, sleep
from .standard import Standard
class MultiQueue(Standard):
"""
Broker to execute jobs in an asynchronous way from multiple queues.
Execute a job from one queue and go to the next one, if the queue is empty
add a timestamp to wait `polling_interval` seconds before trying a... | StarcoderdataPython |
3256292 | <gh_stars>0
# Heap Sort
# CLRS Chapter 6 Page 160
from heap import build_max_heap
from heap import max_heapify
from heap import remove_last
from heap import _swap
from heap import _root
def heap_sort(items):
"""Sorts a list of items.
Uses heap sort to sort the list items.
Args:
items: A lis... | StarcoderdataPython |
144074 | <reponame>valassi/mg5amc_test
# This file was automatically created by FeynRules 2.0.25
# Mathematica version: 8.0 for Mac OS X x86 (64-bit) (February 23, 2011)
# Date: Thu 8 May 2014 12:30:33
from __future__ import absolute_import
from .object_library import all_couplings, Coupling
from .function_library import com... | StarcoderdataPython |
3250929 | #!/usr/bin/python
import monkDebug as debug
import sys
import monkTools
import re
##
## @brief Transcode
## commencez les ligne par ":" comme:
## : 1
## : 2
## ::2.1
## ::2.2
## :::2.2.1
## ::::2.2.1.1
## :::::2.2.1.1.1
## ::2.3
## :3
## resultat:
##
## 1
## 2
## 2.1
## 2.2
## 2.2.1
## 2.2.1.1
##... | StarcoderdataPython |
3304315 | <reponame>timgates42/GuitarFan
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from uuid import uuid4
import shutil
from flask import render_template, request, redirect, url_for, flash, Blueprint, jsonify
from flask.ext.login import login_required
from sqlalchemy import func
from guitarfan.extensions.flasksq... | StarcoderdataPython |
3270663 | <reponame>i-yamane/mu_learning_examples
# pyright: strict
from typing import Dict, Tuple, Any, Optional, Callable, NamedTuple, List, Union
import torch
from torch.utils.data import DataLoader, random_split, TensorDataset
import torchvision.datasets as torchdata # type: ignore
import torchvision.transforms as transfor... | StarcoderdataPython |
1676235 | <gh_stars>1-10
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__date__ = "17 Nov 2018"
# !!! SEE CODERULES.TXT !!!
from silx.gui import qt
from ..core import singletons as csi
from ..core import commons as cco
from .propWidget import QLineEditSelectRB, PropWidget
# from . import propsOfData as gpd
class ColumnFormat... | StarcoderdataPython |
3352438 | # 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, software
# distrib... | StarcoderdataPython |
1702559 | <reponame>mario21ic/pyclima<gh_stars>0
#!/usr/bin/env python3
"""
entrada: ciudad, telefono
salida: temperatura
consultar pronostico clima, si supera 20 enviar sms con alerta
https://api.openweathermap.org/data/2.5/weather?q=Lima&appid=1857efc0aad350431e9002ed71d9395d&units=metric
"""
import requests
import json
fro... | StarcoderdataPython |
4829256 | try:
from unittest2 import TestCase
from mock import patch
except ImportError:
from unittest import TestCase
from mock import patch
import base64
from cfn_sphere.aws.kms import KMS
class KMSTests(TestCase):
@patch('cfn_sphere.aws.kms.boto3.client')
def test_decrypt_value(self, boto_mock):
... | StarcoderdataPython |
1612461 | """
Module which contains all the imports and data available to unit tests
"""
import os
import sys
import json
import time
import shutil
import timeit
import inspect
import logging
import platform
import tempfile
import unittest
import itertools
import subprocess
import numpy as np
import sympy as sp
import trimesh
... | StarcoderdataPython |
1769451 | <gh_stars>0
import os
import click
import gocardless_pro
import pytz
import csv
from dateutil.parser import parse as parse_datetime
from datetime import date, timedelta
from collections import defaultdict
def parse_date(date_str):
# Not using dateutil here as sometimes it thinks you've got an
# American date ... | StarcoderdataPython |
3331590 | from pprint import pprint
import asyncio
from panoramisk import Manager
import sys
@asyncio.coroutine
def ping(lp, username, secret):
manager = Manager(loop=lp,
host='127.0.0.1', port=5038,
username=username, secret=secret,
forgetable_actions=('log... | StarcoderdataPython |
3291323 | <reponame>MatheusHenriq/profiles-rest-api
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, viewsets
from profile_api import serializers
class HelloApiView(APIView):
'''Test API View'''
serializer_class = serializers.HelloSerializer
... | StarcoderdataPython |
3299823 | import os
from os import makedirs
from os.path import join, exists
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from .constants import VIZ_ROOT
class ImagePreprocess:
def __init__(self,input,labels = None):
self.suffixes = ('.jpeg', '.jpg', '.p... | StarcoderdataPython |
3219374 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
import torch.nn as nn
import torch.nn.functional as F
from nni.nas.pytorch.mutables import InputChoice, LayerChoice
from nni.nas.pytorch.mutator import Mutator
from .build import MUTATOR_REGISTRY
from nas.utils.gumbel_softmax impo... | StarcoderdataPython |
158437 | from __future__ import unicode_literals
from mayan.apps.storage.utils import get_storage_subclass
from .settings import (
setting_staging_file_image_cache_storage,
setting_staging_file_image_cache_storage_arguments,
)
storage_staging_file_image_cache = get_storage_subclass(
dotted_path=setting_staging_fi... | StarcoderdataPython |
3302978 | <reponame>gliptak/DataProfiler<gh_stars>0
#!/usr/bin/env python
"""
coding=utf-8
Build model for a dataset by identifying type of column along with its
respective parameters.
"""
from __future__ import division, print_function
import abc
import copy
import itertools
import warnings
import numpy as np
import scipy.sta... | StarcoderdataPython |
1723805 | <filename>state_specific_info.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: neilthomson
"""
import numpy as np
from queue import PriorityQueue
import math
import re
import glob
import itertools
#from tqdm import tqdm
from multiprocessing import Pool
from time import gmtime, strftime
import ast
from p... | StarcoderdataPython |
4821734 | <reponame>akshitdewan/cs61a-apps<filename>examtool/examtool/cli/find_errors.py
import json
from examtool.api.database import get_exam, get_roster
from examtool.api.extract_questions import extract_questions
from examtool.api.scramble import scramble
from google.cloud import firestore
import warnings
warnings.filterwa... | StarcoderdataPython |
6058 | class TreeNode:
def __init__(self, name, data, parent=None):
self.name = name
self.parent = parent
self.data = data
self.childs = {}
def add_child(self, name, data):
self.childs.update({name:(type(self))(name, data, self)})
def rm_branch(self, name, ansistors_n: lis... | StarcoderdataPython |
1615366 | <filename>pPsPointSource/Classification/calc.py
import pandas as pd
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
import itertools
import math
from sklearn.metrics import roc_curve, auc
sOfL = 300 # mm/ns
names = [
"evID1", "evID2", "trID1", "trID2", "x1", ... | StarcoderdataPython |
4804343 | <gh_stars>0
"""
Layer of a neural network.
"""
import theano
import numpy as np
import theano.tensor as T
class Layer(object):
def __init__(self, W_init, b_init, activation):
'''
A layer of a neural network, computes s(Wx + b) where s is a nonlinearity and x is the input vector.
:paramete... | StarcoderdataPython |
3290175 | # for now this is empty
| StarcoderdataPython |
32500 | <reponame>OriDevTeam/PySimpleFrame
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Name: TOFILL\n
Description: TOFILL
"""
"""PySimpleFrame
Author: <NAME>
License: Check LICENSE file
"""
## System imports ##
## Library imports ##
import termtables
from colorama import Fore, Back, Style
## Application ... | StarcoderdataPython |
3269649 | from Tkinter import Tk, Label, Button, Entry, StringVar, DISABLED, NORMAL, END, W, E
from socket import *
from functools import partial
import random
def is_valid_ipv4(ip):
parts = ip.split('.')
return ( len(parts) == 4
and all(part.isdigit() for part in parts)
and all(0 <= ... | StarcoderdataPython |
3390426 | from dataclasses import dataclass
from commanderbot.ext.automod.automod_condition import (
AutomodCondition,
AutomodConditionBase,
)
from commanderbot.ext.automod.automod_event import AutomodEvent
from commanderbot.lib import JsonObject
@dataclass
class MessageMentionsUsers(AutomodConditionBase):
"""Chec... | StarcoderdataPython |
1721525 | <reponame>TheDarrenJoseph/AberWebMUD<filename>server/pyfiles/dice.py
""" Generates random dice rolls, nothing special just a randint wrapper """
from random import randint
# Can't roll less than 1 die
MIN_DICE_COUNT = 1
# 10 is a pretty sensible maximum per turn
MAX_DICE_COUNT = 10
# Cannot have a 1 sided die
MIN_DIC... | StarcoderdataPython |
195880 | import datetime, dateutil.relativedelta
import pandas as pd
import numpy as np
from .settings import WORLD_CPI, WORLD_CY, WORLD_ER
def _get_value(date, df, type_, fpath=None):
"""
_get_value looks up the value of a cell for a given date (date) in a table provided by the Federal Statistical Office.
:param ... | StarcoderdataPython |
131283 | __author__ = '<NAME>'
import logging
import cv2
import numpy
import sys
from combining_classifications import combine_majority_vote, combine_mean_rule, combine_minimum_rule
from loading_images import load_face_vectors_from_disk, extract_color_channels
from pca import PCA
from plotting import plot_results
def main(... | StarcoderdataPython |
1724829 | from dataclasses import dataclass
from typing import Dict, List, Optional, TYPE_CHECKING
if TYPE_CHECKING:
import readimc.data
@dataclass(frozen=True)
class Slide:
"""Slide metadata"""
id: int
"""Slide ID"""
metadata: Dict[str, str]
"""Full slide metadata"""
panoramas: List["readimc.da... | StarcoderdataPython |
4816647 | <gh_stars>1000+
class MockClass(object):
def __init__(self):
pass
def foo():
pass
def bar():
pass
class Error_resp_401(object):
status_code = 401
pass
class Error_resp_500(object):
status_code = 500
pass
class Success_resp(object):
status_code = 200
def jso... | StarcoderdataPython |
66476 | from django.contrib.auth import get_user_model
from django.test.client import RequestFactory
from core.models import Person
import random
import string
def random_user():
user = get_user_model().objects.create_user(
''.join(random.choice(string.lowercase) for _ in range(12)))
person = Person.object... | StarcoderdataPython |
4807743 | <reponame>febuiles/two1-python<filename>two1/bitserv/django/views.py
"""Added views for a bitserv server."""
from rest_framework import status
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from . import payment
class PaymentAPIError(Exception):
"""Generic error for exce... | StarcoderdataPython |
132446 | <filename>xdo.py
#!/usr/bin/python3
from pykeyboard.x11_keysyms import KEYSYMS
from subprocess import run
import time
import sys
# delays are given as 2-item tuples of (seconds before, seconds after)
DEFAULT_DELAY = (0, 0.05)
DELAYS = {
"\n": (0.33, 1.75),
"@D@": (0.25, 0.25),
".": (1, 0.5),
"(": (1,... | StarcoderdataPython |
3238866 | def main():
num=int(input("introduce un número:"))
if num > 0:
print("es natural", num )
else:
print("no es natural", num) | StarcoderdataPython |
51448 | <reponame>allen-garvey/gae-library<filename>controllers/base_controller.py
import webapp2
import json
#base controller class
class BaseController(webapp2.RequestHandler):
#convenience method for writing json response
def write_json(self, json_string):
self.response.content_type = 'application/json'
... | StarcoderdataPython |
1678188 | <filename>region_grow/functions.py
"""
Functions to be used to perform the Region Growing process
"""
# Librerias
import logging
import rasterio as rio
import numpy as np
import pandas as pd
import geopandas as gpd
import region_grow.region as rg
from shapely.geometry import Polygon
from region_grow.classifiers impor... | StarcoderdataPython |
1665728 | <gh_stars>0
import math
import numpy as np
class myPyClass:
def __init__(self, x, y):
self.x = x
self.y = y
def euclength(self):
return math.sqrt(self.x*self.x + self.y*self.y)
def translate(self, deltaX, deltaY):
self.x += deltaX
self.y += deltaY
def arra... | StarcoderdataPython |
3252934 | """
Question Source:Leetcode
Level: Medium
Topic: Stack
Solver: Tayyrov
Date: 03.05.2022
"""
from typing import List
from collections import Counter
def maxOperations(nums: List[int], k: int) -> int:
cnt = Counter(nums)
ans = 0
for n in nums:
if cnt[n] > 0:
needed = k -... | StarcoderdataPython |
4812299 | """Calculador de Descontos"""
def aplicar_desconto_avista(valor):
"""Aplica 10% de desconto"""
return valor * 0.1
def aplicar_desconto_parcelado(valor):
"""Aplica 5% de desconto"""
return valor * 0.05
def calcular(valor_total, tipo_pagamento):
"""Calcula o desconto de acordo com as regras de d... | StarcoderdataPython |
1610449 | """
Test compilation modes
"""
import copy
import theano
import theano.tensor as tt
from theano.compile import Mode
class TestBunchOfModes:
def test_modes(self):
# this is a quick test after the LazyLinker branch merge
# to check that all the current modes can still be used.
linker_class... | StarcoderdataPython |
1789272 | <reponame>jon2allen/aws-scripts
#!/usr/bin/python
#################################################################
# List all exceptions in boto3 library for aws.
#################################################################
import botocore
import boto3
import pprint
list1 = [e for e in dir(botocore.exceptions) i... | StarcoderdataPython |
4820099 | # -*- coding: utf-8 -*-
import json
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.utils import translation
from django... | StarcoderdataPython |
173449 | <filename>search/config.py
from collections import OrderedDict
from contextlib import closing
from copy import deepcopy
from functools import partial
import glob
import inspect
from itertools import chain
import json
import os
import re
CONFIG_PATHS = (
'~/.search.conf*',
'/etc/search.conf*'
)
CONFIG_LOADERS = Orde... | StarcoderdataPython |
120520 | <gh_stars>1-10
#!/usr/bin/env python
#
# Author: <NAME> <<EMAIL>>
#
from pyscf import gto
'''
Specify symmetry.
Mole.symmetry can be True/False to turn on/off the symmetry (default is off),
or a string to specify the symmetry of molecule.
If symmetry is bool type, the atom coordinates might be changed. The molecul... | StarcoderdataPython |
3289016 | ###############################################################################
###
### RunPyDaq
### This file is part of CoreDataLogging
### This file was created by Dr <NAME>
### Twitter: @DrDanParker GitHub:https://github.com/DrDanParker
###
### Copyright (C) 2018 University of Salford - All Rights Res... | StarcoderdataPython |
85427 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License... | StarcoderdataPython |
3289527 | import unittest
from server.data_common.matrix_loader import MatrixDataLoader
from server.common.app_config import AppConfig
import server.compute.diffexp_cxg as diffexp_cxg
import server.compute.diffexp_generic as diffexp_generic
import numpy as np
from server.test import PROJECT_ROOT
class DiffExpTest(unittest.Tes... | StarcoderdataPython |
1624453 | from django.urls import path
from .api.views import link_search_view, link_view
app_name = "links"
urlpatterns = [
path("", view=link_view),
path("search", link_search_view),
]
| StarcoderdataPython |
1662454 | """
Test for searchwidget
"""
from AnyQt.QtWidgets import QAction, QStyle, QMenu
from AnyQt.QtGui import QIcon
from ..lineedit import LineEdit
from ..test import QAppTestCase
class TestSearchWidget(QAppTestCase):
def test_lineedit(self):
"""test LineEdit
"""
line = LineEdit()
l... | StarcoderdataPython |
89446 | <filename>zipfix/merge.py<gh_stars>1-10
"""
This module contains a basic implementation of an efficient, in-memory 3-way
git tree merge. This is used rather than traditional git mechanisms to avoid
needing to use the index file format, which can be slow to initialize for
large repositories.
The INDEX file for my local... | StarcoderdataPython |
3224708 | # Hexapod Hardware Connection
#
# <NAME>
import serial, struct;
import binascii;
import time;
TYPE_POSE_UPDATE = 42;
class SerialLink(object):
def __enter__(self):
return self;
def __exit__(self, typ, value, traceback):
self.ser.close();
def __init__(self, c... | StarcoderdataPython |
1600281 | #-*- coding:utf-8 -*-
#接收电机字节数
RECEIVE_MOTOR_DATA_NUM = 0
def setReceiveMotorDataNum(new):
global RECEIVE_MOTOR_DATA_NUM
RECEIVE_MOTOR_DATA_NUM = new
#接收接近传感器字节数
RECEIVE_SENSOR_DATA_NUM = 0
def setReceiveSensorDataNum(new):
global RECEIVE_SENSOR_DATA_NUM
RECEIVE_SENSOR_DATA_NUM = new
#发送... | StarcoderdataPython |
1740946 | from random import randrange
from os import getenv
LEADER = 0
CANDIDATE = 1
FOLLOWER = 2
LOW_TIMEOUT = int(getenv('LOW_TIMEOUT', 150))
HIGH_TIMEOUT = int(getenv('HIGH_TIMEOUT', 300))
REQUESTS_TIMEOUT = 50
HB_TIME = int(getenv('HB_TIME', 50))
MAX_LOG_WAIT = int(getenv('MAX_LOG_WAIT', 150))
def random_timeout():
... | StarcoderdataPython |
3248093 | # Copyright 2021-xx iiPython
# Modules
import discord
from discord.ext import commands
from discord.commands import Option
# Command class
class Profile(commands.Cog):
def __init__(self, bot) -> None:
self.bot = bot
self.core = bot.core
@commands.slash_command(description = "View somebodies p... | StarcoderdataPython |
4842916 | <gh_stars>10-100
class WebServiceError(Exception):
def __init__(self, code='', desc=None, status=400, *args, **kwargs):
super().__init__(*args, **kwargs)
self.code = code
self.desc = desc
self.status = status
class LoginError(WebServiceError):
def __init__(self, code, redirect_... | StarcoderdataPython |
1635608 | <reponame>gErRyVoY/ganarCRM<gh_stars>10-100
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render
from rest_framework import viewsets, status, filters
from rest_framework.decorators import api_view
from rest_framework.pagination import PageNumberPagination
from... | StarcoderdataPython |
70956 | <reponame>feketebv/Rolling_hash
#A more compact version of the algorithm that can be executed parallelly.
list1 = [0x58, 0x76, 0x54, 0x3a, 0xbe, 0x58, 0x76, 0x54, 0xbe, 0xcd, 0x45, 0x66, 0x85, 0x65]
# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
# Par=4: bulk bulk bulk ... | StarcoderdataPython |
3212334 | <filename>_site/cours/deep_ecn_2019/code_deep_ecn/lib/train_gan.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 4 20:44:54 2018
Train GAN
@author: vayer
"""
#%%
import os,sys
#path='/home/vayer/wgw/gwtest-master/code_deep_ecn'
path='./code_deep_ecn/lib'
#path='/Users/vayer/Doc... | StarcoderdataPython |
3325838 | from pynput import keyboard
import time, sys, termios
break_loop = False
def on_press(key):
try:
global break_loop
# print(f'alpha key {key.char} pressed')
if key == keyboard.Key.space:
print('ack sent')
break_loop = False
if key == keyboard.Key.esc and break... | StarcoderdataPython |
131942 | <reponame>tiveritz/sequence-api
from rest_framework import serializers
from ..models import Explanation
class ExplanationSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name='explanation-detail',
lookup_field='api_id',)
class Meta:
model = Exp... | StarcoderdataPython |
3203319 | <reponame>emre/semaphores<gh_stars>1-10
import random
import time
from threading import Thread, Semaphore
class Philosopher(Thread):
def __init__(self, *args, **kwargs):
self.index = kwargs.pop("index")
self.forks = kwargs.pop("forks")
self.multiplex = kwargs.pop("multiplex")
s... | StarcoderdataPython |
4822036 | import models.net as net
import models.iadam_attention as iadam_attention
import bin.train_and_evaluate as train
# configure
# data_small.pkl is the small data for debugging purpose (10K training instances for UDC)
# data.pkl is the whole data (1M training instances for UDC)
conf = {
"data_name": "udc",
"d... | StarcoderdataPython |
111224 | <reponame>Praneethp09/Geo_Test
# Copyright 2020 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 required by applicab... | StarcoderdataPython |
1730491 | <reponame>achien/transit-time<gh_stars>10-100
import pytest
from scraper import nyc
PARSE_TRIP_ID_ARGNAMES = [
"trip_id",
"sub_division",
"effective_date",
"service_day",
"origin_time",
"trip_path",
"route_id",
"direction",
"path_identifier",
]
PARSE_TRIP_ID_PARAMS = [
(
... | StarcoderdataPython |
3217440 | # Copyright 2018 The TensorFlow 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 applicab... | StarcoderdataPython |
185444 | <reponame>gkucsko/NeMo<filename>nemo/collections/nlp/data/dialogue/dataset/dialogue_bert_dataset.py
# Copyright (c) 2022, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# Copyright 2019 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file e... | StarcoderdataPython |
3375360 | <reponame>tonywanggit/vnpy
# -*- coding: utf-8 -*-
# @Time : 2019/10/1 16:11
# @Author : Tony
import re
from datetime import datetime, timedelta
from vnpy.app.cta_strategy import CtaTemplate
from vnpy.app.cta_strategy.base import EngineType
from vnpy.event import EventEngine, Event
from vnpy.trader.constant import... | StarcoderdataPython |
1670765 | from django.db import models
from .models import *
class Farmer(models.Model):
"""docstring for Farmer"""
email = models.ForeignKey(MyUser, on_delete= models.CASCADE)
username = models.CharField(max_length = 20)
date_of_birth = models.DateField()
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'e... | StarcoderdataPython |
71413 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
from torch.distributions.transforms import TanhTransform
from rl_sandbox.constants import OBS_RMS, VALUE_RMS, CPU
from rl_sandbox.model_architectures.utils import RunningMeanStd
class ActorCritic(nn.Module):
... | StarcoderdataPython |
41584 | # Copyright 2021-present, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch.nn as nn
from torch.optim import SGD
import torch
import torchvision
from argparse import Namespa... | StarcoderdataPython |
4813367 | from rafflebot.cogs.hello import Hello
from rafflebot.cogs.raffle import Raffle
from rafflebot.cogs.raffle_admin import RaffleAdmin
| StarcoderdataPython |
1610212 | <reponame>Hafiz00/lbry
import json
import tempfile
import logging
import asyncio
from types import SimpleNamespace
from twisted.internet import defer
from orchstr8.testcase import IntegrationTestCase, d2f
import lbryschema
lbryschema.BLOCKCHAIN_NAME = 'lbrycrd_regtest'
from lbrynet import conf as lbry_conf
from lbry... | StarcoderdataPython |
4839992 | """
백준 20353번 : Atrium
"""
a = int(input()) ** 0.5
print(a*4)
| StarcoderdataPython |
146843 | <reponame>DanielRios549/PythonExcercises
'''
Create a tuple with all teams of the Brazilian Championship, in classification order.
After the show the following:
1 - The first 5 teams.
2 - The last 4 teams.
3 - A list with the teams in alphabetical order.
4 - In which position is the Chapecoense... | StarcoderdataPython |
1699527 | #!/usr/bin/env python
#
# Copyright 2010 Google 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 o... | StarcoderdataPython |
3358084 | <reponame>yohm/oacis_sample_workflow
import functools
import oacis
localhost = oacis.Host.find_by_name("localhost")
def step1(param):
sim = oacis.Simulator.find_by_name("workflow_sample_step1")
ps = sim.find_or_create_parameter_set( {"p1":param} )
runs = ps.find_or_create_runs_upto( 1, submitted_to=localh... | StarcoderdataPython |
3252446 | <reponame>ioos/qartod
import numpy as np
import pyproj
import quantities as pq
import pandas as pd
import multiprocessing
class QCFlags:
"""Primary flags for QARTOD."""
# Don't subclass Enum since values don't fit nicely into a numpy array.
GOOD_DATA = 1
UNKNOWN = 2
SUSPECT = 3
BAD_DATA = 4
... | StarcoderdataPython |
1701191 | import itertools
from typing import Any, List, Sequence, Tuple
import numpy as np
import pytest
from pydantic import BaseModel
from useq import (
Channel,
MDAEvent,
MDASequence,
NoT,
NoZ,
Position,
TDurationLoops,
TIntervalDuration,
TIntervalLoops,
ZAboveBelow,
ZAbsolutePos... | StarcoderdataPython |
3280572 | import pygame
from engine import gametime, inputs, gamestate
import time
from pygame.locals import (
QUIT,
KEYDOWN,
KEYUP,
K_ESCAPE,
MOUSEBUTTONDOWN,
MOUSEBUTTONUP,
)
def launch():
pygame.init()
screen = pygame.display.set_mode((1600, 900))
running = True
last_time = time.time()
while running:
... | StarcoderdataPython |
3276806 | <reponame>jiyolla/StudyForCodingTestWithDongbinNa
# https://programmers.co.kr/learn/courses/30/lessons/12899
# 124 나라의 숫자
def solution(n):
def recursive(n, i):
if i == 0:
return str(n - 1)
a = (n - 1) // 3**i
return str(a) + recursive(n - a*3**i, i - 1)
for i in range(100):... | StarcoderdataPython |
1784952 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import json
import time
import uuid
import random
from django.shortcuts import render
from django.contrib import messages
from django.template.response import TemplateResponse
from django.core.paginator import Paginator, EmptyPage, InvalidPage
f... | StarcoderdataPython |
3250564 | <reponame>pixelink-support/PixelinkPythonWrapper
"""
setIpAddress.py
This demonstration application assumes that you have one GigE camera visible to the host, and that
that GigE camera is connected to a GigE card with a statically assigned IP address.
This demo app is incomplete in that we can't know a priori ... | StarcoderdataPython |
152129 | <gh_stars>1-10
import pandas as pd
import plotly.plotly as py
import plotly
df2 = pd.read_csv('input.csv', header=0)
df2['promo_dep15'].astype(float)
color = pd.Series(['rgb(100,100,100)', 'rgb(38,17,235)', 'rgb(17,93,235)', 'rgb(17,235,220)',
'rgb(49,235,17)', 'rgb(188,235,17)', 'rgb(235,202,17)', ... | StarcoderdataPython |
145218 | from twentyc.rpc import RestClient
from twentyc.rpc.client import NotFoundException, PermissionDeniedException
from peeringdb import get_backend
from peeringdb.resource import Network
from . import _data
# try: from peeringdb import _debug_http
# except: pass
__data = {Network: {20: _data.twentyc}}
class Fetcher(... | StarcoderdataPython |
3314787 | <reponame>mixcloud/graphql-core
from ...error import GraphQLError
from .base import ValidationRule
class KnownTypeNames(ValidationRule):
def enter_NamedType(self, node, *args):
type_name = node.name.value
type = self.context.get_schema().get_type(type_name)
if not type:
self.... | StarcoderdataPython |
1784713 | # -*- coding: utf-8 -*-
"""
Helper functions for calculating the shear wave anisotropy (SWA)
Author: <NAME>
Date: 29 February 2020
"""
import pathlib
import numpy as np
import pandas as pd
import pyproj
def vbar(vmodel, event_depth, station_elevation):
"""
Calculates the average velocity between source and... | StarcoderdataPython |
1671936 | import time
import servo_process as sp
class Arm:
def __init__(self):
self.spoon_status = 'empty'
self.leg_status = 'retracted'
def init(self):
self.sp = sp.ServoProcess()
self.sp.start()
def is_initialized(self):
return self.sp.initialized.value
def update(se... | StarcoderdataPython |
155234 | <reponame>tensojka/cshyphen<gh_stars>1-10
import sys
def has_forbidden_character(string):
try:
string.encode('iso-8859-2')
except UnicodeEncodeError:
return True
return False
if not (len(sys.argv[1]) > 0 and len(sys.argv[2]) > 0):
print("Supply output file and input file.", file=sys.st... | StarcoderdataPython |
151882 | <filename>inputs/timeElapsed.py
import time
from utils.number import Number
class TimeElapsed(Number):
def __init__(self):
self.__start_ms = time.time()
def get(self):
return time.time() - self.__start_ms
| StarcoderdataPython |
84643 | <filename>createcsvfile.py<gh_stars>0
#!/usr/bin/env python3
# coding=utf-8
import csv
import os
import datetime
import time
from ccws.configs import HOME_PATH
from ccws.configs import TIMEZONE
from ccws.configs import ExConfigs
def create_tomorrow_folder(path=''):
tmr = datetime.datetime.fromtimestamp(time.time... | StarcoderdataPython |
4820920 | import logging
import typing
from discord.ext import commands
from cogs import error_handler
log = logging.getLogger('logger')
async def get_member(ctx: commands.Context, member: typing.Union[int, str], is_expected: bool=True):
member = str(member)
try:
member_id = int(''.join(list(filter(str.isdigit... | StarcoderdataPython |
121599 | """Views for generating reports."""
from django.contrib.auth import get_user_model
from django.db.models import Count, Sum, Q
from django.http import HttpResponse
from django.views.generic import ListView
from pure_pagination import PaginationMixin
from tablib import Dataset
from open_connect.accounts.views import Sup... | StarcoderdataPython |
4828966 | import os
from setuptools import setup
__author__ = "<NAME>"
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(name="django_ldap_auth_bac... | StarcoderdataPython |
4809209 | import numpy as np
from statsmodels.stats.multitest import multipletests
def split_by_target(mat, targets, target, axis=0):
"""
Split the rows of mat by the proper assignment
mat = ndarray
targets, length is equal to number of components (axis=0) or features (axis=1)
target is a singular eleme... | StarcoderdataPython |
3258726 | <gh_stars>0
from rest_framework import serializers
from ..models import Attribute
class AttributeSerializer(serializers.ModelSerializer):
parent = serializers.CharField(source='parent.uri', default=None, read_only=True)
children = serializers.SerializerMethodField()
class Meta:
model = Attribut... | StarcoderdataPython |
3250461 | <filename>clispy/python/builtin_function.py
# Copyright 2019 <NAME>. 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
#
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.