id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1689066 | <gh_stars>1-10
#!/usr/bin/env python
import roslib
roslib.load_manifest('sheldon_servos')
import rospy
from std_msgs.msg import Float64
# Servo Position Command Publishers
pub_chest_camera_tilt = rospy.Publisher('/chest_camera_tilt_joint/command', Float64, queue_size=1)
| StarcoderdataPython |
1661467 | from django.contrib import admin
from .models import BloodBank
# Register your models here.
admin.site.register(BloodBank) | StarcoderdataPython |
1611851 | # Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.
import copy
from dace import properties, symbolic
import dace.library
import dace.sdfg.nodes
from dace.sdfg import SDFG, SDFGState
from dace import memlet as mm, data as dt
from dace.transformation.transformation import ExpandTransformation
fro... | StarcoderdataPython |
3239010 | works = {
'schema': {
'title': {
'type': 'string',
'required': True,
},
'description': {
'type': 'string',
},
'owner': {
'type': 'objectid',
'required': True,
# referential integrity constraint: value mus... | StarcoderdataPython |
1610199 | import sys
import os
import numpy as np
import cv2
import torch
from model import *
from scipy.ndimage.filters import gaussian_filter
from loss import kldiv, cc, nss
import argparse
from torch.utils.data import DataLoader
from dataloader import DHF1KDataset
from utils import *
import time
from tqdm import tqdm
from to... | StarcoderdataPython |
65678 | from __future__ import unicode_literals
import logging
from django.core.management.base import BaseCommand
from django.db.models import F
from scripts import utils as script_utils
from osf.models import PreprintService
from website.preprints.tasks import on_preprint_updated
logger = logging.getLogger(__name__)
def ... | StarcoderdataPython |
127668 | argv = ['']
def exit(n):
pass
exit(0)
stdout = open("/dev/null")
stderr = open("/dev/null")
stdin = open("/dev/null")
| StarcoderdataPython |
1624001 | #! /usr/bin/env python
#
# This file is part of khmer, http://github.com/ged-lab/khmer/, and is
# Copyright (C) Michigan State University, 2009-2013. It is licensed under
# the three-clause BSD license; see doc/LICENSE.txt.
# Contact: <EMAIL>
#
import sys
import screed.fasta
import os
import khmer
from khmer.thread_uti... | StarcoderdataPython |
74911 | <reponame>PredadorAkrid/IS-2020-2-La-Orden-De-Turing
from django.urls import path
from django.conf.urls import url, include
from administrador import views
from .views import *
import repartidor
from repartidor import views
app_name = "administrador"
urlpatterns = [
# temporal, no se llamarán así las vistas
... | StarcoderdataPython |
3218021 | <reponame>ab93/Depression-Identification
import os
TRAIN_SPLIT_FILE = os.path.join('data','classification_data','training_split.csv')
TEST_SPLIT_FILE = os.path.join('data','classification_data','test_split.csv')
VAL_SPLIT_FILE = os.path.join('data','classification_data','dev_split.csv')
D_ND_DIR = os.path.join('data',... | StarcoderdataPython |
78384 | <reponame>cj-wong/photo-dash-sds011
from dataclasses import asdict, dataclass
from typing import Dict, List, Union
@dataclass
class AirQualityRange:
"""Represents a single air quality range given an associated PM size.
Attributes:
label (str): the quality label for this range, e.g. Good
pm (f... | StarcoderdataPython |
3342553 | <reponame>sLiinuX/wxRaven
'''
Created on 1 janv. 2022
@author: slinux
'''
from .wxRavenIPFSDesign import *
from wxRavenGUI.application.wxcustom.CustomLoading import *
from wxRavenGUI.application.wxcustom import *
import wx.html2 as webview
import sys
import logging
from wxRavenGUI.application.wxcustom.CustomUserIO i... | StarcoderdataPython |
3278333 | from ..qt.QtWebKit import QWebView, QWebSettings
from qt_ace_editor import QtAceEditor
class QtAceEditorView(QWebView):
def __init__(self, parent=None):
""" Initialize the editor window
"""
super(QtAceEditorView, self).__init__(parent)
self.ace_editor = QtAceEditor()
# XX... | StarcoderdataPython |
3244846 | #!/usr/bin/env python
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.
import os.path
from setuptools import setup
import sys
try:
from Cython.Build import cythonize
have_cython = True
except:
have_cython = False
name = "Mini-AMF"
description = "AMF serialization and deserialization su... | StarcoderdataPython |
3361662 | <filename>Modules/mlp.py
import torch
from Modules.vae_attention import VAE_Attention
import torch.nn.functional as F
class Mlp(torch.nn.Module):
def __init__(self, vae, vocab_dict, input_size, hidden_size):
super(Mlp, self).__init__()
self.vae = vae
self.vocab_dict = vocab_dict
se... | StarcoderdataPython |
3226934 | <gh_stars>0
from cfg import *
from context_menu import menus
from PyPDF2 import PdfFileWriter, PdfFileReader
import tkinter
from tkinter import messagebox
import tkinter as tk
# from time import sleep
import os
def remove_ext(filename: str):
# TODO: this is hardcoded linux path separator. Make dynamic or be able ... | StarcoderdataPython |
3327378 | <filename>google/cloud/networkmanagement/v1beta1/networkmanagement-v1beta1-py/google/cloud/networkmanagement/__init__.py
# -*- coding: utf-8 -*-
# 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 ob... | StarcoderdataPython |
1650497 | # Make py2 like py3
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import ( # pylint: disable=redefined-builtin, unused-import
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, super,
filter, map, zip
)
... | StarcoderdataPython |
4833350 | <reponame>Diegof2612/Algoritmos-y-Programaci-n-Talleres<filename>Taller de Estructuras de control secuenciales/punto11.py
"""
ENTRADAS
horas_trabajadas-->float-->ht
valor_por_hora-->float-->vxh
horas_extras-->float-->hext
bonus_hext-->float-->bonus_hext
paro_forzoso-->float-->paro_forzoso
politica_habitacional-->float-... | StarcoderdataPython |
3258311 | #!/bin/python3
'''
https://www.hackerrank.com/challenges/30-loops
Given an integer, n, print its first 10 multiples. Each multiple n x i (where 1 <= i <= 10)
should be printed on a new line in the form: n x i = result.
'''
if __name__ == '__main__':
n = int(input())
for i in range(1, 11):
print(n, 'x... | StarcoderdataPython |
1748208 | <filename>csl/solver_base.py
# -*- coding: utf-8 -*-
"""Base constrained learning solver
Base primal-dual solver.
"""
import numpy as np
import torch
import matplotlib.pyplot as plot
import logging
class SolverSettings():
"""Primal-dual solver settings
Attributes
----------
settings : `dict`, op... | StarcoderdataPython |
3313157 | <reponame>sebasrp/sgbikecrawler
import regex as re
import urllib.parse
from decimal import Decimal
from bs4 import BeautifulSoup
import requests
from tqdm import tqdm
import dateparser
from dateparser.search import search_dates
from vehicle_ad import VehicleAd
class Carousell:
BASE = "https://sg.carousell.com"
... | StarcoderdataPython |
1604023 | <reponame>deathbeds/jupyter-graphql
def CM(info):
app = info.context["_app"] if isinstance(info.context, dict) else info.context._app
return app.contents_manager
def RESOLVE_CONTENT(it, info):
return it["content"] or CM(info).get(it["path"])["content"]
def GET(attr):
return lambda it, info: it.get(a... | StarcoderdataPython |
4824348 | <gh_stars>10-100
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilit... | StarcoderdataPython |
3366630 | # -*- coding: utf-8 -*-
from besttags.util import merge, limit, Tags
from besttags.apis import best_hashtags, ritetag, instatag, displaypurposes
class Manager:
"""This make great stuff."""
def __init__(self, kind='simple', count=30, weights=[], fix=[]):
self.kind = kind
self.limit = count
... | StarcoderdataPython |
3273130 | from . import db
from dataclasses import dataclass
from typing import List
from datetime import datetime
@dataclass
class UserModel(db.Model):
__tablename__ = "users"
id: int = db.Column(db.Integer, primary_key=True)
name: str = db.Column(db.String)
email: str = db.Column(db.String)
token: str = ... | StarcoderdataPython |
1700147 | default_app_config = 'note.apps.NoteConfig'
| StarcoderdataPython |
3289841 | # -*- coding: utf-8 -*-
from JapaneseTokenizer.kytea_wrapper import KyteaWrapper
from JapaneseTokenizer.datamodels import TokenizedResult, TokenizedSenetence, FilteredObject
import unittest
class TestKyteaWrapperPython2(unittest.TestCase):
def setUp(self):
pass
def test_tokenization(self):
in... | StarcoderdataPython |
1616865 | import unittest
import tlpy.defect
import tlpy.host
import numpy as np
from unittest.mock import Mock
class DefectTestCase( unittest.TestCase ):
"""Test for `defect.py`"""
def setUp( self ):
elemental_energies = { 'Ge' : -4.48604,
'P' : -5.18405,
'O' : ... | StarcoderdataPython |
1766741 | import asyncio
import logging
import os
import time
import unittest
from integration_tests.env_variable_names import (
SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN,
SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID,
SLACK_SDK_TEST_GRID_TEAM_ID,
SLACK_SDK_TEST_GRID_USER_ID,
)
from integration_tests.helpers import async_... | StarcoderdataPython |
3257216 | from app import create_app
application = create_app()
if __name__ == '__main__':
# This is used when running locally. Gunicorn is used to run the
# application on Google App Engine. See entrypoint in app.yaml.
# Using "application" instead of the standard "app" to prevent errors.
application.run(host=... | StarcoderdataPython |
3221080 | <filename>spyder/widgets/tests/test_pathmanager.py
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
Tests for pathmanager.py
"""
# Standard library imports
import sys
import os
# Test library imports
import pytest
from qtpy import PYQT4
from qtpy.... | StarcoderdataPython |
1633114 | <gh_stars>1-10
import warnings
from functools import wraps
class generic_deprecation(object):
def __init__(self, message, warning_class=DeprecationWarning, stack_level=2):
self.message = message
self.warning_class = warning_class
self.stack_level = stack_level
def __call__(self, metho... | StarcoderdataPython |
62832 | from __future__ import absolute_import
import re
import os
import json
import xml.etree.ElementTree as ET
from svtplay_dl.service import Service, OpenGraphThumbMixin
from svtplay_dl.utils import is_py2_old
from svtplay_dl.error import ServiceError
from svtplay_dl.log import log
from svtplay_dl.fetcher.rtmp import RTMP... | StarcoderdataPython |
192694 | # Copyright (C) 2020 Clariteia SL
#
# This file is part of minos framework.
#
# Minos framework can not be copied and/or distributed without the express
# permission of Clariteia SL.
import functools
from aiohttp import (
web,
)
from ..configuration import (
MinosConfig,
)
from ..importlib import (
import... | StarcoderdataPython |
3319873 | import os
import logging
from abc import ABCMeta, abstractmethod
import numpy as np
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import pandas as pd
import h5py
from specutils import Spectrum1D
from astropy import units as u
logger = logging.getLogger(__name__)
class BaseSpectralGr... | StarcoderdataPython |
3361 | # 1. Create students score dictionary.
students_score = {}
# 2. Input student's name and check if input is correct. (Alphabet, period, and blank only.)
# 2.1 Creat a function that evaluate the validity of name.
def check_name(name):
# 2.1.1 Remove period and blank and check it if the name is comprised with on... | StarcoderdataPython |
3304142 | from Cython.Build import cythonize
import os
from os.path import join as pjoin
import numpy as np
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
try:
numpy_include = np.get_include()
except AttributeError:
numpy_include = np.get_numpy_include()... | StarcoderdataPython |
3210994 | import argparse
import operator
import sys
import os
import setGPU
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from data import get_batch
from meta_optimizer import MetaModel, MetaOptimizer, FastMetaOptimizer
from model import Model
from torch.autogr... | StarcoderdataPython |
1788567 | <reponame>Hour-Sirak/Hour-Sirak<gh_stars>0
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers
class Keypad:
def __init__(self, keys, rowPins, colPins, Lcd):
self.ROW = rowPins
self.COL = colPins
self.keys = keys
self.Lcd = Lcd
self.key = set()
... | StarcoderdataPython |
3281832 | <reponame>ChyavanKoushik/-My-Solutions-to-Leetcode-problems-using-Python-3
class Solution:
dict = {0:1, 1:1}
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
if n in self.dict.keys():
return self.dict[n]
summ=0
for i in ra... | StarcoderdataPython |
3218244 | """
network.py
~~~~~~~~~~
A module to implement the stochastic gradient descent learning
algorithm for a feedforward neural network. Gradients are calculated
using backpropagation. Note that I have focused on making the code
simple, easily readable, and easily modifiable. It is not optimized,
and omits many desirab... | StarcoderdataPython |
3208038 | """codeCounter URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | StarcoderdataPython |
3325115 | <reponame>kimKate/nplus1<gh_stars>0
from concurrent.futures import process
import json
import csv
from SlavicNames.parse_fio import fio_parse, gender_parse
data = json.load(open('data2015.json'))
# for article in data['articleData']:
# article['gender'] = gender_parse(article['author'])
# print(article['title... | StarcoderdataPython |
1647292 | # -*- mode: Python; tab-width: 4 -*-
#
# Walk the root directory of a project and create a table containing details
# of the files and directories it contains
#
import sys
import getopt
import os
import os.path
import subprocess
import configparser
import cmd
import json
import ctags
import sqlite3
ConfigFile = "tagba... | StarcoderdataPython |
3359140 | <gh_stars>0
"""TODO."""
from testplan.testing.multitest.driver.base import Driver
def test_pre_post_callables():
class MyDriver(Driver):
def __init__(self, **options):
super(MyDriver, self).__init__(**options)
self.pre_start_called = False
self.post_start_called = Fals... | StarcoderdataPython |
68761 | from helper.shapenet.shapenetMapper import desc_to_id
from deformations.FFD import get_template_ffd
from deformations.meshDeformation import get_thresholded_template_mesh
from mayavi import mlab
import numpy as np
from graphicUtils.visualizer.mayaviVisualizer import visualize_mesh, visualize_point_cloud
ds = get_tem... | StarcoderdataPython |
171169 | <reponame>t-sakai-kure/PNU-Classification<gh_stars>100-1000
"""
Common calculation.
"""
import numpy as np
#import check
def cv_index(n, n_fold):
index = (np.arange(n, dtype=np.int)*n_fold)//n
return index[np.random.permutation(n)]
def squared_dist(x, c):
# assert x.shape[1] == c.shape[1], "Dimension ... | StarcoderdataPython |
4824738 | <gh_stars>0
class WFA:
def __init__():
pass
if __name__ == '__main__':
wfa = WFA()
| StarcoderdataPython |
1773908 | from django import template
register = template.Library()
register.simple_tag
@register.filter(name='cssname')
def cssname(value):
"""Replaces all spaces with a dash to be a valid id for a cssname"""
return value.replace(' ', '-') | StarcoderdataPython |
3305119 | <gh_stars>0
#!/usr/bin/env python
"""Get random lines for various characters in the film TOP GUN."""
from random import choice
import re
import os
class TopGun(object):
CHARACTERS = {
"mav": r"MAVERICK",
"iceman": r"ICE(MAN)?",
"goose": r"GOOSE",
"jester": r"JESTER",
"v... | StarcoderdataPython |
1771442 | <gh_stars>1-10
__all__ = ["data_preprocessing", "model", "trainer"]
| StarcoderdataPython |
143109 | <reponame>qbilius/autoart
import sys
import psychopy
from psychopy import visual, core
import numpy as np
import scipy.ndimage
import matplotlib.pyplot as plt
import matplotlib as mpl
from PIL import Image
# import hmax
class Filters(object):
def gabor(self,theta=0, gamma=1, sigma=2, lam=5.6,k=10):
# g = n... | StarcoderdataPython |
112738 | import numpy as np
from conftest import EPS
from testutils import (
CLUSTER_LABEL_FIRST_CLUSTER,
CLUSTER_LABEL_NOISE,
assert_cluster_labels,
assert_label_of_object_is_among_possible_ones,
assert_two_objects_are_in_same_cluster,
insert_objects_then_assert_cluster_labels,
reflect_horizontally... | StarcoderdataPython |
3309740 | import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range, xlabel, ylabel, filename):
x = np.array(x_range)
y = eval(formula)
plt.plot(x, y)
plt.xlim(0, 5000)
# plt.xscale("log", nonposx='clip')
# plt.yscale("log", nonposy='clip')
# plt.show()
plt.xlabel(xlabel)
... | StarcoderdataPython |
3272744 | <reponame>erezsh/runtype<gh_stars>10-100
"""
Enhances Python's built-in dataclass, with type-checking and extra ergonomics.
"""
import random
from copy import copy
import dataclasses
from typing import Union
from abc import ABC, abstractmethod
from .common import CHECK_TYPES
from .validation import TypeMismatchError,... | StarcoderdataPython |
1792820 | <reponame>douglasdavis/tdub<filename>src/tdub/frames.py
"""Module for handling dataframes."""
from __future__ import annotations
# stdlib
import logging
import re
from typing import Optional, Union, List, Iterable
# externals
import pandas as pd
import uproot
# tdub
import tdub.config
from tdub.data import (
R... | StarcoderdataPython |
1729495 | <filename>xView/dataset.py
from __future__ import absolute_import
import tensorflow as tf
import numpy as np
import os
import ast
class Dataset(object):
def __init__(self, file_path, anchor_path):
self.path = file_path
self.anchor_path = anchor_path
self.dataset = tf.data.TFRecordDataset(... | StarcoderdataPython |
1613870 | <gh_stars>0
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | StarcoderdataPython |
3231143 | # malwarescan/cli.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from operator import attrgetter
import click
from flask import current_app
from flask_appfactory.cli import clifactory
from flask_cli import with_appcontext
from .app import create_app
cli = clifactory(create_app)
... | StarcoderdataPython |
1604882 | from face_detection import Detector
from face_verification.OneShotFaceVerification import Verifier
from data_source import CCTV
import cv2
from utils import *
import os
from dotenv import load_dotenv
from menu_pages import *
import json
from threading import Thread
import time
from multiprocessing import Process
detec... | StarcoderdataPython |
1755443 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Demo showing functionality from insegtbasis on CT image of glass fibres.
Created on Wed Oct 14 12:11:48 2020
@author: <EMAIL>
"""
import PIL.Image # using PIL for easier treatment of indexed rgb images
import numpy as np
import matplotlib.pyplot as plt
import insegtb... | StarcoderdataPython |
1682246 | """
Agent is something which converts states into actions and has state
"""
import copy
import numpy as np
import torch
import torch.nn.functional as F
from . import actions
class BaseAgent:
"""
Abstract Agent interface
"""
def initial_state(self):
"""
Should create initial empty stat... | StarcoderdataPython |
4811964 | <gh_stars>1-10
"""Uses setuptools to install the torchluent module"""
import setuptools
import os
setuptools.setup(
name='torchluent',
version='0.0.4',
author='<NAME>',
author_email='<EMAIL>',
description='Build pytorch models in a fluent interface',
license='CC0',
keywords='torc... | StarcoderdataPython |
1702840 | from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from . import views
app_name = 'djangoapp'
urlpatterns = [
# path for about view
path(route='about/', view=views.about, name='about'),
# path for contact us vie... | StarcoderdataPython |
1685648 | <gh_stars>0
import json
import pytz
from django.conf import settings
from rest_framework import serializers
from apps.utils.timezone_utils import formatted_ts
class DeviceDataMaskSerializer(serializers.Serializer):
start = serializers.DateTimeField(format='%Y-%m-%dT%H:%M:%SZ', required=False)
end = serial... | StarcoderdataPython |
3328963 | """
Write a Python program to check a list is empty or not.
"""
l = []
if not l:
print("List is empty") | StarcoderdataPython |
3340837 | <filename>li_privacy/Request.py
from __future__ import print_function
import json
import time
class Request(object):
"""Represents a request payload to the li-privacy API"""
def __init__(self, operation, path, domain_name, key_id, callback_url, scope=None, identifiers=None, request_id=None, iat=int(time.time(... | StarcoderdataPython |
70253 | from .pandas_vb_common import *
from random import shuffle
class Reindexing(object):
goal_time = 0.2
def setup(self):
self.rng = DatetimeIndex(start='1/1/1970', periods=10000, freq='1min')
self.df = DataFrame(np.random.rand(10000, 10), index=self.rng,
columns=range... | StarcoderdataPython |
110123 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from django.contrib.auth import get_user_model
from django.core import signing
from django.http import Http404
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views import generic
from django.... | StarcoderdataPython |
186902 | import os
# linesep = os.linesep.encode('ascii')
linesep = b'\n'
def dir_parts(dir: str) -> tuple[str]:
return tuple(os.path.normpath(dir).split(os.sep))
def is_in_dir(dir: str, in_: tuple[str]) -> bool:
return tuple(dir.split(os.sep, len(in_)))[:len(in_)] == in_
def is_in_dirs(dir: str, in_: tuple[tuple... | StarcoderdataPython |
1704938 | <reponame>ihorsuniversalapps/slack_history_bot<gh_stars>0
#!/usr/bin/env python
import datetime
import os
import time
from pymongo import MongoClient
from slackclient import SlackClient
BOT_NAME = 'historybot'
BOT_ID = '--'
slack_client = SlackClient(os.environ.get('HISTORY_SLACK_BOT_KEY'))
mongo_client = MongoClie... | StarcoderdataPython |
4814656 | <filename>githuborganizer/__init__.py<gh_stars>10-100
from celery import Celery
import os
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
SETTINGS = [
'DEBUG',
'GITHUB_PRIVATE_KEY',
'GITHUB_APP_ID',
'GITHUB_WEBHOOK_SECRET',
'CELERY_BROKER',
'PROCESS_INS... | StarcoderdataPython |
3346713 | import pytest
import falcon
from falcon import testing
from _util import create_app # NOQA
@pytest.mark.parametrize('asgi', [True, False])
def test_custom_router_add_route_should_be_used(asgi):
check = []
class CustomRouter:
def add_route(self, uri_template, *args, **kwargs):
check.app... | StarcoderdataPython |
22181 | <reponame>BradleyKirton/django_dramatiq
import os
import sys
from io import StringIO
from unittest.mock import patch
from django.core.management import call_command
from django_dramatiq.management.commands import rundramatiq
def test_rundramatiq_command_autodiscovers_modules():
assert rundramatiq.Command().disco... | StarcoderdataPython |
3210966 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""config for pytest."""
def pytest_configure(config):
"""Configure pytest."""
plugin = config.pluginmanager.getplugin("mypy")
plugin.mypy_argv.append("--ignore-missing-imports")
| StarcoderdataPython |
119716 | # Generated by Django 2.1.8 on 2019-10-20 01:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api_v1', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='map_lat',
field... | StarcoderdataPython |
18547 | <filename>Tests/playground.py
import matplotlib.pyplot as plt
plt.plot()
plt.show() | StarcoderdataPython |
1749530 | import dpkt
__author__ = "<NAME>"
class DPKTHelper(object):
"""
A Façade for DPKT module.
"""
def __init__(self):
self.ssl_port = 443
self.handshake_byte = 22
self.reader = None
def read_packet(self, packet):
"""
Reads a packet.
:param packet: Pack... | StarcoderdataPython |
3208386 | <reponame>PapenfussLab/Mungo
#!/usr/bin/env python
"""
fastaRenameToIndex.py <input file> <output file> [<index file> default=index.txt]
Author: <NAME>
Date: Fri Mar 7 13:32:40 EST 2008
"""
import sys
import re
import mungo.fasta as fasta
iFilename = sys.argv[1]
oFilename = sys.argv[2]
if len(sys.argv)==4:
i... | StarcoderdataPython |
1691636 | <gh_stars>0
import sqlite3
from .config import DATABASE_URI
class SqliteManager:
@staticmethod
def get_db():
print(DATABASE_URI)
db = sqlite3.connect(database=DATABASE_URI, timeout=5)
return db
@staticmethod
def close_connection(db):
if db is not None:
db.c... | StarcoderdataPython |
3306619 | <reponame>maxzhenzhera/my_vocab_backend
from pydantic import (
BaseConfig,
BaseModel
)
__all__ = [
'IDModelMixin',
'ModelWithOrmMode'
]
class IDModelMixin(BaseModel):
id: int
class ModelWithOrmMode(BaseModel):
class Config(BaseConfig):
orm_mode = True
| StarcoderdataPython |
3281029 | <reponame>johnnygreco/astrostamps<filename>astrostamps/tools.py
import os
try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
from io import BytesIO
import requests
from getpass import getpass
import xml.etree.ElementTree as ET
from PIL import Image
import numpy as np
from mat... | StarcoderdataPython |
4801951 | import os
import numpy as np
import torch
import cv2
import rlkit.torch.sac.diayn
from .mode_actions_sampler import ModeActionSampler
from network import ModeDisentanglingNetwork
from env import OrdinaryEnvForPytorch
class DisentanglingDiversityTester:
def __init__(self,
latent_model_path,
... | StarcoderdataPython |
3315352 | # -*- coding: utf-8 -*-
import sys
import hmac
import time
import random
import hashlib
import json
import urllib
import base64
import os
pv = "python2"
if sys.version_info[0] < 3:
from urllib import quote
from urllib import urlencode
else:
from urllib.parse import quote
from urllib.parse import urlenc... | StarcoderdataPython |
49782 | <reponame>C-Mierez/Web3-Solidity
from scripts.utils import get_account
from brownie import interface, config, network, accounts
from web3 import Web3
def get_weth():
"""
Mint wETH by depositing ETH
"""
account = get_account()
# Need to get the ABI and the Address of the contract
weth = inte... | StarcoderdataPython |
187242 | <reponame>gilbertohasnofb/auxjad<filename>tests/mutate/test_rests_to_multimeasure_rest.py<gh_stars>1-10
import abjad
import auxjad
def test_rests_to_multimeasure_rest_01():
staff = abjad.Staff(r"r1")
auxjad.mutate.rests_to_multimeasure_rest(staff[:])
assert abjad.lilypond(staff) == abjad.String.normalize... | StarcoderdataPython |
4841985 | <reponame>ijufumi/demo-python
from lark import Lark
from typing import Tuple, Any
class Environment(object):
def __init__(self, parent_env):
self._parent_env = parent_env
self._env = dict()
def get(self, key, default=None):
value = self._env.get(key, None)
if value is None and... | StarcoderdataPython |
1729903 | from math import pi, log
from itertools import accumulate
from typing import Union, List
import numpy as np
import torch as th
from torch import nn
import torch.nn.functional as F
from scipy.signal import lfilter
from ail.common.utils import zip_strict
LOG2PI = log(2 * pi)
def pure_discount_cumsum(x: Union[list, ... | StarcoderdataPython |
1650008 | <reponame>cs-fullstack-2019-fall/python-basic-review-1-ic-insideoutzombie
### Create a ```main``` function and a function for each exercise. Call each exercise from ```main```
# 1. Variables:
# - Define a variable called 'season' and assign it your favorite season as a String.
# Print 'My favorite season is Fall' (use... | StarcoderdataPython |
1707076 | <gh_stars>1-10
'''entre no programa com um número e sai com este número em quantidade
de sequência de fibonacci'''
cont = 3 # a partir do 3 indice começa a lógica
t1 = 0
t2 = 1
print('{:-^40}'.format('SEQUÊNCIA DE FIBONACCI'))
quantidade = int(input('Qual quantidade de números quer ver na Sequência? '))
print(f'\033[1;... | StarcoderdataPython |
1682650 | <reponame>uuk0/mcpython-7-pretests
def position2chunk(position):
return position[0] // 16, position[2] // 16
| StarcoderdataPython |
3302679 | # File: exp.py
# Author: raycp
# Date: 2019-06-08
# Description: exp for EasiestPrintf, trigger malloc by printf
from pwn_debug import *
pdbg=pwn_debug("./EasiestPrintf")
pdbg.context.terminal=['tmux', 'splitw', '-h']
#pdbg.local()
pdbg.debug("2.27")
#pdbg.remote('127.0.0.1', 22)
#p=pdbg.run("local")
#p=pdbg.run(... | StarcoderdataPython |
154021 | <gh_stars>1-10
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from django.conf import settings
from django.db import models
from accelerator_abstract.models.accelerator_model import AcceleratorModel
class BaseProgramRoleGrant(AcceleratorModel):
per... | StarcoderdataPython |
72306 | <reponame>gigaquads/tunafish<filename>tunafish/tuning/parameter_specification.py
from inspect import Parameter
from typing import (
Dict, Any, Type, Tuple, List, Text,
Set, Optional
)
class ParameterSpecification:
"""
The ParameterSpecification contains data necessary to convert the output
of a ge... | StarcoderdataPython |
21035 | from .mem_bank import RGBMem, CMCMem
from .mem_moco import RGBMoCo, CMCMoCo
def build_mem(opt, n_data):
if opt.mem == 'bank':
mem_func = RGBMem if opt.modal == 'RGB' else CMCMem
memory = mem_func(opt.feat_dim, n_data,
opt.nce_k, opt.nce_t, opt.nce_m)
elif opt.mem == '... | StarcoderdataPython |
3365386 | <gh_stars>1-10
#!/usr/bin/env python
#
# Copyright 2011-2020 Splunk, 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 require... | StarcoderdataPython |
124773 | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2017, <NAME> <<EMAIL>>
# License: http://pyasn1.sf.net/license.html
#
from pyasn1.type import univ, tag
class NumericString(univ.OctetString):
tagSet = univ.OctetString.tagSet.tagImplicitly(
tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple... | StarcoderdataPython |
1764410 | <reponame>Nawarrr/wagtail<filename>wagtail/tests/search/__init__.py
default_app_config = "wagtail.tests.search.apps.WagtailSearchTestsAppConfig"
| StarcoderdataPython |
1623607 | <gh_stars>1-10
from typing import Callable, Optional, Awaitable
from slack_sdk.errors import SlackApiError
from slack_sdk.oauth.installation_store import Bot
from slack_sdk.oauth.installation_store.async_installation_store import (
AsyncInstallationStore,
)
from slack_bolt.auth.result import AuthorizationResult
f... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.