id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
4858587 | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='acapi2',
version='2.0.0-a1',
url='https://github.com/pmatias/python-acquia-cloud-2',
download_url='https://pypi.python.org/pypi/TBD',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description='Acqu... | StarcoderdataPython |
1709748 | <gh_stars>0
import sys
import math
class IV:
def IV(t):
H = [int('6a09e667f3bcc908', 16) ^ int('a5a5a5a5a5a5a5a5', 16),
int('bb67ae8584caa73b', 16) ^ int('a5a5a5a5a5a5a5a5', 16),
int('3c6ef372fe94f82b', 16) ^ int('a5a5a5a5a5a5a5a5', 16),
int('a54ff53a5f1d36f1', 16) ^ int('a5a5a5a5a5... | StarcoderdataPython |
1748461 | """
Gentle Hands-On Introduction to Python: course project
"""
import sys
if not "-m" in sys.argv:
from .distance import align, edit_distance, needleman_wunsch
from .assemble import assemble, score
| StarcoderdataPython |
3360706 | <filename>py4e/exercises/exercise_13_1.py<gh_stars>1-10
"""
Extracting Data from XML
In this assignment you will write a Python program somewhat similar to
http://www.py4e.com/code3/geoxml.py. The program will prompt for a URL,
read the XML data from that URL using urllib and then parse and extract
the comment counts ... | StarcoderdataPython |
1980606 | <gh_stars>0
pkgname = "transset"
pkgver = "1.0.2"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
makedepends = ["libxt-devel"]
pkgdesc = "Sets the transparency of an X window"
maintainer = "q66 <<EMAIL>>"
license = "MIT"
url = "https://xorg.freedesktop.org"
source = f"$(XORG_SITE)/app/{pkgname}-... | StarcoderdataPython |
12844454 | <filename>fastquotes/fund/history.py
import json
from datetime import datetime
from typing import Optional
import requests
from ..const import CUSTOM_HEADER
def get_dividend(msg: str) -> Optional[float]:
if not msg:
return None
left, right = 0, len(msg) - 1
while not msg[left].isdigit() or not m... | StarcoderdataPython |
3519623 | <filename>voidpp_tools/logger_proxy.py<gh_stars>0
class LoggerProxy(object):
def __init__(self, level):
self.level = level
def write(self, msg):
if msg != '\n':
self.level(msg)
def flush(self):
pass
| StarcoderdataPython |
3563438 | #!/usr/bin/env python3
from sys import path
path.append('../')
from sherline_lathe.lathe_parting import lathe_parting
import unittest
class test_lathe_parting(unittest.TestCase):
def test_set_surface_speed(self):
pass
| StarcoderdataPython |
4821327 | import pandas as pd
t = 600
df = pd.read_csv('player_time.csv')
df['team_1_gold'] = (df.gold_t_0 + df.gold_t_1 + df.gold_t_2 +
df.gold_t_3 + df.gold_t_4)
df['team_2_gold'] = (df.gold_t_128 + df.gold_t_129 + df.gold_t_130 +
df.gold_t_131 + df.gold_t_132)
df = df[['match_id',... | StarcoderdataPython |
4940065 | # GUI component to "train" the watchdog
from tkinter import *
import dbclient, sys, gui_common
__all__ = []
if __name__ == '__main__':
Tk().title('搞打卡竞赛,进国家队,拿亚洲金牌!')
asker = gui_common.IPAsker()
asker.mainloop()
if asker.machine_data is None:
sys.exit(0)
trainer = gui_common.T... | StarcoderdataPython |
1944565 | import os, webbrowser, requests, time, sys, sqlite3, random, traceback
import pyinspect as pi
import datetime
import wikipedia
import pywhatkit as kit
import ClointFusion as cf
from pathlib import Path
import subprocess
from PIL import Image
from rich.text import Text
from rich import print
from rich.console import Con... | StarcoderdataPython |
4847465 | <reponame>mitodl/mitxonline
# Generated by Django 3.1.12 on 2021-09-23 14:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("wagtailimages", "0023_add_choose_permissions"),
("cms", "0012_product_description_help_... | StarcoderdataPython |
1684735 | # Create your views here.
from collections import OrderedDict
from copy import deepcopy, copy
from datetime import datetime
from humanize import intcomma
import time
import json
import os
from pathlib import Path
import zipfile
from accounts.forms import LogInForm, SignUpForm
from geodata.geodata import GeoData
from d... | StarcoderdataPython |
3549859 | <gh_stars>0
# Copyright (c) 2019. Partners HealthCare, Harvard Medical School’s
# Department of Biomedical Informatics, <NAME>
#
# Developed by <NAME>, based on contributions by:
# <NAME> and other members of Division of Genetics,
# Brigham and Women's Hospital
#
# Licensed under the Apache License, Version 2.0 (... | StarcoderdataPython |
12840039 | <filename>App/Graphic/app.py
"""
This is the module containing the graphical user interface for
my Newegg tracker application
"""
from tkinter import *
from tkinter import ttk
import webbrowser
from PIL import ImageTk, Image #Tkinter's image management is outdated
root = Tk()
root.config(bg="#2D2D2D")
root.title("N... | StarcoderdataPython |
5172057 | <filename>src/bda/calendar/base/converter.py<gh_stars>1-10
from DateTime import DateTime
from math import floor
import datetime
import pytz
ONEDAYINMILLIS = 86400000.0
def dt2DT(dt):
"""Convert Python's datetime to Zope's DateTime.
Acts timezone-aware.
"""
if isinstance(dt, DateTime):
retur... | StarcoderdataPython |
11214951 | <gh_stars>0
import logging
from flask import jsonify, request
from flask_jwt_extended import create_access_token, jwt_required
from api import db_api
from api.notifier import notifier_blueprint
from api.notifier.models import Contact, User
from api.notifier.login_utils import verify_pass
from api.notifier.telegram_ut... | StarcoderdataPython |
333404 | from torndb import *
from toto.exceptions import *
from toto.session import *
from time import time, mktime
from datetime import datetime
from dbconnection import DBConnection
from uuid import uuid4
import toto.secret as secret
import base64
import uuid
import hmac
import hashlib
import random
import string
class MySQ... | StarcoderdataPython |
1909007 | import random
from random import randrange
import json
class Player:
def __init__(self, name, race, stamina, deffence, atack):
self.nameOfPlayer = name
self.raceOfPlayer = race
self.staminaOfPlayer = stamina
self.deffenceOfPlayer = deffence
self.atackOfPlayer = atack
... | StarcoderdataPython |
1728739 | <filename>src/gui/components/table/table.py<gh_stars>0
"""
This is the table that is used in the main part table
"""
from tkinter import Entry, Frame
class Table(Frame):
"""
Main table structure for the parts information section
Methods:
+ add_entry = add an entry with no label
+... | StarcoderdataPython |
6622807 | '''
A module for hash unordered elements
'''
from typing import Union
from collections import OrderedDict
import hashlib
import json
import warnings
class UnorderedSha256:
'''
Using SHA256 on unordered elements
'''
def __init__(self):
self.result = [0] * 32
def update_data(self, data: Union[bytes, bytearra... | StarcoderdataPython |
3365681 | <reponame>fanglab/6mASCOPE<filename>SLpackage/private/pacbio/pythonpkgs/pysiv2/lib/python2.7/site-packages/pysiv2/custom/test_ccs.py
"""
Test output of Circular Consensus Sequence (CCS) pipelines.
"""
# XXX currently the pipeline output is defined as the pbreports report, which
# has the various statistics pre-calcul... | StarcoderdataPython |
24261 | <reponame>megansimwei/pydex
from matplotlib import pyplot as plt
import numpy as np
class TrellisPlotter:
def __init__(self):
self.cmap = None
self.colorbar_label_rotation = None
self.colobar_tick_fontsize = None
self.grouped_fun = None
self.fun = None
self.data = N... | StarcoderdataPython |
3582548 | #
# Copyright (c) 2016-2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# noinspection PyUnresolvedReferences
from ceph_manager.i18n import _
from ceph_manager.i18n import _LW
# noinspection PyUnresolvedReferences
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
class Ce... | StarcoderdataPython |
12839428 | <gh_stars>1-10
from __future__ import absolute_import
from django.utils.translation import ugettext_lazy as _
from permissions.models import PermissionNamespace, Permission
namespace = PermissionNamespace('scheduler', _(u'Scheduler'))
PERMISSION_VIEW_JOB_LIST = Permission.objects.register(namespace, 'jobs_list', _(u... | StarcoderdataPython |
9691128 | <filename>Query_two.py
"""
SELECT ID FROM EMPLOYEE e1
WHERE e1.department = 'department35' and
not exists (SELECT * FROM EMPLOYEE e2 WHERE e2.Department = e1.Department
and e2.salary>e1.salary and
exists (SELECT * from COURSE c Where c.EmpID=e2.ID));
"""
import time
import query_outp... | StarcoderdataPython |
5101424 | <reponame>dangell7/xrpl-py
"""High-level methods to obtain information about accounts."""
import asyncio
from typing import Dict, Union
from xrpl.asyncio.account import main
from xrpl.clients.sync_client import SyncClient
from xrpl.models.response import Response
def does_account_exist(address: str, client: SyncCli... | StarcoderdataPython |
8137123 | import flask
blueprint = flask.Blueprint('auth', __name__, template_folder='templates')
import ruddock.modules.auth.routes
| StarcoderdataPython |
87989 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
class ActivationEvent(object):
def __init__(self, request, user):
self.request = request
self.user = user
class LoginEvent(object):
def __init__(self, request, user):
self.request = request
self.user = user
cla... | StarcoderdataPython |
9674297 | <gh_stars>0
import gkeepapi
import re
import schoolopy
import time
import yaml
def main():
"""
Bring Schoology posts into Google Keep as notes.
Returns:
Number of posts newly converted.
"""
# Retrieve credentials
with open('config.yaml', 'r') as file:
config = yaml.load(file, ... | StarcoderdataPython |
6596700 | # -*- coding: utf-8 -*-
import random
from tkinter import *
#variables and Dictionary
#These are total events that could occur if/else can also be used but they are pain to implement
schema={
"rock":{"rock":1,"paper":0,"scissors":2},
"paper":{"rock":2,"paper":1,"scissors":0},
"scissors":{"ro... | StarcoderdataPython |
9677127 | """
Merge compatible PUDL datapackages and load the result into an SQLite DB.
This script merges a set of compatible PUDL datapackages into a single
tabular datapackage, and then loads that package into the PUDL SQLite DB
The input datapackages must all have been produced in the same ETL run, and
share the same ``dat... | StarcoderdataPython |
3464417 | <reponame>Crystal-girl/Algorithm-interview-lecture-40
"""
leetcode 98
Valid Binary Search Tree
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
solution 1
T: O(N)
S: O(N)
"""
def isValidBST(self, root: 'TreeNode') -> bool:
self.prev = None... | StarcoderdataPython |
3316650 | #
# Copyright (C) 2015 <NAME>
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
import argparse
from builtins import range
from rdkit.Chem.Scaffolds... | StarcoderdataPython |
8187920 | <reponame>jtilly/git_root<filename>git_root/__init__.py<gh_stars>10-100
from .git_root import *
| StarcoderdataPython |
1670208 | from .environment import ForagingEnv
| StarcoderdataPython |
6614213 | <reponame>gstavosanchez/tytus
class DB():
def __init__(self):
self.dicDB = {}
self.dicTB = {}
#---------------------FUNCIONES BASES DE DATOS----------------------#
# CREAR BASE DE DATOS
def createDatabase(self, database):
if self.identify(database):
ready = False
... | StarcoderdataPython |
6445573 | <filename>findsame/calc.py<gh_stars>1-10
import os
import hashlib
import functools
import itertools
from collections import defaultdict
##from multiprocessing import Pool # same as ProcessPoolExecutor
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from findsame import common as co
from findsame... | StarcoderdataPython |
6440958 | import warnings
from typing import Iterable, Optional, Union, Tuple, List
ArraysetsRef = Union['ArraysetDataReader', Iterable['ArraysetDataReader']]
class GroupedAsets(object):
"""Groups hangar arraysets and validate suitability for usage in dataloaders.
It can choose a subset of samples in the hangar arra... | StarcoderdataPython |
5129272 | import unittest
import numpy as np
import openmdao.api as om
import numpy.testing as npt
import wisdem.commonse.environment as env
from wisdem.commonse import gravity as g
from openmdao.utils.assert_utils import assert_check_partials
npts = 100
myones = np.ones((npts,))
class TestPowerWind(unittest.TestCase):
d... | StarcoderdataPython |
4964578 | #!/usr/bin/env python3
"""
Script to collect system-level resource info indluding CPU, memory, disk and netwwork.
"""
import psutil
import subprocess
import os
import sys
import time
import signal
import threading
from desc.sysmon import __version__
def none():
"""Function that always returns none."""
return... | StarcoderdataPython |
4882459 | <gh_stars>0
from neurons_and_synapses import *
import copy
def generate_memory_synapses(G,idx_start=0,name=''):
synapses_list = []
neurons_idx = {'input': 0, 'first': 1, 'last': 2, 'acc': 3, 'acc2': 4, 'ready': 5, 'recall': 6, 'output': 7}
for _key in neurons_idx:
neurons_idx[_key] +=idx_start
... | StarcoderdataPython |
142961 | <gh_stars>0
num = 10
num1 = 10
num2 = 20
num3 = 30
| StarcoderdataPython |
6660656 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-02 14:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import softhub.models.Executable
class Migration(migrations.Migration):
dependencies = [
('softhub', '0004_version'),... | StarcoderdataPython |
1916680 | <reponame>danixeee/textx-gen-syntaxhighlighting
from os.path import dirname, join
from textx import metamodel_from_file
mm_path = dirname(__file__)
def _get_metamodel(file_name):
return metamodel_from_file(join(mm_path, file_name))
coloring_mm = _get_metamodel("coloring.tx")
| StarcoderdataPython |
1896684 | #<NAME> 01/04/18
#Exercise 6
#function to output the factorial of a positive integer
# define function
def myfactorial (x):
ans = 1
#loop, start with number 1 and add one to end variable
for i in range(1, x+1):
#calculate factorial
ans = ans * i
return ans
#test factorial
print("t... | StarcoderdataPython |
4813488 | from FreeTAKServer.model.FTSModel.fts_protocol_object import FTSProtocolObject
#######################################################
#
# Mission.py
# Python implementation of the Class Mission
# Generated by Enterprise Architect
# Created on(FTSProtocolObject): 11-Feb-2020 11(FTSProtocolObject):08(FTSProtocolOb... | StarcoderdataPython |
6428202 | <reponame>paulhuggett/pstore2<filename>system_tests/broker/broker_kill.py
#!/usr/bin/env python
# ===- system_tests/broker/broker_kill.py ---------------------------------===//
# * _ _ _ _ _ _ *
# * | |__ _ __ ___ | | _____ _ __ | | _(_) | | *
# * | '_ \| '__/ _ \| |/ / _ \ '__| | |/ ... | StarcoderdataPython |
4973566 | <reponame>daichi-yoshikawa/dnnet
# Authors: <NAME> <<EMAIL>>
# License: BSD 3 clause
import dnnet.utils.numcupy as ncp
from dnnet.ext_mathlibs import cp, np
from dnnet.exception import DNNetRuntimeError
from dnnet.layers.layer import Layer
from dnnet.training.weight_initialization import DefaultInitialization
from dnn... | StarcoderdataPython |
1851671 | <filename>src/spaceone/repository/error/repository.py<gh_stars>1-10
from spaceone.core.error import *
class ERROR_NO_REPOSITORY(ERROR_BASE):
_message = 'Repository does not exists.'
class ERROR_REPOSITORY_BACKEND(ERROR_BASE):
_status_code = 'INTERNAL'
_message = 'Repository backend has problem. ({host})... | StarcoderdataPython |
5070208 | <reponame>ibrahim-elshar/Never-Ending-Learning-Imitation-Based-Methods
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
NUM_POINTS = 300.0
def plot(prefix, rewards):
x_gap = len(rewards) / NUM_POINTS
x_vals = np.arange(0, len(rewards), x_gap).astype(int)
rewards =... | StarcoderdataPython |
8181835 | <reponame>brianWeng0223/toad
import pytest
import numpy as np
import pandas as pd
from .metrics import KS, KS_bucket, F1, PSI, AUC, matrix
np.random.seed(1)
feature = np.random.rand(500)
target = np.random.randint(2, size = 500)
base_feature = np.random.rand(500)
test_df = pd.DataFrame({
'A': np.random.rand(500... | StarcoderdataPython |
9753559 | <filename>environment/NFG/twoplayer_twoaction.py
'''
Created on 07/11/2014
@author: <NAME> <<EMAIL>>
'''
from environment import Environment, ENV_SINGLE_STATE
class TwoPlayerTwoAction(Environment):
def __init__(self, game_string):
super(TwoPlayerTwoAction, self).__init__()
s... | StarcoderdataPython |
9656399 | <gh_stars>1-10
import unittest
from unittest.mock import MagicMock
from equipment.framework.Queue.AbstractQueue import AbstractQueue
from equipment.framework.Queue.RedisQueue import RedisQueue
from equipment.framework.tests.TestCase import TestCase
class RedisQueueTest(TestCase):
def setUp(self):
super().... | StarcoderdataPython |
9626261 | <reponame>domfp13/Snowflake-backup
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by <NAME>
import pandas as pd
from pandas import DataFrame
import os, contextlib, json
from pathlib import Path
@contextlib.contextmanager
def this_directory(path:str):
"""Change working directroy to the path(within the src... | StarcoderdataPython |
9665369 | import argparse
import os
import pdb
import numpy as np
import subprocess
import ffmpeg
import time
def main(video_dir):
print('MAIN')
t1 = time.time()
videos = os.listdir(video_dir)
videos = [v for v in videos if v.endswith('.mp4')]
for videoname in videos:
video_file = os.path.join(video... | StarcoderdataPython |
9652324 | # -*- coding: utf-8 -*-
import pytest
from aiohttp.web import Application
from mtpylon.aiohandlers.schema import schema_view_factory
from tests.simpleschema import schema
from tests.test_serializers import json_schema
@pytest.fixture
def cli(loop, aiohttp_client):
schema_view = schema_view_factory(schema)
... | StarcoderdataPython |
62671 | <reponame>glimpens/EnergyScope
# -*- coding: utf-8 -*-
"""
This script modifies the input data and runs the EnergyScope model.
@author: <NAME>, <NAME>, <NAME>, <NAME>
"""
import yaml
import os
import pandas as pd
import energyscope as es
from print_run_files import print_master_run_file, print_main_run_file
from sy... | StarcoderdataPython |
4987549 | <reponame>pgDora56/Mocho<filename>tamagame.py
# coding=utf-8
import discord
import json
import pickle
import time
with open("config.json", "r") as f:
conf = json.load(f)
tg_zatsu_id = conf["tamagame"]
class TamaGame:
def __init__(self, client):
self.zatsudan = client.get_channel(tg_zatsu... | StarcoderdataPython |
3517257 | <reponame>toptal/license-cop
import pytest
from textwrap import dedent
from test import *
from app.dependency import *
from app.github.repository import *
from app.platforms.python.repository_matcher import *
@pytest.fixture
def nodejs_repository():
return GithubRepository.from_url(
'https://github.com/b... | StarcoderdataPython |
1740859 | <filename>public/shader/220210_2142.py<gh_stars>0
#define BPM 90.0
const float PI = acos(-1.0);
const float TAU = PI * 2.0;
/* sound common */
float timeToBeat(float t) {return t / 60.0 * BPM;}
float beatToTime(float b) {return b / BPM * 60.0;}
float sine(float phase) {
return sin(TAU * phase);
}
float pitch(fl... | StarcoderdataPython |
11365048 | import sys
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, WeightedRandomSampler
sys.path.append('../')
from config.cfg import cfg
from data.datasets import RafFaceDataset, UTKFaceDataset, RafPartDataset, FER2013Dataset
def load_data(dataset_name):
"""
load dataset
:... | StarcoderdataPython |
3367728 | """
A dictionary to control logging via logging.config.dictConfig
"""
loggingDict = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(levelname)s\t%(process)d '
'[%(asctime)s]:\t%(message)s',
'datefmt': '%m/%d/... | StarcoderdataPython |
8102008 | <reponame>bjlittle/ugrid-checks<filename>lib/ugrid_checks/tests/__init__.py
"""
Unittests for the ugrid_checks package.
TODO: definitely a good idea to convert all this to PyTest.
"""
import copy
from pathlib import Path
from subprocess import check_call
from typing import Text, Union
from pytest import fixture
from... | StarcoderdataPython |
1924839 | import unittest
from selenium import webdriver
import page
import secrets
class ShoppingListTest(unittest.TestCase):
# set up will run before each test
def setUp(self):
# initialize driver with path to chrome driver in my personal environment
self.driver = webdriver.Chrome("/Users/cody/dev/pra... | StarcoderdataPython |
8006555 | from typing import List
from ..db import get_session
from ..db_models import Chase
from ..error import BabylonServerError
from ..api_models.all_activity import AllActivity
from ..api_models.chase_activity import ChaseActivity
def fetch_all_by_type(activity_type: str) -> dict:
"""
Fetch all activity for a giv... | StarcoderdataPython |
5199762 | import pyaudio
import zlib
import io
import audioop
import time
import asyncio
import socket
from config.config import Audio
from config.config import Server
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def callback(input_data, frame_count, time_info, status):
message = audioop.lin2adpcm(input_data, 2... | StarcoderdataPython |
11277769 | ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
from importkit.yaml import validator
from importkit.yaml.validator.tests.base import SchemaTest, raises, result
class TestPerson(SchemaTest):
def setUp(self):
super().setUp()
self.schema = self.get_s... | StarcoderdataPython |
270696 | <reponame>byteskeptical/salt<gh_stars>1-10
# -*- coding: utf-8 -*-
'''
Managing implicit state and baselines using snapshots
=====================================================
.. versionadded:: 2016.11.0
Salt can manage state against explicitly defined state, for example
if your minion state is defined by:
.. cod... | StarcoderdataPython |
8170721 | <filename>funcx_sdk/funcx/sdk/client.py
import json
import os
import logging
from inspect import getsource
from globus_sdk import AuthClient
from fair_research_login import NativeClient, JSONTokenStorage
from funcx.sdk.search import SearchHelper, FunctionSearchResults
from funcx.serialize import FuncXSerializer
# f... | StarcoderdataPython |
9744449 | <reponame>chopinx/file_manager<filename>file_manager/utils.py<gh_stars>0
import datetime
import hashlib
import os
import time
def str_md5sum(my_str, cache_map):
if cache_map.get(my_str, None) is not None:
return cache_map.get(my_str, None)
if not isinstance(my_str, str):
raise TypeError
m ... | StarcoderdataPython |
9728941 | from collections import OrderedDict
from urllib.parse import urlencode
def order_list_api(request, data, page, max_per_page, total):
""" 顺序展示返回结果, 像Django DRF一样的返回。
:param request:
:param data:
:param page:
:param max_per_page:
:param total:
:return:
"""
url_urlencode ... | StarcoderdataPython |
3232193 | # ActivitySim
# See full license in LICENSE.txt.
import os.path
import logging
import pytest
import pandas as pd
from .. import tracing
from .. import inject
def close_handlers():
loggers = logging.Logger.manager.loggerDict
for name in loggers:
logger = logging.getLogger(name)
logger.handle... | StarcoderdataPython |
6425037 | <filename>townsquare/testing/__init__.py
"""
The testing package provides test boilerplate to avoid
writing the same code in tests. Use it extensively.
"""
from flask_testing import TestCase
from townsquare import TownSquare
from townsquare.db import db
from townsquare.db.data import bootstrap
class TownSquareTestCa... | StarcoderdataPython |
6421007 | import pytest
from share.harvest.base import FetchResult
from share.models import SourceConfig, RawDatum
xml = """
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<APPLICATION_ID>6828756</APPLICATION_ID>
<ACTIVITY>N01</ACTIVITY>
<ADMINISTERING_IC>AG</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE... | StarcoderdataPython |
3219880 | <reponame>pawan7587/Snake_game<gh_stars>0
"""
This module contains a basic wrapper for a window class.
"""
import pygame
class Window:
"""
The Window class is a wrapper around a pygame window.
It provides very basic rendering functionallity.
Attributes:
-----------------
ba... | StarcoderdataPython |
4990296 | <filename>cnapy/gui_elements/phase_plane_dialog.py
"""The phase plane plot dialog"""
import matplotlib.pyplot as plt
from qtpy.QtCore import Qt, Signal
from qtpy.QtWidgets import (QCompleter, QDialog, QHBoxLayout, QLabel,
QLineEdit, QPushButton, QVBoxLayout)
import numpy
class CompleterLi... | StarcoderdataPython |
9613815 | <reponame>mvgiacomello/leetcode-solutions
import unittest
from longest_substring_wo_repeat_chars import solution
class TestSolution(unittest.TestCase):
def test_repeat_char_detection(self):
self.assertTrue(solution.repeat_chars('aa'))
self.assertTrue(solution.repeat_chars('aA'))
self.asser... | StarcoderdataPython |
4951108 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import time,sys
from pymongo import MongoClient
from bson.objectid import ObjectId
db = MongoClient('10.168.11.151')['fair_db']
db.authenticate('ipcam','zjjL_3026')
ISOTIMEFORMAT=['%Y-%m-%d %X', '%Y-%m-%d', '%Y%m%d%H%M']
def time_str(t=None, format=0):
return time.... | StarcoderdataPython |
21787 | import os
import pytest
import numpy as np
from laserembeddings import Laser
SIMILARITY_TEST = os.getenv('SIMILARITY_TEST')
def test_laser():
with open(Laser.DEFAULT_ENCODER_FILE, 'rb') as f_encoder:
laser = Laser(
Laser.DEFAULT_BPE_CODES_FILE,
None,
f_encoder,
... | StarcoderdataPython |
5145172 | <filename>riberry/app/context/__init__.py
from contextlib import contextmanager
import riberry
from .artifact import Artifact
from .current import ContextCurrent
from .event_registry import EventRegistry, EventRegistryHelper
from .external_task import ExternalTask
from .flow import Flow
from .input_mapping import Inpu... | StarcoderdataPython |
8110912 | # coding: utf-8
from __future__ import print_function
import sys
import pytest
import xmldiff.main
from lxml import etree
from lxml.builder import E
from benker.builders.formex import FormexBuilder
from benker.cell import Cell
from benker.table import Table
TBL = E.TBL
ROW = E.ROW
P = E.P
@pytest.mark.parametrize... | StarcoderdataPython |
8102907 | <reponame>jqueguiner/ai-api-template<gh_stars>1-10
import os
import requests
import random
import _thread as thread
from uuid import uuid4
import numpy as np
import skimage
from skimage.filters import gaussian
import zipfile
from PIL import Image
import matplotlib.image as mpimg
import cv2
def blur(image, x0, x1, y0... | StarcoderdataPython |
4902734 | # -*- 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 obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | StarcoderdataPython |
83451 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 27 13:49:16 2021
@author: luis
"""
# Plantilla de pre-procesado #
# Cómo importar las librerías
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importar el dataset a Spyder
dataset = pd.read_csv('Data.csv') # Definir la ubicación del archivo
# ... | StarcoderdataPython |
4871428 | from rest_framework import routers
from invoices.api.viewsets import InvoiceViewSet
from menus.api.viewsets import MenuViewSet
from order_items.api.viewsets import OrderItemViewSet
from orders.api.viewsets import OrderViewSet
app_name = 'api'
router = routers.DefaultRouter()
router.register(r'orders', OrderViewSet, b... | StarcoderdataPython |
8007823 | import re
from rest_framework import filters
class TypedCourseSearchBackend(filters.SearchFilter):
code_re = re.compile(r"^([A-Za-z]{1,4})?[ |-]?(\d{1,5})?$")
def infer_search_type(self, query):
if self.code_re.match(query):
return "course"
else:
return "keyword"
... | StarcoderdataPython |
280985 | # Entry point
import pyfiglet
from app.configs.local import projectName
print(pyfiglet.figlet_format(projectName, font = "slant"))
import core.packages.router.route_manager as route_manager
route_manager.RouteManger()
| StarcoderdataPython |
9756284 | # Ex1 : Write a function named total that takes a list of integers as input,
# and returns the total value of all those integers added together.
def total(lst) :
sum = 0
for num in lst :
sum += num
return sum
# Ex2 : Write a function called count that takes a list of numbers as input
# ... | StarcoderdataPython |
8077335 | <gh_stars>0
# -*- coding:utf-8 -*-
# @Time : 2019/6/22 7:55 PM
# @Author : __wutonghe__
from test_plus.test import TestCase
from django.test import RequestFactory
from segmentfault.apps.circle.views import *
class BaseUser(TestCase):
def setUp(self):
self.user = self.make_user()
self.factory = ... | StarcoderdataPython |
133798 | <reponame>bearsh/raccoon
from collections import OrderedDict
from copy import deepcopy
import pytest
import raccoon as rc
from raccoon.utils import assert_series_equal
def test_names():
srs = rc.Series([1, 2])
assert srs.index_name == 'index'
assert srs.data_name == 'value'
srs.index_name = 'new_in... | StarcoderdataPython |
1788693 | import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
from transformers import BertModel
from config import Baseline_LSTMConfig
from config import Baseline_BertConfig
from config import Baseline_CNNConfig
from tools import load_bert_vocab_embedding_vec
class Baseline_Model_B... | StarcoderdataPython |
166977 | # Benchmark the counting of alanine residues in a PDB file
import time
import MDAnalysis as mda
pdb_filepath = "pdbs/1AKE.pdb"
u = mda.Universe(pdb_filepath)
def count():
return (u.residues.resnames == "ALA").sum()
start = time.time()
count()
elapsed = time.time() - start
print elapsed
| StarcoderdataPython |
11372743 | # Copyright (c) 2020 AllSeeingEyeTolledEweSew
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERC... | StarcoderdataPython |
347572 | <reponame>nielshojen/macnamer<filename>macnamer/urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^macnamer/', include('macnamer.foo.urls')),
... | StarcoderdataPython |
5166595 | class Error(Exception):
"""Base class for exceptions in this module."""
pass
class DuplicateXMLDocumentError(Exception):
def __init__(self, *args):
message = "Error %s: \nIndicates: %s\nIn Location: %s" % (args[0], args[1], args[2])
print(message)
self.message = message
class Undef... | StarcoderdataPython |
1890806 | <gh_stars>10-100
# ---
# jupyter:
# anaconda-cloud: {}
# jupytext:
# cell_metadata_filter: -all
# formats: ipynb,py:percent
# notebook_metadata_filter: all
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.6.0
# ker... | StarcoderdataPython |
11276289 | <filename>deep_filters/core/util.py<gh_stars>10-100
import logging
import os
import random
import shelve
import time
from logging.config import fileConfig
import numpy as np
from PIL import Image
from tqdm import *
from deep_filters.core.images import load_array_image, process_image
from deep_filters.core.keras_callb... | StarcoderdataPython |
9798744 | from .bases import ButtonConfig
from .buttons import ActionButton, DropDownButton, HyperlinkButton, WidgetButton
from .enums import ButtonLevel, ButtonType, HyperlinkTarget
| StarcoderdataPython |
1616687 | from ccdc import cassandra
from ccdc import pyccd
from pyspark import sql
def test_options():
opts = cassandra.options("foo")
assert set(opts.keys()) == {'table',
'keyspace',
'spark.cassandra.auth.password',
'spar... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.