id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3391991 | import matplotlib
matplotlib.use('Agg')
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import random
random.seed(0)
np.random.seed(0)
import os.path as osp
def plot_clusters_vs_lambda(X_org,l,filename,dataset, lmbda, fairness_error):
K = max(l) +1
... | StarcoderdataPython |
1725465 | <reponame>jialululu/2020-CS109B
model = Sequential()
model.add(Embedding(vocabulary_size, embedding_dim, input_length=max_review_length))
model.add(LSTM(100))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
model.fit(X_t... | StarcoderdataPython |
1729913 | <filename>src/timetree/backend/base.py
from abc import ABCMeta
from abc import abstractmethod
from collections import defaultdict
__all__ = ['BaseBackend', 'BaseVersion', 'BaseVnode']
class BaseBackend(metaclass=ABCMeta):
""" Abstract base class for persistence backends
Timetree's general goal is to express... | StarcoderdataPython |
3245412 | <reponame>threefoldtech/jumpscalex_3bot_packages_archived<filename>token/actors/token.py
from Jumpscale import j
import random
class token(j.baseclasses.threebot_actor):
def _init(self, **kwargs):
self.market = self.bcdb.model_get(url="tfgrid.token.market.1")
self.capacity = self.bcdb.model_get(ur... | StarcoderdataPython |
3370067 | import asyncio
import json
import logging
import os
import ssl
import sys
import threading
import dotenv
import nest_asyncio
from IPython.core.magic import Magics, cell_magic, line_magic, magics_class
# For changing input cell syntax highlighting logic for the entire session
# http://stackoverflow.com/questions/287036... | StarcoderdataPython |
4842810 | <filename>slackbot.py
#! /usr/bin/env python2.7
import requests
class Slackbot(object):
def __init__(self, slack_name, token):
self.slack_name = slack_name
self.token = token
assert self.token, "Token should not be blank"
self.url = self.sb_url()
def sb_url(self):
ur... | StarcoderdataPython |
1714295 | # Copyright (c) 2020 Leiden University Medical Center
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, me... | StarcoderdataPython |
1746820 | <gh_stars>1-10
import sys
from .node import Node
from .Fila import Queue
class RB_Tree:
def __init__(self):
self.TNULL = Node(0)
self.TNULL.color = 0
self.TNULL.left = None
self.TNULL.right = None
self.root = self.TNULL
def insert(self, key):
node = Node(key)... | StarcoderdataPython |
1652041 | # For equations like [ x**2 + 2*x + 1 = 0 ] we use the Quadratic Formula
# Such equations are know as quadratic equations
# Generally expressed as a*(x**2) + b*x + c = 0
# A quadratic equation has two roots, generally expressed as
# x is the unknown, a b and c are constants with "a" not equal to 0
# a*(x**2) + (b*x) + ... | StarcoderdataPython |
4800706 | '''
Convert data from glass.data.txt into python-sensible data
Due to the small dataset of about 200 data, train data will contain about 190 samples
and test data contain about 10 samples
'''
glass_features = 9
def getGlassData():
f = open('data/glass/glass.data.txt', 'r')
x = f.read().splitlines()
trainX = []
tra... | StarcoderdataPython |
3272583 | <reponame>ivaninkv/python_basics
from queue import Queue
def is_relation(clss, parent, child):
parents = clss.get(child)
if parent in clss and child in clss:
if (parents is not None and parent in parents) or (parent == child):
return True
elif parents is not None:
for e... | StarcoderdataPython |
1619663 | <gh_stars>1-10
import logging
from datetime import datetime
from datetime import timezone
from aiogram.types import Chat as TelegramChat
from dasbot.models.chat import Chat, ChatSchema
log = logging.getLogger(__name__)
class ChatsRepo(object):
def __init__(self, chats_col, scores_col):
self._chats = c... | StarcoderdataPython |
3276362 | <filename>src/tests/test_api.py
"""
Author: <NAME>
Date: October, 2021
This script holds the test functions for api module
"""
import pytest
from http import HTTPStatus
from fastapi.testclient import TestClient
from app.api import app
client = TestClient(app)
def test_greetings():
"""
Test... | StarcoderdataPython |
3392191 | <reponame>askap-vast/vast-tools
#!/usr/bin/env python
"""
A script find sources in the VAST Pilot Survey.
Includes options to provide light curves, cutouts and overlay files for
viewers such as kvis and DS9.
Example:
```terminal
find_sources "16:16:00.22 +22:16:04.83" --create-png --imsize 5.0 \
--png-zscale-... | StarcoderdataPython |
55495 | from QUANTAXIS.QAUtil import QA_util_log_info,QA_util_sql_mongo_setting
from QUANTAXIS.QASU.user import QA_user_sign_in,QA_user_sign_up
class QA_Setting():
QA_util_sql_mongo_ip='127.0.0.1'
QA_util_sql_mongo_port='27017'
client=QA_util_sql_mongo_setting(QA_util_sql_mongo_ip,QA_util_sql_mongo_port)
... | StarcoderdataPython |
3374209 | <gh_stars>0
#! /usr/bin/python
from lxml import html
import requests
west_tx_parks = requests.get('http://texascampgrounds.com/find-a-park?region=West&state=TX&task=findlocation')
west_tree = html.fromstring(west_tx_parks.text)
north_tx_parks = requests.get('http://texascampgrounds.com/find-a-park?region=North&state... | StarcoderdataPython |
47158 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
@author: lx0hacker
@date:2018-02-07
'''
import requests
from urllib.parse import unquote,urlparse
import re
import os
import os.path
from bs4 import BeautifulSoup
requests.packages.urllib3.disable_warnings()
import time
import random
'''
@url : 漫画的入口
@return 创建的文件夹的名字
'... | StarcoderdataPython |
3393718 | <reponame>LucasFDutra/pysls
import boto3
import json
import os
def invoke_function(function_name, service_name, event_path):
config_client = {
'service_name': 'lambda',
'aws_access_key_id': '123',
'aws_secret_access_key': '123',
'region_name': 'us-east-1',
'endpoint_url': 'h... | StarcoderdataPython |
181945 | <filename>create_function.py
from sys import argv
import json
if __name__ == "__main__":
function_content = None
dependencies = None
service_name = None
target_function = None
trigger_type = "http-trigger"
kafka_server = None
for i, arg in enumerate(argv):
if "--" not in arg:
continue
if arg... | StarcoderdataPython |
3285706 | <gh_stars>100-1000
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for divitional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Licen... | StarcoderdataPython |
1752850 | import prettytable as pt
import argparse
import urllib.request
class Resource():
def __init__(self, name, path, size, description):
self.name = name
self.path = path
self.size = size
self.description = description
def download(self, des_root):
if des_root ... | StarcoderdataPython |
4803667 | <filename>pydupes.py<gh_stars>0
import collections
import datetime
import functools
import gzip
import hashlib
import itertools
import json
import logging
import os.path
import pathlib
import queue
import stat
import threading
import typing
from collections import defaultdict
import click
from tqdm import tqdm
# size... | StarcoderdataPython |
3301034 | # test a round works
# test roll means land on right tile
# test roll with someone in front lands on right tile
# test roll past end lands on right tile
# test changing direction (same roll forward and backward)
# test picking up a tile
# test putting down a tile
# test tile value ranges
# test banking
# test ... | StarcoderdataPython |
3285611 | <gh_stars>1-10
import random
import time
from pprint import pprint
from selenium import webdriver
import pandas as pd
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
actions = ActionChains(driver)
time.sleep(5)
def load_u... | StarcoderdataPython |
1786389 | <reponame>j9ac9k/navitron<filename>crons/tests/test_cli_core.py
"""test_cli_core.py: tests expected behavior for global space"""
from os import path
import uuid
import dateutil.parser
import pytest
from plumbum import local
import pandas as pd
import semantic_version
import navitron_crons.exceptions as exceptions
imp... | StarcoderdataPython |
1706098 | import urllib.request
url="file:///C:/Users/NFate/Desktop/demo.html"
site=urllib.request.urlopen(url)
data=site.read().decode('utf-8')
print(data)
| StarcoderdataPython |
3288026 | <reponame>aliyura/fttcrypt-python
from setuptools import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="FTTCrypt",
version="0.0.1",
author="FTTCrypt.io",
author_email="<EMAIL>",
description="FTTCrypt Encryption, Encrypt Text to Cipher or any ... | StarcoderdataPython |
1710787 | """create schemas
Revision ID: 7f1be83ab61c
Revises:
Create Date: 2020-12-03 10:15:03.256592
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7f1be83ab61c'
down_revision = None
branch_labels = None
depends_on = None
def schema_command(base: str):
connecti... | StarcoderdataPython |
4820740 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# : Command Line Interface
# Author:
# c(Student) -> {'<NAME>'}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | StarcoderdataPython |
3255695 | <reponame>rhu2001/csua-backend
from django.urls import include, path
from django.conf.urls.static import static
from django.contrib import admin
from . import views
from .admin_views import admin, admin_group, admin_user
urlpatterns = [
path("", views.index),
path("user/<username>/", views.user),
path("us... | StarcoderdataPython |
4822638 | """
This package contains common parts of serializers.
"""
| StarcoderdataPython |
48720 |
"""
Library to fetch and parse the public Princeton COS courses history as a
Python dictionary or JSON data source.
"""
__version__ = '1.0.0'
__author__ = "<NAME> <<EMAIL>>"
__all__ = [
"CosCourseInstance",
"CosCourseTerm",
"fetch_cos_courses",
]
from princeton_scraper_cos_courses.parsing import CosCo... | StarcoderdataPython |
59062 | #! /bin/python
import sys
import os
import time
import glob
import simplejson as json
import subprocess
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
import config
import utils
#---------------------------------------------------------------------------------------
def main(dirlis... | StarcoderdataPython |
1711042 | from setuptools import setup
setup(
name='jetmon',
version='1',
packages=[''],
url='https://github.com/BlackburnHax/jetmon',
license='Apache License Version 2.0',
author='<NAME>',
author_email='<EMAIL>',
description='Verizon MiFi Jetpack monitoring'
)
| StarcoderdataPython |
126933 | <gh_stars>10-100
#!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 PanXu, Inc. All Rights Reserved
#
"""
测试 conll2003 dataset
Authors: panxu(<EMAIL>)
Date: 2020/06/26 22:07:00
"""
import os
import pytest
from ner.tests import ASSERT
def test_msra_dataset(msra_dataset):
"""
测试 msra 数... | StarcoderdataPython |
1625722 | <gh_stars>0
import hashlib
import math
P = 21888242871839275222246405745257275088696311157297823662689037894645226208583
B = 3
class CTHelpers:
@staticmethod
def getConditionId(cls, oracle, qustionId, outcomeSlotCount):
m = hashlib.md5()
m.update(oracle)
m.update(qustionId)
m.... | StarcoderdataPython |
3363271 | # coding=utf-8
"""
豆瓣爬虫: 用beautifulsoup4库获取豆瓣排行榜上每部电影的有利于分析的数据细节再写入csv文件
更新2.2.1: some little fixes on the way to standard
XX: 魔法值 连数据库 异常判断
Introduction: This program is to output the information of each movie in the top ten latest movie charts to a csv file
** API由豆瓣提供: https://developers.douban.com/wiki/?title=movi... | StarcoderdataPython |
56473 | <filename>TarangGUI.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'TarangGUI.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from ... | StarcoderdataPython |
3380080 | <filename>image_trasnformations/hello.py
def say_hello():
print("Hello pip")
| StarcoderdataPython |
3376353 | import numpy as np
import constants as ct
import argparse
from os.path import join
import logging
import sys
logger = logging.getLogger('tamaraw')
'''params'''
MON_SITE_NUM = 100
MON_INST_NUM = 90
UNMON_SITE_NUM = 9000
def config_logger():
# Set file
log_file = sys.stdout
ch = logging.StreamHandler(log_... | StarcoderdataPython |
29181 | a = float(input('Введите число: '))
def koren (a):
x = 3
k = 0
if (a<0):
raise ValueError('Ошибка, введите число, меньшее нуля')
while k != (a**0.5):
k = 0.5 * (x + a/x)
x = k
return(k)
print('Корень из числа ' + str(a) + ' равен ' + str(koren(a)))
| StarcoderdataPython |
1630752 | # -*- coding: utf-8 -*-
from django.conf.urls import patterns
from django.conf.urls import url
from networkapi.api_list_config_bgp.v4 import views
urlpatterns = patterns(
'',
url(r'^list-config-bgp/((?P<obj_ids>[;\w]+)/)?$',
views.ListConfigBGPDBView.as_view()),
)
| StarcoderdataPython |
1675420 | """Shelly entity helper."""
from dataclasses import dataclass
from typing import Any, Callable, Optional, Union
import aioshelly
from homeassistant.core import callback
from homeassistant.helpers import device_registry, entity, update_coordinator
from . import ShellyDeviceRestWrapper, ShellyDeviceWrapper
from .const... | StarcoderdataPython |
195045 | <filename>guibaker/ui/uimanager.py
import tkinter as tk
from tkinter import ttk
root = None
def CreateLabel (name) :
label = ttk.Label(root, text = name)
label.pack(pady = 8)
def CreateButton (name,function) :
button = ttk.Button(root, text = name, command = function)
button.pack(pady = 2)
def CreateEntry (... | StarcoderdataPython |
32685 | <gh_stars>1000+
import torch
class LossScaler:
def __init__(self, scale=1):
self.cur_scale = scale
# `params` is a list / generator of torch.Variable
def has_overflow(self, params):
return False
# `x` is a torch.Tensor
def _has_inf_or_nan(x):
return False
# `overflow... | StarcoderdataPython |
183406 | <filename>sensor_correction/gp_gpu.py
__author__ = '<NAME>'
__copyright__ = 'Copyright 2017, Profactor GmbH'
__license__ = 'BSD'
import numpy as np
import tensorflow as tf
class GPRegressorGPU:
'''Gaussian Process regressor on GPU.
Takes a pre-fitted Gaussian Process regressor (CPU) and prepares a TensorFlow... | StarcoderdataPython |
4814115 | from utils.image import ImgDraw
from nonebot.adapters.cqhttp.event import GroupMessageEvent
import pymongo
import datetime
from utils.group import User, make_query
from utils import NAME
import os
import json
import random
import nonebot
from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, MessageEv... | StarcoderdataPython |
3201581 | <reponame>issamhammad/RETS-Manager<gh_stars>1-10
import pickle
import boto3
import os
from web_app.models import Property, PropertyInfo, AgentDetails, DDF_LastUpdate
# from RETS_Manager.settings_aws import *
from .aws_settings import *
from . import db_write
#from .db_summary import *
from .ddf_logger import *
from .dd... | StarcoderdataPython |
3335806 | # Copyright 2021 The Narrenschiff Authors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in... | StarcoderdataPython |
140766 | from six.moves.urllib.parse import quote_plus
from . import get_cookies
def setup_session(openid, password, username=None,
check_url=None,
session=None, verify=False):
"""
A special call to get_cookies.setup_session that is tailored for
ESGF credentials.
username s... | StarcoderdataPython |
3252470 | """
zoom setups cli
"""
from argparse import ArgumentParser
import os
import sys
from zoom.cli.utils import legacy_command_argv
def setup():
"""set up a new Zoom instance"""
join = os.path.join
parser = ArgumentParser(
description='set up a new Zoom instance',
usage='zoom setup [opt... | StarcoderdataPython |
9799 | # -*- coding: utf-8 -*-
"""Implementation of MiniGoogLeNet architecture.
This implementation is based on the original implemetation of GoogLeNet.
The authors of the net used BN before Activation layer.
This should be switched.
"""
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutiona... | StarcoderdataPython |
3234397 | <reponame>Lyuhitto/extracting_files_from_dir<gh_stars>1-10
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.0)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x01\xa6\
\x89\
\x50\x4e... | StarcoderdataPython |
1672994 | <filename>maskrcnn_benchmark/data/datasets/evaluation/coco/coco_compute_and_eval.py<gh_stars>0
import torch
import logging
import tempfile
import os
from tqdm import tqdm
import numpy as np
from .coco_eval import evaluate_predictions_on_coco, COCOResults
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchma... | StarcoderdataPython |
13384 | <gh_stars>0
import sys
from gensim import models
from gensim.models.doc2vec import LabeledSentence
import pickle
def corpus_to_sentences(corpus):
sentences = []
for idx, (name, doc) in enumerate(corpus.items()):
sys.stdout.write('\r前処理中 {}/{}'.format(idx, len(corpus)))
sentence = LabeledSenten... | StarcoderdataPython |
1755473 | <reponame>andersop91/core
"""The test for the sql sensor platform."""
import pytest
import voluptuous as vol
from homeassistant.components.sql.sensor import validate_sql_select
from homeassistant.const import STATE_UNKNOWN
from homeassistant.setup import async_setup_component
async def test_query(hass):
"""Test ... | StarcoderdataPython |
945 | <filename>test/test_sampler.py<gh_stars>10-100
import numpy as np
import pandas as pd
from autogbt.sampler import MajorityUnderSampler
def _test_sample(y):
sampler = MajorityUnderSampler()
idx = sampler.sample(y, 40000, 3.0)
assert len(idx) == 40000
assert y[idx].sum() == 10000
def test_sample_with_... | StarcoderdataPython |
1741871 | import gevent
import json
import logging
import subprocess
from jadi import component
import aj
from aj.api.http import url, HttpPlugin
from aj.plugins import PluginManager, DirectoryPluginProvider
from aj.api.endpoint import endpoint
@component(HttpPlugin)
class Handler(HttpPlugin):
def __init__(self, context)... | StarcoderdataPython |
3204682 | <reponame>exarkun/foolscap<gh_stars>10-100
"""Foolscap"""
from ._version import get_versions
__version__ = str(get_versions()['version'])
del get_versions
| StarcoderdataPython |
35789 | <filename>docs/webflask/quiz_orm/quiz2_sa/app.py
# -*- coding: utf-8 -*-
# quiz-orm/app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
# konfiguracja aplikacji
app.config.update(dict(
SECRET_KEY='bardzosekretnawartosc',
DATABASE=os.path.join(app.root_path, ... | StarcoderdataPython |
1703737 | <gh_stars>0
py_frameworks = ['Python', 'Numpy','Pandas','Django', 'Flask']
for p in py_frameworks:
print(p)
| StarcoderdataPython |
3306430 | # Copyright (c) 2021-2022 <NAME>
# Licensed under the zlib/libpng License
# https://opensource.org/licenses/Zlib
import sys
import os
import platform
import ctypes as ct
is_windows = (bool(platform.win32_ver()[0]) or
(sys.platform in ("win32", "cygwin")) or
(sys.platform == "cli" and os.na... | StarcoderdataPython |
135543 | <filename>F20/SVM_3beat/ECG_preprocessing.py
import numpy as np
import h5py
import matplotlib.pyplot as plt
from scipy.signal import butter,lfilter,filtfilt,find_peaks,resample
import pywt
def ecg_preprocessing_final(original_signal,fs=240):
'''
This function is the whole preprocessing pipeline for E... | StarcoderdataPython |
1724945 | from .onset import \
MeasureOfTransience, MovingAveragePeakPicker, TimeSliceFeature, \
ComplexDomain | StarcoderdataPython |
1657484 | <gh_stars>1-10
# We could have user timeit but I'm afraid bank will ban us for that
import time
import random
from collections import deque
from concurrent.futures import ThreadPoolExecutor, as_completed
import utils
parser = utils.get_parser("bgp")()
NUMBER_OF_DATES = 20
date_diffs = list(range(10, NUMBER_OF_DATES +... | StarcoderdataPython |
3345878 | <filename>order/forms.py
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, Field, Fieldset, Layout, Submit
from django import forms
from .models import Order
class OrderCreateForm(forms.ModelForm):
class Meta:
model = Order
fields = [
"nombre",
"email",
"dire... | StarcoderdataPython |
1694222 | <filename>main.py
#!/usr/bin/env python3
"""Create entry-point."""
from sched.cli import group
if __name__ == "__main__":
group()
| StarcoderdataPython |
3282641 | <filename>bou/__init__.py
""" bou
~~~
A CLI migrations tool for sqlite.
See https://github.com/Feastybeast/bou for details.
"""
class BouError(Exception):
""" Root exception for the application """
pass
| StarcoderdataPython |
178917 | <gh_stars>1-10
'''
This script contains examples of functions that can be used from the SciKit-
Learn module.
'''
# Example ------------------------------------------------------------
# Create test data
import numpy as np
X, y = np.arange(10).reshape((5, 2)), range(5)
X
y
# Split test data into train & test data ... | StarcoderdataPython |
1729958 | <reponame>nathanawmk/SPARTA<filename>spar_python/analytics/ta3/generate_test_publications.py
import argparse
import re
import fileinput
import glob
import os
TEMPORARY_DIRECTORY_FILENAME = '__temporary__directory__'
OUTPUT_FILENAME_NAME = 'PUBLICATIONS.csv'
RESOLVE_TIMESTAMPS_PROGRAM = ''
TEST_NAME = ''
TEMPORARY_DIRE... | StarcoderdataPython |
1732434 | <gh_stars>0
import click
from ovos_skills_manager import OVOSSkillsManager
from pprint import pformat
APPSTORE_OPTIONS = ["ovos", "mycroft", "pling", "andlo", "neon", "all", "default"]
def print_config(appstore):
osm = OVOSSkillsManager()
if appstore == "all":
prompt = "Appstore configuration:\n" + p... | StarcoderdataPython |
138525 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Qt Widgets for implementing OpenFrames
"""
from PyQt5.QtWidgets import QWidget, QGridLayout, QSizePolicy
from PyQt5.QtGui import QWindow, QOpenGLContext
from PyQt5.QtCore import Qt, QSize, QCoreApplication, QEventLoop
from .PyOFInterfaceC import *
DEFAULT_WIDTH = 320
DEF... | StarcoderdataPython |
3334166 | <reponame>plandes/actioncli<filename>test/python/test_configfactory.py
import unittest
import logging
import shutil
from pathlib import Path
from zensols.actioncli import (
Config,
ConfigFactory,
ConfigManager,
DirectoryStash,
)
logger = logging.getLogger('zneosls.configfactory.test')
#logging.basicCon... | StarcoderdataPython |
1715513 | ''' An example of learning a DeepCFR Agent on No-Limit Texas Holdem
'''
import tensorflow as tf
import os
import rlcard
from rlcard.agents import DeepCFR
from rlcard.agents import RandomAgent
from rlcard.utils import set_global_seed, tournament
from rlcard.utils import Logger
# Make environment
env = rlcard.make('no... | StarcoderdataPython |
36421 | <gh_stars>0
# -*- coding: utf-8 -*-
from model.group import group
def test_add_group(app):
app.group.create(group(name="Name", header="Head", footer="Footer"))
def test_add_empty_group(app):
app.group.create(group(name="", header="", footer=""))
| StarcoderdataPython |
1753997 | #
# Copyright 2016 Cluster Labs, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | StarcoderdataPython |
1779694 | # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2021. <NAME> +
# All rights reserved. +
# This file is part of ... | StarcoderdataPython |
1709669 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: generateData.py
# Purpose: Make the data work...
#
# Authors: <NAME>
#
# Copyright: Copyright © 2016 <NAME> and cuthbertLab
# License: MIT, see LICENSE file
#-----------------------... | StarcoderdataPython |
1752006 | <filename>tests/service_atcoder.py
# -*- coding: utf-8 -*-
import unittest
import requests
from onlinejudge.service.atcoder import AtCoderContest, AtCoderProblem, AtCoderProblemDetailedData, AtCoderService, AtCoderSubmission
from onlinejudge.type import TestCase
class AtCoderSerivceTest(unittest.TestCase):
def ... | StarcoderdataPython |
3360898 | """
Time: O(H), since we are just moving vertically in the tree.
Space: O(1)
First, check if the node has right child, if so, continue the traversal.
If the node doesn't have right child, this mean that the node and all its children are visited.
We need to move up.
While moving up a node, if a node itself is a right c... | StarcoderdataPython |
4818437 | <reponame>voodoopeople42/Vproject<filename>Janus/python-base-unit_12/modules/module1/mymodule.py
# mymodule.py:
def sayhi():
print("Hi! Cool module said it!")
__version__ = '0.1'
if __name__ == '__main__':
print('Эта программа запущена сама по себе.')
else:
print('Меня импортировали в другой модуль.')
| StarcoderdataPython |
1681564 | <reponame>KillianSan/Calculadora
def calculate():
operation = input('''
Calculadora do <NAME> aka <NAME>:
Por favor, escolha uma das operações e digite o simbolo dela ou o nome e depois aperte ENTER:
+ adição | 3+ adição de 3 números | 4+ adição de 4 números
- subtração | 3- s... | StarcoderdataPython |
3215485 | <filename>tests/api/rules/compiler_rules_test.py
"""Tests templar/api/rules/core.py"""
from templar.api.rules.compiler_rules import MarkdownToHtmlRule
import unittest
class MarkdownToHtmlRuleTest(unittest.TestCase):
def setUp(self):
self.rule = MarkdownToHtmlRule()
def testApplies_default(self):
... | StarcoderdataPython |
1766988 | <reponame>onsoim/FuzzBuilderEx
#!/usr/bin/env python
import sys, os
def usage():
print ("[usage] python " + __file__ + " $seed_path $seed_out_path")
def main():
if len(sys.argv) != 3:
sys.exit(0)
seed_path = sys.argv[1]
seed_out_path = sys.argv[2]
if not os.path.exists(seed_out_path):
... | StarcoderdataPython |
3229005 |
from time import sleep
import gym
import subprocess
import numpy as np
from unittest import TestCase
"""
Assumes that the nats-server was started on port 127.0.0.1 with "nats-server -a 127.0.0.1".
Assumes that simulation_test.py is running with NATS connection to port 127.0.0.1, "python simulation_test.py -o 127.0.0.... | StarcoderdataPython |
21221 | """Compute ordinary Voronoi diagrams in Shapely geometries."""
import operator
import numpy
import scipy.spatial
import shapely.geometry
import shapely.geometry.base
import shapely.prepared
def pointset_bounds(coords):
return (
min(coords, key=operator.itemgetter(0))[0],
min(coords, key=operator... | StarcoderdataPython |
3360935 | from pathlib import Path
from playthrough.models import Game, GameConfig, Guild
from django.core.management import call_command
from . import PlaythroughTestBase
class TestMigrateShogun(PlaythroughTestBase):
def test_migrate_short(self):
db_path = Path(__file__).resolve().parents[0] / 'fixtures' / 'shog... | StarcoderdataPython |
1620966 | # single source of truth for package version,
# see https://packaging.python.org/en/latest/single_source_version/
__version__ = "0.1.0"
# app name to send as part of requests
app_name = "funcX Endpoint v{}".format(__version__)
| StarcoderdataPython |
148590 | # Copyright (c) 2020, <NAME>, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code mus... | StarcoderdataPython |
1746368 | <reponame>wahyuhadi/malinkundang<gh_stars>0
import motor.motor_asyncio
from bson import ObjectId
from decouple import config
MONGO_URL = config('DB_URL')
client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_URL)
database = client.Sangkuriang
# User database handler
user_collection = database.get_collection('users')
... | StarcoderdataPython |
1657293 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@ Author : pengj
@ date : 2018/11/28 12:24
@ IDE : PyCharm
@ GitHub : https://github.com/JackyPJB
@ Contact : <EMAIL>
--------------------... | StarcoderdataPython |
18307 | <filename>pythran/tests/cases/sobelfilter.py
#skip.runas import Image; im = Image.open("Scribus.gif"); image_list = list(im.getdata()); cols, rows = im.size; res = range(len(image_list)); sobelFilter(image_list, res, cols, rows)
#runas cols = 100; rows = 100 ;image_list=[x%10+y%20 for x in xrange(cols) for y in xrange(... | StarcoderdataPython |
1701004 | <gh_stars>0
#encoding:utf-8
import uuid
import imghdr
from flask import Flask
from flask import jsonify, make_response, render_template
from flask import request
from qiniu import Auth, put_data
app = Flask(__name__)
access_key = '<KEY>'
secret_key = '<KEY>'
def upload_file_qiniu(data):
q = Auth(access_key, sec... | StarcoderdataPython |
4804296 | from distutils.core import setup
setup(
name='python-crud',
version='0.0.1',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/GustavoHdezH/python-crud',
license='MIT',
description='Python script for show it data from sqlite',
long_description=open('README.md').read(),
... | StarcoderdataPython |
1799155 | import pandas as pd
import numpy as np
import nltk
import os
import nltk.corpus
import texts
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
from nltk import ne_chunk
def tokenize(text):
return word_tokenize(text)
... | StarcoderdataPython |
1607482 | <filename>examples/stuff/make_grid.py
import os
from mpl_toolkits.basemap import Basemap, shiftgrid
import matplotlib.colors as colors
from scipy.signal import medfilt2d
import netCDF4
import pycnal
import pycnal_toolbox
from ROMS_bathy_smoother import *
#Grid dimension
Lp = 150
Mp = 80
## define the 4 corners of t... | StarcoderdataPython |
1753751 | # -*- coding: utf-8 -*-
"""importing modules for package"""
from .dropdownmenu import DropDownMenu
| StarcoderdataPython |
3393251 | <filename>tests/snapshots/snap_test_holidata/test_holidata_produces_holidays_for_locale_and_year[pt_PT-2021] 1.py
[
{
'date': '2021-01-01',
'description': 'Ano Novo',
'locale': 'pt-PT',
'notes': '',
'region': '',
'type': 'NF'
},
{
'date': '2021-02-16',... | StarcoderdataPython |
130022 | <reponame>pkumar-singh/bookkeeper
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | StarcoderdataPython |
1699286 | <gh_stars>1-10
"""
python变量作用域
1 局部变量不会覆盖全局变量
2 局部变量不会被外部引用
3 局部没有会去找上一级
4 global会使局部变量变成全局变量
5 python没有块级作用域(如if, for, while)
"""
# a = 20
def fun1():
a = -10
def fun2():
# a = 10 # 局部变量
print(a)
return fun2
#fun1()()
#print(a)
def change():
global a
a = 100
print(a)
#a =... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.