id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3411259 | <gh_stars>0
import logging
import json
import os
import shutil
import threading
import traceback
from typing import Iterable
from xmlrpc.client import ServerProxy
import numpy as np
from skimage.external.tifffile import imread
from skimage.transform import AffineTransform
import matplotlib.pyplot as plt
import matplo... | StarcoderdataPython |
89432 | # -*- coding: UTF-8 -*-
import arcpy
import re
import os
import codecs
#ツール定義
class FeatureToWKTCSV(object):
def __init__(self):
self.label = _("Feature To UTF-8 WKT CSV")
self.description = _("Creates a UTF-8 WKT CSV from specified features.")
self.category = _("DataManagement")
self.canRunInBac... | StarcoderdataPython |
245042 | <filename>tsp.py
# -*- encoding: utf-8 -*-
"""
Traveling Salesman Problem related utilities.
"""
import re
from random import randint
from math import pi as M_PI
from math import cos, acos
from misc import array_double, array_bool
def geo_distance(x1, y1, x2, y2):
"""
Compute geometric distance between two... | StarcoderdataPython |
4969967 | #!/usr/bin/env python3
import initIOCs
#-------------------------------------------------
#---------------- MAIN GUI CLASSES ---------------
#-------------------------------------------------
# Include guard in case user doesn't have tkinter installed but still wants to use the CLI version
WITH_GUI=True
try:
fr... | StarcoderdataPython |
11260663 | <reponame>vinjn/net-doctor<gh_stars>0
# $Id: dns.py 27 2006-11-21 01:22:52Z dahelder $
# -*- coding: utf-8 -*-
"""Domain Name System."""
from __future__ import print_function
from __future__ import absolute_import
import struct
import codecs
from . import dpkt
from .compat import compat_ord
DNS_Q = 0
DNS_R = 1
# Op... | StarcoderdataPython |
6616156 | <reponame>MrKosif/Neural-Networks-From-Scratch
import numpy as np
from nnfs import spiral_data
input = [[1, -2, 3],
[-3, 6 ,-8]]
class Layer_Dense:
def __init__(self, no_of_inputs, no_of_neurons):
self.weight = 0.10*np.random.randn(no_of_inputs, no_of_neurons)
self.bias = np.zero... | StarcoderdataPython |
4863966 | <reponame>LucasRR94/RPG_Pirates_and_Fishers
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#---------------------------------------------------------------------------
from Item import Item
from Weapon import Weapon
import random
import string
def testAssignname_Weapon(weapon,name,numberofsum,num):
if(len(name)<=32 and... | StarcoderdataPython |
1619212 | <reponame>extra2000/nginx-podman
# This file is generated from semantic-release bot
version = '3.0.0'
| StarcoderdataPython |
3219408 | import requests
def create_header(access_token):
'''
Prepare headers to attach to request.
'''
headers = {
'Authorization': f'Bearer {access_token}'
}
return headers
def call_api(access_token, data_dictionary, method, endpoint, path, mapped_fields, id):
# assemble the url without the ... | StarcoderdataPython |
255028 | import pyautogui
import win32api, win32con
from time import sleep
import os
def clear_term():
"""
Clears the terminal.
"""
os.system('cls' if os.name =='nt' else 'clear')
def get_next_click_pos():
"""
Gets the x, y coordinates of the next left-click.
Returns:
(int, int) - the x and y... | StarcoderdataPython |
1791886 | import unittest
from passlocker import passlocker
import Pyperclip
class Testpasslockers(unittest.TestCase):
def setup(self):
"""
setup before running test
"""
self.new_passlocker = ("millywayne", "<PASSWORD>" "github" "<EMAIL>")
def test_init(self):
"""
clear list
... | StarcoderdataPython |
6500369 | <reponame>a6350202/harvester<gh_stars>0
import os
import errno
import datetime
import tempfile
import threading
import random
from concurrent.futures import ThreadPoolExecutor
import re
from math import sqrt, log1p
from pandaharvester.harvesterconfig import harvester_config
from pandaharvester.harvestercore.queue_con... | StarcoderdataPython |
6637560 | """Ndnt related classes."""
from pathlib import Path
import sys
from ndnt.arguments import Arguments
from ndnt.extension import Extension
from ndnt.paths import ExcludeGitignoredPaths, ExtensionPaths, FilesPaths
from ndnt.summary import DirectorySummary, FileSummary
class Ndnts:
"""Main class of this tool."""
... | StarcoderdataPython |
60160 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from functools import partial
import torch
from torch import nn
from timm.models.layers import DropPath
from einops.layers.torch import Reduce
from .layers import DWConv, SPATIAL_FUNC, ChannelMLP, STEM_LAYER
from .misc import reshape2n... | StarcoderdataPython |
89833 | <gh_stars>100-1000
"""
Testing for TG2 Configuration
"""
from nose import SkipTest
from nose.tools import eq_, raises
import sys, os
from datetime import datetime
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine import Engine
from ming import Session
from ming.orm... | StarcoderdataPython |
273423 | # -*- coding: utf-8 -*-
#twFuncs.py
from twitter import Twitter, OAuth
import yweather
import requests
from operator import itemgetter
import re
from bs4 import BeautifulSoup
if __name__ != "__main__":
from . import config
#--------------------------------------------------------------------------
# twitter Modu... | StarcoderdataPython |
5095203 | <reponame>pskrunner14/info-retrieval
import math
class BooleanModel():
@staticmethod
def and_operation(left_operand, right_operand):
# perform 'merge'
result = [] # results list to be returned
l_index = 0 # current ind... | StarcoderdataPython |
8026020 | import glob
import pickle
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tf_fourier_features.fourier_features_mlp import FourierFeatureMLP
BATCH_SIZE = 8192
IMAGE_SIZE = 800
IMAGE_EMBED = 8
img_filepath_1 = '../data/blue_flower.jpg'
img_filepath_2 = '../data/fur-style.jpg'
img_filepa... | StarcoderdataPython |
86894 | # -*- coding: utf-8 -*-
import datetime
import tempfile
import unittest
from pathlib import Path
import pytest
from _pytest.logging import caplog
from dsg_lib.logging_config import config_log
import logging
def some_func(var1, var2):
"""
some function to test logging
"""
if var1 < 1:
logging.w... | StarcoderdataPython |
1852410 | import logging
from django.core.management.base import BaseCommand
from projects.models import Project
logger = logging.getLogger(__name__)
# Creates indexes by re-saving all projects
class Command(BaseCommand):
help = "Index all projects"
def handle(self, *args, **options):
for project in Project.... | StarcoderdataPython |
3307995 | <reponame>jessejohn01/CSCI446PA2<gh_stars>0
import network_3_0
import argparse
import time
from time import sleep
import hashlib
class Packet:
## the number of bytes used to store packet length
seq_num_S_length = 10
length_S_length = 10
## length of md5 checksum in hex
checksum_length = 32
... | StarcoderdataPython |
5184127 | #!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with this
work for additional information regarding copyright ownership. The ASF
licenses this file to you under the Apache License, Version 2.0 (the
"Licens... | StarcoderdataPython |
5103111 | <reponame>jxgu1016/GCN_PyTorch
import torch
from torch.autograd import gradcheck
from gcn.layers.GConv import GOF_Function
def gradchecking(use_cuda=False):
print('-'*80)
GOF = GOF_Function.apply
device = torch.device("cuda" if use_cuda else "cpu")
weight = torch.randn(8,8,4,3,3).to(device).double().r... | StarcoderdataPython |
12805732 | <filename>Chap8.py
import os
import sys
import tarfile
import time
import pyprind
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import re
from nltk.stem.porter import PorterStemmer
import nltk
from nltk.cor... | StarcoderdataPython |
5153450 | <filename>source/brailleDisplayDrivers/freedomScientific.py
#brailleDisplayDrivers/freedomScientific.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2008-2011 <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
from ctyp... | StarcoderdataPython |
6627252 | # -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='CellCounting',
version='0.1',
author='<NAME>',
author_email='<EMAIL>',
packages=['cell_counting', 'cell_counting.validation'],
install_requires=['numpy', 'scikit-learn', 'scipy', 'keras', 'shapely', 'joblib']
)
| StarcoderdataPython |
9703085 | <reponame>HongminWu/HMM
#!/usr/bin/env python
import os
import pandas as pd
import numpy as np
from sklearn.externals import joblib
from math import (
log,
exp
)
from matplotlib import pyplot as plt
import time
import util
def assess_deri_threshold_and_decide(
threshold_c_value,
mean_of_log_curve,
... | StarcoderdataPython |
3561197 | <filename>investing_algorithm_framework/core/market_services/__init__.py<gh_stars>1-10
from investing_algorithm_framework.core.market_services.ccxt import \
CCXTMarketService
from investing_algorithm_framework.core.market_services.market_service \
import MarketService
__all__ = [
"MarketService",
"CCXT... | StarcoderdataPython |
335435 | # encoding: utf-8
import re
from sqlalchemy.orm import (joinedload, joinedload_all, subqueryload, subqueryload_all)
from sqlalchemy.orm.exc import NoResultFound
import pyramid.httpexceptions as exc
import pokedex.db.tables as t
from .. import db
from . import caching
def ability_list(request):
c = request.tmpl... | StarcoderdataPython |
6572663 | <reponame>kant/ComputerVision<filename>tests/unit/detection/test_detection_bbox.py<gh_stars>0
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import pytest
from utils_cv.detection.bbox import DetectionBbox, AnnotationBbox, _Bbox
@pytest.fixture(scope="session")
def basi... | StarcoderdataPython |
9692862 | # Units : SI Units
import numpy as np
import scipy
from scipy.integrate import quad as integrate
from matplotlib import pyplot as plt
pi = np.pi
mu0 = 4e-7 * pi
def vec(*args):
return np.atleast_2d(args).T
def R(x,y,z):
# Rotation Matrix
np.matrix()
class Pose(object):
def __init__(self):
se... | StarcoderdataPython |
1811886 | <filename>wtdepth_bins_distinland_21Nov19.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 21 09:08:30 2019
@author: kbefus
"""
import sys,os
import numpy as np
import glob
import pandas as pd
import geopandas as gpd
#import dask.array as da
import rasterio
from rasterio import mask
from raste... | StarcoderdataPython |
9613926 | <reponame>iwasakishuto/PyVideoEditor<filename>docs/veditor-utils-video_utils-1.py
from veditor.utils import show_frames, SampleData
fig = show_frames(video=SampleData().VIDEO_PATH, step=300, ncols=2)
fig.show()
| StarcoderdataPython |
82000 | import json
import os
config = {}
default_config = {}
extra_config = {}
def load():
global config
load_default()
composer = get_value('project-dir')+'composer.json'
if not os.path.isfile(composer):
raise SystemExit('You have to define a composer.json in your project.')
data = load_json(... | StarcoderdataPython |
235258 | <gh_stars>0
import os, sys
def main():
if not os.path.exists('examples/thumbs'):
os.makedirs('examples/thumbs')
generate_thumbnails()
else:
print('Thumbnails already exist, skipping generation')
def generate_thumbnails():
print('Generating thumbnails')
if sys.platform == 'lin... | StarcoderdataPython |
4805776 | <gh_stars>0
likes = '0'
loves = '853 Yêu thích'
def reaction_string_to_number(text: str):
multiplier = 1
stringNumber = text.split(' ')[0].replace(',', '').replace('.', '')
hasK = stringNumber.find('K')
if(hasK != -1):
stringNumber = stringNumber.replace('K', '')
multiplier = 1000
... | StarcoderdataPython |
8022397 | from typing import Union
from django.contrib.postgres.fields import ArrayField
from django.db import models
from castledice.common.constants import DeckName
from .decks import CastleDeck, MarketDeck, VillagerDeck
from .exceptions import InvalidDeckTypeError
class GameDeck(models.Model):
game = models.ForeignKe... | StarcoderdataPython |
8189581 | <reponame>HolisticCoders/mop
"""Minimal observer/publisher implementation for all your GUI needs."""
import traceback
from collections import defaultdict
_SIGNALS = defaultdict(list)
def clear_all_signals():
"""Clear all signals.
Calling this function will unsubscribe all functions.
"""
_SIGNALS.cle... | StarcoderdataPython |
107316 | from blog.models import Post,comment
from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from django.views.generic import (TemplateView,
CreateView,ListView,DetailView,UpdateView)
from django.contrib.auth.mixins import LoginRequiredMixin
from blog.forms import PostForm,comme... | StarcoderdataPython |
6442346 | #!/bin/python3
# author: <NAME>
import os
import subprocess
def write_file(f, s, mode='w'):
if f:
os.makedirs(os.path.dirname(f), 0o777, True)
if s is None:
s = ''
with open(f, mode) as fp:
fp.write(s)
def read_file(f, mode='r'):
if not f:
return ''
... | StarcoderdataPython |
3346024 | <filename>src/factories/service_factory.py<gh_stars>0
"""Service factory module"""
import factory
from faker import Faker
from faker.providers import lorem
from src.factories import BaseFactory
from src.models.service import Service
from app import database as db
faker = Faker()
faker.add_provider(lorem)
class Ser... | StarcoderdataPython |
6557115 | from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from apps.account.api.serializers import RegistrationSerializer, UserSerializer
from rest_framework.authtoken.models import Token
'''
def get_random_str... | StarcoderdataPython |
3220484 | <reponame>nogproject/nog
#!/usr/bin/env python3
# Import only packages that are usually available (preferrably only core
# packages), so that the file is self-contained and can, in principle, be used
# to resolve dependencies when dependencies such as nogpy are not yet
# available.
from glob import glob
import json
i... | StarcoderdataPython |
247168 | import random
def Tonelli_Shanks(n, p):
"""
Находит дискретный корень
x^2 = n (mod p)
:param n: prime
:param p: prime
:return: x
"""
from Helper import EulerCriterion, moduloPow
assert(EulerCriterion(n, p))
S = 0 # number of offsets (количество смещений)
m = (p - 1)
whi... | StarcoderdataPython |
4847296 | <reponame>unclechu/py-radio-class
# -*- coding: utf-8 -*-
from setuptools import setup
from test import TestCommand
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programmin... | StarcoderdataPython |
6401816 | <gh_stars>10-100
from machine import Pin, I2C
from oled import Write, GFX, SSD1306_I2C
from oled.fonts import ubuntu_mono_15, ubuntu_mono_20
scl = Pin(15)
sda = Pin(4)
i2c = I2C(scl=scl, sda=sda)
Pin(16, Pin.OUT, value=1)
oled = SSD1306_I2C(128, 64, i2c)
gfx = GFX(128, 64, oled.pixel)
write15 = Write(oled, ubuntu_m... | StarcoderdataPython |
12844198 | """Template filter for rendering Markdown to HTML."""
from django import template
from django.utils.safestring import mark_safe
from django.template.defaultfilters import stringfilter
from markdownx.utils import markdownify
register = template.Library()
@register.filter
@stringfilter
def markdown(raw_markdown):
... | StarcoderdataPython |
54039 | import datetime
from .celery import celery
from backend.news import hot_topics
from backend.cache import sadd
from backend.utils import time_now_formatted
@celery.task(bind=True)
def store_hot_topics(a):
sadd(time_now_formatted('PESTO_SYSTEM_HOT_TOPICS'), hot_topics()) | StarcoderdataPython |
300076 | import chainer
class PreprocessSVHN(chainer.link.Chain):
def __init__(self):
super(PreprocessSVHN, self).__init__()
def augment(self, x):
return x
def __call__(self, x):
x, t, l = x
if isinstance(l, int) or isinstance(l, float):
xp = chainer.cuda.get_array_mod... | StarcoderdataPython |
4840597 | from setuptools import setup, find_namespace_packages
setup(
name="pyskip_blox",
version="0.0.1",
author="<NAME>, <NAME>",
description="A pyskip wrapper library for loading and operating on Minecraft assets",
packages=find_namespace_packages(),
install_requires=["pyskip>=0.0.1", "nbt", "tqdm", ... | StarcoderdataPython |
11348813 | <reponame>ychen820/microblog
# Copyright 2013 Google Inc. All Rights Reserved.
"""A calliope command that calls a help function."""
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import cli
from googlecloudsdk.calliope import exceptions as c_exc
from googlecloudsdk.core import log
from googlecl... | StarcoderdataPython |
1702305 | <reponame>arifulhaqueuc/python-algorithm-excersice
## Print the items form the following list
## if the items ONLY start with "ba"
list_all_1 = [
'bb1'
,'bb2'
,'bb3'
,'ba4'
]
bb_remove = [x for x in list_all_1 if x[:2]=='ba']
for i in ba_remove:
print i
#####################
#####################
list... | StarcoderdataPython |
3529636 | # TODO: add unit tests for utils.py
import numpy as np
import pandas as pd
import pytest
from sfrmaker.utils import (assign_layers, width_from_arbolate_sum,
arbolate_sum, make_config_summary)
def test_assign_layers(shellmound_sfrdata, shellmound_model):
reach_data = shellmound_sfr... | StarcoderdataPython |
8155441 | def test_node_version_set_to_12(host):
assert host.exists("node")
assert host.run("node --version").stdout.startswith('v12')
def test_given_node_packages_are_installed(host):
packages = ['ionic', 'cordova', 'appcenter']
for package in packages:
assert host.exists(package)
| StarcoderdataPython |
12848695 | <reponame>liquidgecka/twitcher<filename>twitcher/inotify.py
#!/usr/bin/python26
"""Watches a list of directories for file updates.
The classes in this module will watch a list of subdirectories for file
updates. A class is passed in at object initialization time and is used to
create objects as new files are discove... | StarcoderdataPython |
5178182 | <filename>hold_grudge/blog/admin.py<gh_stars>1-10
from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from .models import Post, Category, Tag
from .adminforms import PostAdminForm
from hold_grudge.custom_site import custom_site
@admin.register(Category)
class Cat... | StarcoderdataPython |
9777335 | <filename>exercicio_02.py
"""
Faça um programa que leia um número real e o imprima.
"""
num = float(input('Digite um numero real: '))
print(num)
| StarcoderdataPython |
11382327 | from __future__ import division
import dqn
import gym
import numpy as np
import random
# import matplotlib.pyplot as plt
import scipy.misc
import os
from gridworld import gameEnv
env = gameEnv(partial=False, size=5)
print('bal')
testMnih = dqn.QnetworkMnih13()
testMnih.runTraining(env)
| StarcoderdataPython |
6490137 | <filename>torchvex/cam/__init__.py<gh_stars>1-10
from .cam import CAM
from .grad_cam import GradCAM
| StarcoderdataPython |
1673114 | <filename>tests/vcr_support.py
import os
import vcr as vcrpy
test_dir = os.path.dirname(__file__)
test_data_dir = os.path.join(test_dir, "data", "cassettes")
vcr = vcrpy.VCR(
cassette_library_dir=test_data_dir,
record_mode=os.environ.get("VCR_RECORD_MODE", "new_episodes"),
)
| StarcoderdataPython |
6571386 | <reponame>ujjwalsh/cs
#! /usr/bin/env python
from __future__ import print_function
import base64
import hashlib
import hmac
import os
import re
import sys
import time
from datetime import datetime, timedelta
from fnmatch import fnmatch
try:
from configparser import ConfigParser
except ImportError: # python 2
... | StarcoderdataPython |
154488 | #!/usr/bin/env python
"""
This script extracts btsnooz content from bugreports and generates
a valid btsnoop log file which can be viewed using standard tools
like Wireshark.
btsnooz is a custom format designed to be included in bugreports.
It can be described as:
base64 {
file_header
deflate {
repeated {
... | StarcoderdataPython |
382085 | from celery import Celery
from flask import current_app
celery_app = Celery(__name__)
@celery_app.task
def add(x, y):
"""
加法
:param x:
:param y:
:return:
"""
return str(x + y)
@celery_app.task
def flask_app_context():
"""
celery使用Flask上下文
:return:
"""
with current_ap... | StarcoderdataPython |
6439860 | <reponame>dzshn/python-tetris<filename>examples/cli.py
import curses
import time
import tetris
from tetris import MinoType
from tetris import Move
@curses.wrapper
def main(screen: curses.window) -> None:
game_start = time.monotonic()
game = tetris.BaseGame()
moves: dict[int, Move] = {
ord("z"): ... | StarcoderdataPython |
6697557 | from terrascript import Terrascript, provider
from terrascript.vsphere.r import vsphere_virtual_machine
from terrascript.vsphere.d import vsphere_datastore
from terrascript.vsphere.d import vsphere_datacenter
from terrascript.vsphere.d import vsphere_resource_pool
from terrascript.vsphere.d import vsphere_network
from ... | StarcoderdataPython |
143999 | #!/usr/bin/env python
#
# Author: <NAME> (mmckerns @caltech and @uqfoundation)
# Copyright (c) 2008-2016 California Institute of Technology.
# Copyright (c) 2016-2019 The Uncertainty Quantification Foundation.
# License: 3-clause BSD. The full license text is available at:
# - https://github.com/uqfoundation/dill/blo... | StarcoderdataPython |
1834561 | <gh_stars>0
#### Chain CLG Model ####
import numpy as np
import random
##### Lattice Methods #####
#==============================================================================
# create_clg_lattice(n,L)
# Arguments - N is the number of particles
# L is the number of sites
# returns an array with N par... | StarcoderdataPython |
1675330 | <gh_stars>0
# These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = '<EMAIL>'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
| StarcoderdataPython |
8001869 | # -*- coding: utf-8 -*-
import sys, os, platform, subprocess
from .flowpy_switcher.setupfile import setup
def getargs(argv):
tuples = []
def gen(key):
if key.startswith("-"):
key = key[1:]
if key == 'h':
tuples.append((key,'True'))
return gen
def setarg(value):
tuples.append( (key,value) )
... | StarcoderdataPython |
5111756 | <filename>rock/rules/rule_manager.py<gh_stars>1-10
# Copyright 2011 OpenStack Foundation.
# 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://ww... | StarcoderdataPython |
8042976 | # Accessing webcam using mobile device and saving video in hardisk
# importing library
import cv2 as cv
# Mobile camera ip
camera = "http://192.168.43.90:4747/video"
cap = cv.VideoCapture(0) # 0-> Internal webcam, 1-> External webcam
cap.open(camera)
print("Cap is Opened",cap.isOpened())
# For saving the read video
#... | StarcoderdataPython |
3309987 | <filename>SellBuildKRD/account/models.py
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class ContactSend(models.Model):
name_agent = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ContactSend")
theme = models.TextField(max_length=250)
... | StarcoderdataPython |
3317407 | <reponame>emerginganalytics/cyberarena<gh_stars>1-10
"""
Prepares a build spec for an image with an Apache Guacamole server and adds startup scripts to insert the correct
users and connections into the guacamole database. This server becomes the entrypoint for all students in the arena.
"""
import random
import string... | StarcoderdataPython |
3550002 | #!/usr/bin/python
# encoding: utf-8
#主要是对python中的re的相关操作的封装
import re
import nltk
class re_wrapper(object):
def __init__(self):
pass
def re_show(self, regexp, string, left='{', right='}'):
'''
把找到的符合regexp的non-overlapping matches标记出来
如:
nltk.re_show('[a-zA-Z]+','12fFd... | StarcoderdataPython |
5025234 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
from viacep import ViaCEP
class TestCase(unittest.TestCase):
def test_localidade(self):
d = ViaCEP('78048000')
data = d.getDadosCEP()
self.assertEqual(data['localidade'], 'Cuiabá')
def test_logradouro(self):
d = ViaCEP... | StarcoderdataPython |
3261791 | # Generated by Django 2.1.13 on 2019-12-25 04:04
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('nablaforum', '0003_auto_20191025_2140'),
]
operations = [
migrations.AddField(
model_name='thread'... | StarcoderdataPython |
6435635 | import exp
import sys
import pprint
parts = {} # Parts database.
comps = {} # Lists component instances
nets = {} # Netlist with list of connected comps/pins.
infile = sys.argv[1]
def process_comment(rawlines):
pass
def process_parts(s):
current_parts = None
for ln in s:
if not ln[0].isspace(... | StarcoderdataPython |
6434629 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import random
from collections import deque, defaultdict
import typing
from rasa_core.domain import Domain
from typing import List, Text, Dict, Optional
from rasa_core.i... | StarcoderdataPython |
1781696 | <reponame>Arcensoth/pyckaxe
from .loot_table import *
from .loot_table_serializer import *
| StarcoderdataPython |
3324884 | #!/usr/bin/python3
import json
import urllib3
from pathlib import Path
import requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
pools = requests.get('https://raw.githubusercontent.com/xolentum/mining-pools-json/main/'
'xolentum-mining-pools.json').json()['pools']
w... | StarcoderdataPython |
11369152 | <filename>Pyton_curso/A+B.py
n1 = float (input("Digite um numero A "))
n2 = float (input("Digite um numero B "))
print("A+B = {}".format(n1+n2) )
print("A soma entre {}".format(n1), "e {}".format(n2), "e igual a {}".format(n1+n2))
print("A soma entre {} e {} e igual a {}".format(n1, n2, n1+n2)) | StarcoderdataPython |
9665357 | import youtube_dl
import os
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
except PermissionError:
print("Wait for the current playing music to end or use the 'stop' command")
ydl_opts = {
'format': 'bestaudio/best',
#'postprocessors': [{
# ... | StarcoderdataPython |
3550106 | # -*- coding: utf-8 -*-
class DuobeiSDKException(Exception):
pass
class DuobeiSDKInvalidParamException(DuobeiSDKException):
pass
class DuobeiSDKServerException(DuobeiSDKException):
pass
| StarcoderdataPython |
1882942 | <filename>examples/sync_to_async_sleep.py
import asyncio
import random
from greenletio import await_
def main():
for i in range(10):
await_(asyncio.sleep(random.random()))
print(i)
main()
| StarcoderdataPython |
268541 | <filename>util/rotate.py
"""Do the rotation action that some products need."""
import sys
import os
import gzip
BASE = "/mesonet/ldmdata/"
def main(argv):
"""Do SOmething"""
data = sys.stdin.buffer.read()
fnbase = argv[1]
fmt = argv[2]
dirname = "%s/%s" % (BASE, os.path.dirname(fnbase))
if n... | StarcoderdataPython |
11293498 | #coding: utf-8
from caty.testutil import TestCase
from caty.util.cache import *
from functools import partial
class MemoizeTest(TestCase):
def test_memoized(self):
def foo(a, b):
return a() + b()
def _(d):
d['x'] += 1
return d['x']
d1 = {'x': 0}
... | StarcoderdataPython |
11209934 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
3484914 | <gh_stars>0
import requests
import json
import yaml
with open("config.yaml", "r") as ymlfile:
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
#
api_url = f"https://app.harness.io/gateway/api/graphql?accountId={config['harness']['account_id']}"
headers = {"x-api-key": config["harness"]["api_key"], "Content-Type... | StarcoderdataPython |
1817687 | <filename>tvizbase/__init__.py
__all__ = [
"api",
"base58",
"broadcast",
"key",
"operations",
"storage",
"types",
"ws_client",
]
| StarcoderdataPython |
1908579 | # -*- coding: utf-8 -*-
"""
Chromium-based rasterizer module.
Prerequisite:
sudo apt-get install -y chromedriver chromium
"""
from __future__ import absolute_import, unicode_literals
from selenium import webdriver
from PIL import Image
from io import BytesIO
import json
import logging
import math
import os
impo... | StarcoderdataPython |
1976841 | """lg-rez / features / Commandes annexes
Commandes diverses qu'on ne savait pas où ranger
"""
import random
import requests
import datetime
from discord.ext import commands
from akinator.async_aki import Akinator
from lgrez.blocs import tools
from lgrez.bdd import Joueur
class Annexe(commands.Co... | StarcoderdataPython |
1893956 | <gh_stars>0
# -*- coding: utf-8 -*-
import re
from datetime import datetime
from city_scrapers.constants import COMMISSION
from city_scrapers.spider import Spider
class ChiSsa25Spider(Spider):
name = 'chi_ssa_25'
agency_name = 'Chicago Special Service Area #25 Little Village'
timezone = 'America/Chicago'... | StarcoderdataPython |
294167 | from flask import Blueprint, render_template, redirect, url_for, request
from models import Post, Category, Blogroll
from models import cache
from flask.ext.login import current_user, login_required, logout_user
from sqlalchemy import desc
bp = Blueprint('blog', __name__)
# pagination
POSTS_PER_PAGE = 5
@bp.route('... | StarcoderdataPython |
342559 | <gh_stars>0
from django.db import models
from django.contrib.auth.models import User
class SavedCityModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
city = models.TextField()
modified = models.DateTimeField(auto_now=True)
def __str__(self):
return self.city
| StarcoderdataPython |
8181831 | <filename>grr/server/grr_response_server/flow_utils.py
#!/usr/bin/env python
"""Utils for flow related tasks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import logging
import time
from grr_response_server import aff4
from grr_response_server impor... | StarcoderdataPython |
3321791 | <gh_stars>0
# from coding problem
# Trying brute force on a sudoku board will take a really long time: we will need to try every permutation of the numbers 1-9 for all the non-empty squares.
# Let's try using backtracking to solve this problem instead. What we can do is try filling each empty cell one by one, and backt... | StarcoderdataPython |
397373 | '''
Created on 22.01.2014
@author: CaiusC
'''
import re
import csv
import subprocess
import shutil
import os
import sys
class TGF(object):
'''
This class contains every Hardware component and is responsible for creating the XPS project.
'''
def __init__(self, tgf_file, component_path, base_design... | StarcoderdataPython |
12827891 | # encoding=utf-8
__author__ = 'Jonny'
__location__ = '西安'
__date__ = '2018-03-25'
from scrapy import cmdline
cmdline.execute('scrapy crawl douban'.split(''))
| StarcoderdataPython |
185352 | <reponame>eabyshev/appscale<gh_stars>1-10
""" A test script to start Zookeeper. """
import logging
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
import monit_interface
def run():
""" Starts up cassandra. """
logging.warning("Starting Zookeeper.")
monit_interface.s... | StarcoderdataPython |
3276826 | # global
import abc
# local
from ivy_builder.specs.spec import Spec
from ivy_builder.specs.spec import locals_to_kwargs
from ivy_builder.specs.dataset_dirs import DatasetDirs
class DatasetSpec(Spec, abc.ABC):
def __init__(self,
dirs: DatasetDirs,
**kwargs) -> None:
"""
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.