id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3212427 | import sys
import re
if sys.version_info[0] > 2:
from itertools import zip_longest
else:
from itertools import izip_longest as zip_longest
class _Comparable(object):
"""Rich comparison operators based on __lt__ and __eq__"""
__gt__ = lambda self, other: not self < other and not self == other
__le_... | StarcoderdataPython |
1773736 | <gh_stars>0
from django.db import models
# VBT MODELS
# OPTION IN GUI
class Backtest(models.Model):
ENTRY = (
('rsi', 'RSI'),
('obv', 'OBV'),
('ma', '200-SMA'),
)
EXIT = (
('rsi', 'RSI'),
('obv', 'OBV'),
('ma', '200-SMA'),
)
# FOREIGN KEY -> BACKTE... | StarcoderdataPython |
1696047 | import os
import sys
import re
import types
import itertools
import matplotlib.pyplot as plt
import numpy
import scipy.stats
import numpy.ma
import Stats
import Histogram
from CGATReport.Tracker import *
from cpgReport import *
##########################################################################
class replica... | StarcoderdataPython |
167945 | # BEGIN_COPYRIGHT
#
# Copyright 2009-2015 CRS4.
#
# 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 |
83725 | # -----------------------------------------------------------------------------
# Licence:
# Copyright (c) 2012-2018 <NAME> for Gecosistema S.r.l.
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WI... | StarcoderdataPython |
3225901 | import pmdarima
import pandas as pd
import numpy as np
import sklearn
import copy
from training import TrainHelper, ModelsBaseClass
from preparation import PreparationHelper
class ARIMA(ModelsBaseClass.BaseModel):
"""
Class containing (S)ARIMA(X) model and methods
"""
def __init__(self, target_colum... | StarcoderdataPython |
3377880 | <gh_stars>1-10
# MapLoop - asks ScanMaster to make a series of scans with one of the pg
# parameters incremented scan to scan
from DAQ.Environment import *
def aquireWithEFlip(numScans):
# setup
fileSystem = Environs.FileSystem
file = \
fileSystem.GetDataDirectory(\
fileSystem.Paths["scanMasterDataPath"])\
... | StarcoderdataPython |
3298365 | <reponame>pnowk/pygadgets<filename>tests/test_exc.py<gh_stars>0
import exc.boyorgirl as t1
def test_1(capsys):
input_values = ['xiaodao']
def mock_input():
return input_values.pop(0)
t1.input = mock_input
t1.main()
out, err = capsys.readouterr()
assert out == 'IGNORE HIM!\n'
as... | StarcoderdataPython |
1765736 | <filename>Tilemap Maker/Tilemap Builder.py
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
from ast import *
from shutil import copy2
from os import path
import json
def build_matrix(width, height):
row = []
matrix = []
for i in range(0, width):
row.append(0)... | StarcoderdataPython |
1762934 | from output.models.saxon_data.override.over028a_xsd.over028a import NewSize
__all__ = [
"NewSize",
]
| StarcoderdataPython |
1765418 | # Copyright (c) 2015-2016 Hewlett-Packard Enterprise Development Company, L.P.
# 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.or... | StarcoderdataPython |
78148 | from django.http import HttpResponse
import json
import time
from datetime import datetime
from model import models
from api.v11 import common
def processRequest(request):
parsedRequest = common.parseRequest(request)
if parsedRequest['error'] is not None:
return parsedRequest['error']
if parsedRequest['respon... | StarcoderdataPython |
1634077 |
#
# @Author: kuroitu (2020)
# @email: <EMAIL>
#
import numpy as np
from ..dual import *
##########
# 指数関数 exponential functions
#######
def power(obj, n):
obj = to_dual(obj)
return obj ** n
def square(obj):
obj = to_dual(obj)
return obj ** 2
def sqrt(obj):
obj = to_dual(obj)
return obj... | StarcoderdataPython |
3207858 | from core_api.assets.base_asset import BaseAsset
from core_api.assets.image_asset import ImageAsset
class TextureAsset(ImageAsset, BaseAsset):
def __init__(self, **kwargs):
super(TextureAsset, self).__init__(**kwargs)
| StarcoderdataPython |
1605115 | <reponame>Shaid3r/reservations
from flask import session
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email, EqualTo, ValidationError
from models import User
from storage import conn
from utils.security import check_password
class Registra... | StarcoderdataPython |
3265597 | <filename>main.py
import math
from machine import Timer
tim = Timer()
sec = 0.0
amp = 0.49
freq = 1
def generate_sine(sec, amp, freq):
return amp * (math.sin(2.0 * math.pi * freq * sec / 1000) + 1.0)
def tick(timer):
global sec, amp, freq
print(", ".join([str(generate_sine(sec, amp, freq * (i + 1))) f... | StarcoderdataPython |
1623780 | <reponame>PozziSan/Django-Url-Shortener
'''
Url shortener model
'''
from django.db import models
from django.urls import reverse_lazy
from .utils import create_shortened_url
# Create your models here.
class Shortener(models.Model):
'''
Creates a short url based on the long one
created -> Hour and d... | StarcoderdataPython |
3248064 | <gh_stars>1-10
import simplejson as json
from collections import defaultdict
import math
import heapq
import sys
import csv
import glob
from pybloom import BloomFilter
reddit_archive_dir = sys.argv[1]
sub_archive_dir = sys.argv[2]
print
print "outputting to " + sub_archive_dir
# CREATE BLOOMFILTER OF BOTS
bot_name... | StarcoderdataPython |
1699143 | # Modulo para detección de nuevos miembros y saludo automático en #☕|café
# El id del documento creado en la colección Users es: 292556657925292550 # TODO: Cambiarlo por el de la DB de FEC
# ///---- Imports ----///
import logging
import random
import os
from time import time
from discord.ext import commands
from libs.... | StarcoderdataPython |
3305934 | # 배달
def find_shortest_path(startV, graph):
# dijkstra algorithm
from heapq import heappush, heappop
weights = [float('inf') for _ in range(len(graph)+1)]
weights[startV] = 0
heap = []
heappush(heap, (weights[startV], startV)) # (가중치, 노드) 전달 (정렬 기준: 가중치)
while heap:
cw, cv = heappop(... | StarcoderdataPython |
81228 | <reponame>BrambleLLC/H4H_2014
import re
import unicodedata
from socketio import socketio_manage
from socketio.namespace import BaseNamespace
from socketio.mixins import RoomsMixin, BroadcastMixin
from werkzeug.exceptions import NotFound
from gevent import monkey
from random import randint
from flask import Flask, Resp... | StarcoderdataPython |
3343712 | <filename>main/WSE/XDP/scs/parser/models.py
import logging
import sortedcontainers as sct
from consts import *
import datetime
def totimestamp(dt, epoch=datetime.datetime(1970,1,1)):
td = dt - epoch
# return td.total_seconds()
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 1e6
c... | StarcoderdataPython |
3232356 | # -*- coding: utf-8 -*-
"""
Project: EverydayWechat-Github
Creator: DoubleThunder
Create time: 2019-08-30 12:21
Introduction:
"""
| StarcoderdataPython |
24422 | <gh_stars>1-10
'''
PLNCPRO
This file takes as input
and it extracts dasta seq by label after reading prediction file
Author : <NAME>
email: <EMAIL>
UrMi 3/5/16
'''
import sys
import getopt
#import math
#import re
from Bio import SeqIO
from Bio.Seq import Seq
def main(args = sys.argv,home=None):
#set defaults
cutoff... | StarcoderdataPython |
1684673 | <filename>lambda/users/signals.py
from datetime import date, timedelta
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from projects.models import Project
from tasks.models import Task
from teams.models import Team
from .models import Pr... | StarcoderdataPython |
3378639 | <filename>backend/test/test_movie.py
# coding: utf8
from mock import MagicMock
from backend import test, movie, cache, error
class MovieTests(test.TestCase):
def test_create(self):
obj = movie.Movie.create(title="Dog", year=2000, imdb_id="xyz", type="movie", poster_url="http://poster")
self.asser... | StarcoderdataPython |
168698 | test = """2H2 + O2 -> 2H2O"""
def times_sep(s):
elem = []
times = []
checking_pro = False
last = 0
for i in range(len(s)):
if checking_pro:
if s[i].isalpha() and not s[i].islower() or s[i].isdigit():
elem.append(s[last])
checking_pro = False
... | StarcoderdataPython |
1644353 | <filename>dependencies/RoboFab/setup.py
#! /usr/bin/env python
import os, sys
from distutils.core import setup, Extension
try:
# load py2exe distutils extension, if available
import py2exe
except ImportError:
pass
try:
import numpy
except ImportError:
print "*** Warning: FontTools needs the numpy library for so... | StarcoderdataPython |
1730114 | <filename>django_social_pill/apps.py
from django.apps import AppConfig
from django.conf import settings
from django.core import exceptions
class DjangoSocialPillConfig(AppConfig):
name = 'django_social_pill'
backend_providers = {
'social_core.backends.github.GithubOAuth2': 'GITHUB',
'social_c... | StarcoderdataPython |
3309482 | <reponame>qinjunjerry/jupyter-vvp
"""Magics to connect to vvp."""
__version__ = '0.1.0'
from .vvpmagics import VvpMagics
def load_ipython_extension(ipython):
print("Registering jupytervvp for vvp.")
ipython.register_magics(VvpMagics)
| StarcoderdataPython |
172888 | <filename>facebook/modules/profile/user/admin.py
from django.contrib import admin
from facebook.modules.base import AdminBase
from .models import User
class UserAdmin(AdminBase):
list_display = ('id', 'profile_link', '_email', 'access_token', 'user', '_name', 'created', 'updated',)
readonly_fields = ('friend... | StarcoderdataPython |
3242736 | """Project-wide shared test fixtures."""
import os
import pytest
IF_DUMMY_SPARK = 'DUMMY_SPARK' in os.environ
@pytest.fixture(scope='session', autouse=True)
def spark_ctx():
"""A simple spark context."""
if IF_DUMMY_SPARK:
from dummy_spark import SparkConf, SparkContext
conf = SparkConf()
... | StarcoderdataPython |
1757824 | """Functions for reading Jupyter files."""
import json
import re
import nbformat
from . import ParseError
from ._common import RE_JSON
def deserialize(source):
"""Convert ``.jupyter`` string representation to Jupyter notebook.
Lines have to be terminated with ``'\\n'``
(a.k.a. :term:`universal newline... | StarcoderdataPython |
178308 | from unittest.mock import patch, ANY
import numpy as np
import cv2
from tasks import (
_download_image, ascii, candy, mosaic, the_scream,
udnie, celeba_distill, face_paint, paprika
)
IMAGE_URL = "image_url"
IMAGE_NAME = "image_name"
IMAGE_PATH = "image_path"
IMAGE_IPFS_URL = "pinata_hash_123"
METADATA_IPFS_URL = ... | StarcoderdataPython |
1611679 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2021 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... | StarcoderdataPython |
1705390 | <reponame>dianjixz/AutoDL<gh_stars>1000+
from at_speech.data_space.data_augment import DNpAugPreprocessor, MixupGenerator, TTAGenerator | StarcoderdataPython |
1714658 | <reponame>shreeramsigdel77/ram_utils
from matplotlib.colors import Normalize
from albumentations.core.composition import OneOf
from numpy.core.fromnumeric import shape
import torch
from torch import tensor
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoade... | StarcoderdataPython |
185322 | <reponame>szkkteam/agrosys
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Common Python library imports
# Pip package imports
# Internal package imports
from backend.api import ModelResource, Resource, ALL_METHODS, CREATE, DELETE, GET, LIST, PATCH, PUT
from backend.security.decorators import auth_required
from backen... | StarcoderdataPython |
122042 | <filename>checker/management/commands/run_check.py
from django.core.management.base import BaseCommand, CommandError
from checker.checker import run_check
import logging
class Command(BaseCommand):
def handle(self, *args, **options):
logger = logging.getLogger(__name__)
run_check(logger)
| StarcoderdataPython |
32164 | <filename>scripts/convert_0.0_to_0.1.py
#!/usr/bin/env python3
# Copyright (c) 2020 <NAME>
import sys
f = open(sys.argv[1])
for line in f:
s = line.strip()
if s.startswith("source:"):
id = s.split(":")[-1].strip()
indent = ' '*line.index("source")
sys.stdout.write(f"{indent}source:\n"... | StarcoderdataPython |
4837618 | <reponame>wuxiaofeng8764/P3SL_Example
from pprint import pprint
local_data = ['a', 'b', 1, 2]
local_data.append(local_data)
print('id(local_data) =>', id(local_data))
pprint(local_data)
| StarcoderdataPython |
168353 | import os
from flask.app import Flask
from oidcmsg.configure import Configuration
from oidcmsg.configure import create_from_config_file
from fedservice.configure import FedRPConfiguration
from fedservice.rp import init_oidc_rp_handler
dir_path = os.path.dirname(os.path.realpath(__file__))
def oidc_provider_init_ap... | StarcoderdataPython |
2809 | #!/usr/bin/env python
from CraftProtocol.NBT.NBTBase import NBTBase
from CraftProtocol.NBT.NBTProvider import NBTProvider
from CraftProtocol.StreamIO import StreamIO
class NBTTagList(NBTBase):
TYPE_ID = 0x09
def __init__(self, tag_type, values=None):
NBTBase.__init__(self)
if values is None... | StarcoderdataPython |
4805654 | <reponame>dikshaa1702/ml<filename>day7/send_receive.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 12:22:37 2019
@author: DiPu
"""
import requests
import json
Host = "http://172.16.31.10/api_v0.1/sending"
data = {
"student":{"Name":"diksha",
"Phone_No":"7231972592",
"College_name":"PCE",... | StarcoderdataPython |
1692656 | <gh_stars>10-100
from .weight_smooth_l1_loss import WeightSmoothL1Loss
from .weight_softmax_loss import WeightSoftmaxLoss
from .multibox_loss import MultiBoxLoss
from .hsd_multibox_loss import HSDMultiBoxLoss
from .focal_loss_sigmoid import FocalLossSigmoid
from .focal_loss_softmax import FocalLossSoftmax
__all__ = [... | StarcoderdataPython |
4814099 | import unittest
from reverse_string import reverseString
class TestReverseString(unittest.TestCase):
def test_zeroLengthInput(self):
"""We expect an empty string to be returned"""
self.assertEqual(reverseString(None),None)
def test_positiveLengthInput(self):
"""We expect the reverse ... | StarcoderdataPython |
3313324 | <reponame>CribberSix/pygame-texteditor
import pygame
import warnings
def handle_keyboard_input(self, pygame_events, pressed_keys) -> None:
for event in pygame_events:
if event.type == pygame.KEYDOWN:
# ___ COMBINATION KEY INPUTS ___
# Functionality whether something i... | StarcoderdataPython |
1634334 | <reponame>vincentschut/isce2
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2010 California Institute of Technology. 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.
... | StarcoderdataPython |
1639244 | <gh_stars>0
import boto3, os, json
from typing import Dict, List, Any, Union
from boto3 import Session
from botocore.exceptions import ClientError
class Entry:
def __init__(self, name, publickey, fingerprint):
self.name = name
self.publickey = publickey
self.fingerprint = fingerprint
... | StarcoderdataPython |
7157 | <filename>src/backend/tests/test_game/test_models.py
from unittest.mock import Mock, patch
import numpy as np
from game.models import ValuePolicyModel
def test_predict():
mask = np.zeros((9, 7, 8), dtype=bool)
mask[1, 2, 3] = 1
mask[6, 6, 6] = 1
tensor_mock = Mock()
policy_tensor = np.zeros((9... | StarcoderdataPython |
1775932 | <filename>lesson1.py<gh_stars>0
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Создаю экземпляр браузера
browser = webdriver.Chrome()
browser.get('https://uchi.ru/')
... | StarcoderdataPython |
3393521 | <reponame>garretthagen21/bluepi
import dbus
import dbusmock
import io
from pathlib import Path
import subprocess
# from gi.repository import GLib
from unittest import mock, skip
from tests.mock_eventloop import MockAsync, run_pending_events
from examples import eddystone_scanner
class TestExampleScanner(dbusmock.DBu... | StarcoderdataPython |
1722521 | <reponame>DanilooSilva/Cursos_de_Python<gh_stars>0
nome = input('Digite seu nome completo: ')
print('O nome possuí Silva: {}'.format(nome.count('Silva')))
print('O nome possuí Silva: {}'.format('Silva' in nome)) | StarcoderdataPython |
4827599 | from googletrans import Translator, constants
from pprint import pprint
# initilize the Google API translator
translator = Translator()
# this function is a translation function
# this function assumes the translation language is comming from english
# format: translate({text to translate}, {translate to})
def transl... | StarcoderdataPython |
143333 | <gh_stars>0
def get_num(capacity, p):
cell = []
for i in range(len(p) + 1):
cell.append([])
for j in range(capacity + 1):
cell[i].append(0)
for i in range(1, len(p) + 1):
for j in range(1, capacity + 1):
if p[i - 1] <= i:
cell[i][j] = max(p[i ... | StarcoderdataPython |
62425 | """
This is a simplified version to find statistical prevalence that counts instances and is numerically equivalent
to the confidence metric in association rules (# of occurrences / total occurrences).
"""
import csv
def count_stuff(filename):
"""
Counts instances and sorts them by prevalence
... | StarcoderdataPython |
1786580 | <reponame>kudzurunner/conan-opencv
from conans import ConanFile, CMake, tools
import os
class OpencvConan(ConanFile):
name = "opencv"
version = "4.1.2"
license = "https://raw.githubusercontent.com/opencv/opencv/master/LICENSE"
author = "KudzuRunner"
url = "https://github.com/kudzurunner/conan-open... | StarcoderdataPython |
54083 | from dagster import pipeline, ModeDefinition
from .resources import query_vm_resources
from .utilization import (
query_cpu_utilization, normalize_cpu_utilization,
query_mem_utilization, normalize_mem_utilization,
query_disk_utilization, normalize_disk_utilization,
default_azure_monitor_context
)
from .... | StarcoderdataPython |
22984 | <filename>evaluate/evaluate_debug.py
import os
import os.path as op
import numpy as np
import pandas as pd
import cv2
import tensorflow as tf
import settings
from config import opts
from tfrecords.tfrecord_reader import TfrecordReader
import utils.util_funcs as uf
import utils.convert_pose as cp
from model.synthesize.... | StarcoderdataPython |
1734995 | # -*- coding: utf-8 -*-
a=input();
b = a.split(" ")
m = int(b[0])
n = int (b[1])
if(m>n):
print(m)
elif(n>m):
print(n)
elif(n==m):
print(n) | StarcoderdataPython |
3249999 | import random
import numpy as np
import cv2
import lmdb
import torch
import torch.utils.data as data
import data.util as util
import sys
import os
try:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from data.util import imresize_np
from utils import util as utils
except Impor... | StarcoderdataPython |
3266706 |
# coding: utf-8
# In[1]:
#get_ipython().run_line_magic('reload_ext', 'autoreload')
#get_ipython().run_line_magic('autoreload', '2')
#get_ipython().run_line_magic('matplotlib', 'inline')
import platform
python_v = platform.python_version()
print (python_v)
# In[2]:
import numpy as np
import wget
import zipfile
i... | StarcoderdataPython |
1751702 | <reponame>Wolfmarsh/mpf
import asyncio
from mpf.tests.MpfTestCase import MpfTestCase, MagicMock, patch, call
class TestOsc(MpfTestCase):
def get_config_file(self):
return 'config.yaml'
def get_machine_path(self):
return 'tests/machine_files/osc/'
def get_platform(self):
# no fo... | StarcoderdataPython |
44743 | # contains connectors between discord api logic && command logic
from zdiscord.service.messaging.CommandFactory import CommandFactory
from zdiscord.service.ServiceFactory import ServiceFactory
from zdiscord.service.integration.chat.discord.DiscordEvents import DiscordEvent
from zdiscord.service.messaging.Events import ... | StarcoderdataPython |
3238225 | <gh_stars>0
# Retry when proxies fail
RETRY_TIMES = 3
# Retry on most error codes since proxies fail for different reasons
RETRY_HTTP_CODES = [500,503,504,400,403,404,408]
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.retry.RetryMiddleware':80,
'ScrapyRecruitment.ProxyMiddleware.ProxyMiddle... | StarcoderdataPython |
1380 | from typing import Dict, Any
from yaml import load
def get_config() -> Dict[str, Any]:
try:
return load(open('config/config.yml').read())
except Exception as e:
raise Exception('ERROR: Missing config/config.yml file.') from e
CONFIG = get_config()
| StarcoderdataPython |
189702 | <reponame>MrVoid918/GAN
from collections import OrderedDict
from functools import partial
from self_modulation import SelfModulationBN2D
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import spectral_norm
from norm import Norm
norms = {'BN': partial(nn.BatchNorm2d),
'IN': p... | StarcoderdataPython |
3328083 | import json
import time
import sys, traceback
import os
import yaml
import re
from random import shuffle
from dakd_vt import VirusTotalAPI
def initConf():
"""
every plugin uses its own config file
"""
return yaml.load(open(os.path.abspath('./dakd/plugins/dakd_cuckoo.conf'),'r'))
conf = initCon... | StarcoderdataPython |
104824 | <gh_stars>0
# -*- coding: utf-8 -*-
"""Module with the logic of the game even."""
import random
NAME = "Even"
RULES = 'Answer "yes" if the number is even, otherwise answer "no".'
def is_even(num):
"""Проверяем, является ли число простым или нет.
Args:
num (int): Случайное число от 1 до 10
Ret... | StarcoderdataPython |
165153 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | StarcoderdataPython |
1618223 | <reponame>DiegoStucchi/DiegosFirstPackageGit
from setuptools import setup, find_packages
VERSION = '0.0.1'
DESCRIPTION = 'My first (useless) package'
LONG_DESCRIPTION = 'My first (useless) package containing some basic (useless) functions that we can use to test whether it use installed correctly.'
# Setting up
setup... | StarcoderdataPython |
1644623 | line_layer = QgsProject.instance().mapLayer('[% @layer_id %]')
point_layer_name = 'points'
distance = 10000
fid = [% $id %]
line_feature = line_layer.getFeature(fid)
line_geometry = line_feature.geometry().buffer(distance, 5)
point_layer = QgsProject.instance().mapLayersByName(point_layer_name)[0]
nearby_points = [p.id... | StarcoderdataPython |
3232857 | # -*- coding: utf-8 -*-
"""
Verbose and colourful traceback formatting.
**ColorTB**
I've always found it a bit hard to visually parse tracebacks in Python. The
ColorTB class is a solution to that problem. It colors the different parts of a
traceback in a manner similar to what you would expect from a syntax-highlig... | StarcoderdataPython |
3201147 | from django.contrib.gis.geos import *
from django.contrib.gis.measure import D
from procyon.starsystemmaker.space_helpers import *
from django.contrib.gis.db import models
from procyon.starcatalog.models import Star, StarType, StarLuminosityType
import json
class StarModel(models.Model):
"""
Additional data a... | StarcoderdataPython |
9426 | <filename>emailmeld/sender.py<gh_stars>0
from django.core.mail.message import EmailMessage, EmailMultiAlternatives
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
def send_mail_task(subject, message, from_email, ... | StarcoderdataPython |
1600388 | <reponame>Ninja91/DnCensus
#!/usr/bin/python
__author__ = 'Nitin'
import threading
import marisa_trie as mt
import csv
import os.path
import marshal as Pickle
from backports import lzma as lz
IP6_INDEX_FILE = '_ip6_index.marisa'
NAME_INDEX_FILE = '_name_index.marisa'
def build_map(all_name_index_trie, all_target_i... | StarcoderdataPython |
121202 | # Generated by Django 3.2.5 on 2021-09-20 13:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0005_subscription'),
]
operations = [
migrations.AddField(
model_name='subscription',
name='customer_id',... | StarcoderdataPython |
148246 | #
# Copyright (c) 2017-2019 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import collections
import copy
import six
from netaddr import IPAddress
from netaddr import IPNetwork
from oslo_log import log
from sysinv._i18n import _
from sysinv.common import constants
from sysinv.common import except... | StarcoderdataPython |
3218750 | <reponame>cdlib/zephir-services<gh_stars>1-10
import os
from os.path import join, dirname
import sys
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.exc import IntegrityError
import envir... | StarcoderdataPython |
3211458 | from typing import Optional
from . import BasicType
class ReplyKeyboardRemove(BasicType):
fields = {
'remove_keyboard': BasicType.bool_interpreter,
'selective': BasicType.bool_interpreter
}
def __init__(self, obj=None):
super(ReplyKeyboardRemove, self).__init__(obj)
@classme... | StarcoderdataPython |
1762413 | # Generated by Django 3.0.10 on 2020-11-11 18:45
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_userprofile'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
... | StarcoderdataPython |
173794 | # Copyright 2018 ONES.AI
# 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, softwar... | StarcoderdataPython |
156860 | #!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
# Command line :
# python -m benchmark.AP1.explore
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as... | StarcoderdataPython |
3322573 | <gh_stars>0
import pickle
with open('../bin/fire_area.b', 'rb') as f:
FIRE_AREA = pickle.load(f)
with open('../bin/fire_clustering_200.b', 'rb') as f:
FIRE_CLUSTERING = pickle.load(f)
with open('../bin/fire_proba.b', 'rb') as f:
FIRE_PROBA = pickle.load(f)
| StarcoderdataPython |
4808074 | # -*- coding: utf-8 -*-
"""
Enrich BEL graphs
=================
In the current build it is possible to enrich BEL graphs containing metabolites with associated
disease or protein information and to enrich BEL graphs containing disease or protein information with associated metabolites.
This can be done with the functi... | StarcoderdataPython |
3272155 | #coding:utf-8
#
# id: bugs.core_2531
# title: The famous "cannot transliterate" error may be thrown when selecting data from the monitoring tables
# decription:
# In order to check issues of ticket we have to create Python script which is encoded in non-ascii codepage and also
# ... | StarcoderdataPython |
139908 | from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Sequential
class SimpleModel(object):
@staticmethod
def build_model(observation, actions, name=None):
return Sequential([
Flatten(input_shape=(1, observation)),
Dense(observation * 8, activat... | StarcoderdataPython |
133181 | import subprocess
import os.path
import re
from enum import Enum
from .base import TerrawareDevice
UpsStatus = Enum('UpsStatus', 'online onbattery lowbattery unknown')
# We could use the existence of these files in init_ to decide we don't need to start the services if they're already running, but just in case they g... | StarcoderdataPython |
1635942 |
########### Python 3.6 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64, requests, json, cv2
import numpy as np
import cv2
import os
import keyboard
from time import sleep
import pygame
import sys
import random
import keyboard
###############################################
#### Up... | StarcoderdataPython |
36100 | import qrcode
# data example
data = "www.google.com"
# file name
file_name = "qrcode.png"
# generate qr code
img = qrcode.make(data=data)
# save generated qr code as img
img.save(file_name)
| StarcoderdataPython |
125531 | from django.apps import AppConfig
class EthicaConfig(AppConfig):
name = 'Ethica'
| StarcoderdataPython |
4811360 | <gh_stars>1-10
# Api Agenda Lionx
from src.routers.schedule.signature import RoutesSignature
from docs.api_specifications import DocsSpecifications
# Third party
from flask import Flask
app = Flask(__name__)
routes = RoutesSignature()
routes.init_routes(app)
specs = DocsSpecifications()
specs.init_spec(app)
if __n... | StarcoderdataPython |
1693234 | <gh_stars>1-10
from .extensions import mail
from flask_mail import Message
from threading import Thread
from flask import render_template,current_app
def send_async_mail(app,email):
with app.app_context():
mail.send(email)
def send_mail(to,subject,templates,**kwargs):
message = Message(sub... | StarcoderdataPython |
54752 | <gh_stars>10-100
import math
from torch.nn import init, Module
__all__ = ['sqrt_uniform_init']
def sqrt_uniform_init(component: Module):
for weight in component.parameters():
stdv = 1.0 / math.sqrt(weight.shape[-1])
init.uniform_(weight, -stdv, stdv)
| StarcoderdataPython |
138781 | from enum import Enum
from monai.networks.layers.factories import Act
class Activations(Enum):
leaky_relu = "leaky_relu"
relu = "relu"
tanh = "tanh"
swish = "swish"
cos = "cos"
liht = "liht"
piecewise_linear = "piecewise_linear"
linear = "linear"
def __str__(self):
... | StarcoderdataPython |
2179 | from django.db import models
# Create your models here.
# Station
class Stations(models.Model):
stationName = models.CharField(max_length=100)
stationLocation = models.CharField(max_length=100)
stationStaffId = models.CharField(max_length=100)
date = models.DateTimeField(auto_now_add=True)
d... | StarcoderdataPython |
3309084 | <reponame>burdettadam/token-plugin
from sovtokenfees import FeesTransactions
from sovtokenfees.constants import FEE
from sovtokenfees.messages.fields import GetFeeMsg
from sovtokenfees.req_handlers.fees_utils import FeesStaticHelper
from plenum.common.constants import ALIAS, STATE_PROOF, CONFIG_LEDGER_ID, BLS_LABEL
fr... | StarcoderdataPython |
36404 | from . import wallet_pb2_grpc as wallet_grpc
from . import wallet_pb2 as wallet
__all__ = [
"wallet_grpc",
"wallet",
]
| StarcoderdataPython |
3386488 | <gh_stars>0
import asyncio
import operator
from functools import reduce
import pytest
from .server import RPCServer
from .client import RPCClient
@pytest.fixture
def server_port(aiomisc_unused_port):
return aiomisc_unused_port
@pytest.fixture
def handlers():
return {
'foo': lambda: 'bar',
... | StarcoderdataPython |
3254987 | <filename>openpnm/models/misc/__init__.py
r"""
**openpnm.models.misc**
----
This submodule contains models for calculating general or generic values
that are useful for all other pore-scale models, such as scaling values, or
generating an array of random numbers.
"""
from .statistical_distributions import generic_... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.