id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3437522 | # pylint: disable=too-many-locals
import os
import argparse
import argcomplete
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import Logist... | StarcoderdataPython |
4835543 | <reponame>btjanaka/competitive-programming-solutions<filename>leetcode/452.py
# Author: btjanaka (<NAME>)
# Problem: (LeetCode) 452
# Title: Minimum Number of Arrows to Burst Balloons
# Link: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/
# Idea: Represent the horizontal coordinates as a seri... | StarcoderdataPython |
1946923 | import os
import logging
import numpy as np
'''
@ Multifactorial Evolutionary Algorithm
'''
def sbx_crossover(p1, p2, sbxdi):
D = p1.shape[0]
cf = np.empty([D])
u = np.random.rand(D)
cf[u <= 0.5] = np.power((2 * u[u <= 0.5]), (1 / (sbxdi + 1)))
cf[u > 0.5] = np.power((2 * (1 - u[u > 0.5]))... | StarcoderdataPython |
6669190 | <filename>python/leetcode/22.py
# 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
#
# 例如,给出 n = 3,生成结果为:
#
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
#
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/generate-parentheses
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import L... | StarcoderdataPython |
9738700 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | StarcoderdataPython |
6553760 | from .checker import XPermittedCrossDomainPolicyChecker
from .notnone import XPCDPNotNoneChecker
__all__ = ['XPermittedCrossDomainPolicyChecker','XPCDPNotNoneChecker']
| StarcoderdataPython |
8055606 | <reponame>carlsummer/python_developer_tools<gh_stars>10-100
# !/usr/bin/env python
# -- coding: utf-8 --
# @Author zengxiaohui
# Datatime:4/29/2021 2:41 PM
# @File:setup
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md'), e... | StarcoderdataPython |
4878279 | from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django_webtest import WebTest
from ..remote_user_auth import email_to_username
class AuthTests(WebTest):
def test_email_domain_validation(self):
"""Ensure that a given email address is a member of the ri... | StarcoderdataPython |
4899274 | import tool.utils as utils
from tool.template import _Template
from tool.utils import config
from tool.utils import content_path
import tool.module as module
class _Router():
def __init__(self,post_list):
self.post_list = post_list
self.home = _Home(post_list)
self.archive = _Archive(post_l... | StarcoderdataPython |
1645400 | <gh_stars>1-10
import pytest
import responses
from tenable.nessus.iterators.pagination import PaginationIterator
@responses.activate
def test_pagination_iterator(nessus):
responses.add(responses.GET,
'https://localhost:8834/page',
json={'envelope': [{'id': i} for i in range(100... | StarcoderdataPython |
8059269 | from prettytable import PrettyTable
from textwrap import fill, TextWrapper
import frontmatter
import re
from .storage import configStorage as config
# For recursive display of a discussion thread (--comments + --parents)
currentThreadDepth = 0
def markdownify(t):
width = 120
def mdCodeBlock(t):
retu... | StarcoderdataPython |
3345748 | <gh_stars>1-10
# This sample tests the type checker's handling of
# empty tuples and assignment to empty tuples.
from typing import Tuple
a: Tuple[()] = ()
# This should generate an error because the assigned
# tuple has one element, but the destination is
# expecting zero.
b: Tuple[()] = (1, )
# This should genera... | StarcoderdataPython |
3267774 | from plugin.models import NotificationUserSetting
from part.test_part import BaseNotificationIntegrationTest
from plugin.builtin.integration.core_notifications import CoreNotificationsPlugin
from plugin import registry
class CoreNotificationTestTests(BaseNotificationIntegrationTest):
def test_email(self):
... | StarcoderdataPython |
11344197 | #coding:utf-8
import json
import re
from django.http import HttpResponse
# 数据库接口导入
from hbh import models as hbh_models
info = {
'fail': '失败',
'error': '错误',
'Success': '成功'
}
# 注册用户
def addUser(request):
if request.method == "POST":
data = request.POST
if hbh_models.... | StarcoderdataPython |
367004 | <filename>bin/test_siamfc.py<gh_stars>1-10
from __future__ import absolute_import
import os
from got10k.experiments import *
from siamfc import SiamFCTracker
import multiprocessing
multiprocessing.set_start_method('spawn',True)
gpu_id=0
model_path='./models/siamfc_30.pth'
# model_gpu=nn.DataParallel(model,device_... | StarcoderdataPython |
1680866 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 12 19:49:18 2020
@author: hongxing
"""
import torch
import numpy as np
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
torch.manual_seed(1) # reproducible
def Graying(img):
i = 0
grayed = 0
for chan... | StarcoderdataPython |
12828068 | import glob
import os
from flask import current_app
from flask.cli import AppGroup
from flask_fixtures.loaders import YAMLLoader
from flask_fixtures import load_fixtures
from flask_market.products.models import db
user_cli = AppGroup('fixtures')
@user_cli.command('load')
def load_fixtures_():
for fixture_dir in... | StarcoderdataPython |
9604005 | <reponame>btisdall/ecs-cid<filename>tests/conftest.py
import json
import pytest
@pytest.fixture
def event_no_message():
return {
u'Records': [
{
u'EventVersion': u'1.0',
u'EventSubscriptionArn': u'arn:aws:sns:eu-west-1:271871120138:ecs-container-drainer:ee13e8e3-... | StarcoderdataPython |
8058343 | <gh_stars>1000+
from opensfm.actions import compute_depthmaps
from . import command
class Command(command.CommandBase):
name = "compute_depthmaps"
help = "Compute depthmap"
def run_impl(self, dataset, args):
compute_depthmaps.run_dataset(dataset, args.subfolder, args.interactive)
def add_ar... | StarcoderdataPython |
1727223 | import numpy as np
# Change False to True for each block of code to see what it does
# Arithmetic operations between 2 NumPy arrays
if False:
a = np.array([1, 2, 3, 4])
b = np.array([1, 2, 1, 2])
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** b)
# Arithmetic operations be... | StarcoderdataPython |
175341 | import math
from .lang import H, sig, t
#=============================================================================#
# Standard types, classes, and related functions
## Basic data types
from .Data.Maybe import Maybe, Just, Nothing, in_maybe, maybe
from .Data.Either import Either, Left, Right, in_either, either
... | StarcoderdataPython |
11394913 | <reponame>e-mission/e-mission-ng-aggregator
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# Standard imports
from future import standard_library
standard_library.install_aliases()
from builtins import *
import unittes... | StarcoderdataPython |
11217499 |
# coding: utf-8
# In[1]:
import scipy.io
import numpy as np
import matplotlib.pyplot as pyplot
from PIL import Image
import matplotlib.cm as cm
from pprint import pprint
import scipy.misc
import PIL
import KMeansUtilities as km
# In[2]:
def is_background(mat,colno):
row,col=mat.shape
for i in range(0,ro... | StarcoderdataPython |
9780982 | #!/home/kevinml/anaconda3/bin/python3.7
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 13:15:02 2019
@author: juangabriel and <NAME>
"""
# Clustering Jerárquico
# =======================================================================================================
# PASOS
#
# Hay 2 tipos de agrupaciones jerarqu... | StarcoderdataPython |
6639776 | <filename>trade/utils/common.py<gh_stars>1-10
# -*- coding: utf-8 -*-
""" This file contains common modules and packages that will be imported into
the modules for the trading of the coin market price data.
"""
# OS/Standard imports
import sys
import os
import io
from os import listdir
import time
import datetime
... | StarcoderdataPython |
1951869 | <reponame>Holldean/pytorch-models<gh_stars>0
import torch.nn as nn
import torch
from model.activation import activation_layer
class DNNLayer(nn.Module):
def __init__(self,
inputs_dim,
hidden_units,
activation='relu',
dropout_rate=0,
... | StarcoderdataPython |
12847448 | import argparse
import unittest
from ffwd.ffwd_send import tag_type
class TestFFWDSend(unittest.TestCase):
def test_tag_type(self):
self.assertEquals(('hello', 'world'), tag_type("hello:world"))
self.assertEquals(('hello', 'world:two'), tag_type("hello:world:two"))
with self.assertRaises... | StarcoderdataPython |
9688397 | import pyttsx3 #pip install pyttsx3
import speech_recognition as sr #pip install SpeechRecognition
import datetime
import wikipedia #pip install wikipedia
import webbrowser
import os
import smtplib
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
# print(voices[0].id)
engine.setProperty('voice', vo... | StarcoderdataPython |
149741 | #<NAME>, JAIME. 2018
import cv2
from reconocimiento_operaciones import crear_modelo_operaciones
from reconocimiento_operaciones import prediccion_operacion
from reconocimiento_numeros import cargar_numeros_desde_mnist
from reconocimiento_numeros import crear_modelo_numeros
from reconocimiento_numeros import prediccion_... | StarcoderdataPython |
8091639 | <filename>RoboOps/RoboOps.py
import subprocess
from pathlib import Path
from robot.api import logger
from robot.api.deco import library, keyword
from robot.libraries.BuiltIn import BuiltIn
from robot.running.model import TestCase
from robot.result.model import TestCase as TestCaseResult
import shlex
class ErrorsAreFa... | StarcoderdataPython |
338989 | <filename>lib/silfont/scripts/psfsyncmeta.py<gh_stars>1-10
#!/usr/bin/env python
from __future__ import unicode_literals
'''Sync metadata accross a family of fonts assuming standard UFO file naming'''
__url__ = 'http://github.com/silnrsi/pysilfont'
__copyright__ = 'Copyright (c) 2017 SIL International (http://www.sil.o... | StarcoderdataPython |
5100338 | <filename>libraries/AceTime/tools/tzcompiler.py
#!/usr/bin/env python3
#
# Copyright 2018 <NAME>
#
# MIT License.
"""
Main driver for TZ Database compiler which parses the TZ Database files, and
generates zoneinfo files and validation datasets for unit tests.
"""
import argparse
import logging
import sys
from extracto... | StarcoderdataPython |
3553634 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
ResNet50 models base on Keras.
This procedure is suitable for the situation that you need to quickly train
a ResNet50 network as a classification.
The program will do fine turning on the weights pretrained by imageNet.
If you want to start training from scratch on t... | StarcoderdataPython |
3225074 | <filename>derivations/scripts/sympy_addons.py
from sympy.core.symbol import Symbol
from sympy.tensor.indexed import Idx, IndexedBase, Indexed
from sympy.concrete import Product
from sympy.core.compatibility import is_sequence
from sympy.core.singleton import S
from sympy.core.add import Add
from sympy.core.function imp... | StarcoderdataPython |
11277524 | import os
from os.path import join, dirname
from dotenv import load_dotenv
import glob
from source.replay_reader import Replay_reader
from source.stats_service import Stats_service
#setup
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
xml_path = os.environ.get('xml_path')
csv_directory = os.env... | StarcoderdataPython |
6668272 | #!/usr/bin/python
import getopt
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.stats import pearsonr, spearmanr
import sys
# Directories
result_dir = "results/"
plot_dir = "plots/"
# Expected metric column names in result CSV file:
col_human = "Human"
col_coh = "Cohere... | StarcoderdataPython |
6583746 | """
Templates for cheetah configuration. This should be used as little as possible:
ideally scripts should be stored separately and be independently testable.
For example, bash scripts can use environment variables for customization
instead of being templates.
"""
CAMPAIGN_ENV_TEMPLATE = """
export CODAR_CHEETAH_EXPE... | StarcoderdataPython |
6693254 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... | StarcoderdataPython |
336344 | def k_th_smallest_distance(nums):
nums_pairs = []
for i in nums:
for j in nums[i:]:
nums_pairs.append((i, j))
return nums_pairs
nums = [1, 3, 1]
print(k_th_smallest_distance(nums))
def k_th_smallest_distance(nums):
nums.sort()
for index in range(k):
| StarcoderdataPython |
188503 | from getratings.models.ratings import Ratings
class NA_Zed_Jng_Aatrox(Ratings):
pass
class NA_Zed_Jng_Ahri(Ratings):
pass
class NA_Zed_Jng_Akali(Ratings):
pass
class NA_Zed_Jng_Alistar(Ratings):
pass
class NA_Zed_Jng_Amumu(Ratings):
pass
class NA_Zed_Jng_Anivia(Ratings):
pass
class NA_Z... | StarcoderdataPython |
6675440 | <reponame>mwesterhof/wagtail_managed404<gh_stars>1-10
from django.db import models
from wagtail.admin.edit_handlers import (
FieldPanel, MultiFieldPanel, PageChooserPanel)
from wagtail.core.models import Page, Site
class PageNotFoundEntry(models.Model):
site = models.ForeignKey(
Site, related_name='pa... | StarcoderdataPython |
3500636 | <filename>isobenefit_cities/image_io.py
from PIL import Image
import numpy as np
from matplotlib import cm
def import_2Darray_from_image(filepath):
pic = Image.open(filepath)
data = np.array(pic.getdata()).reshape(pic.size[1], pic.size[0], -1).mean(axis=2)
data_rescaled = (data - data.min()) / (data.max() ... | StarcoderdataPython |
6430672 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_schemas.ops.build_job.op import BuildConfig, BuildSchema # noqa
| StarcoderdataPython |
6531358 | """Test Tecan automation script generation."""
import unittest
from synbio.containers import Well
from synbio.instructions import Instruction, Transfer
from synbio.picklists import to_tecan
class TestTecan(unittest.TestCase):
"""Tecan picklist generation."""
def test_to_tecan(self):
"""Create a Tec... | StarcoderdataPython |
6511882 | <reponame>jmcroft7/dadpro<gh_stars>0
from flask_app import app
from flask import render_template, request, redirect, jsonify, session
from flask import flash
import requests
# class for User
class Joke:
def __init__(self, id, contents):
self.id = id
self.contents = contents
# classmethods
# ====... | StarcoderdataPython |
3308079 | import re as _re
from mp.core.expression import Expression as Exp
class EventUnit:
def __init__(self, event_name: str, method, unique, fixed, hidden, is_regex: bool = False):
self._event_name = event_name
self._event_name_compiled = _re.compile(self._event_name) if is_regex else None
self... | StarcoderdataPython |
1974812 | class Vehiculo:
color = ""
ruedas = 0
energia = 0
nombre = ""
def __init__(self, nombre, ruedas, energia, color):
self.nombre = nombre
self.ruedas = ruedas
self.energia = energia
self.color = color
def __repr__(self):
return f'Este es un vehiculo llamad... | StarcoderdataPython |
3255714 | import smv
class input(smv.SmvCsvFile):
def path(self):
return "employment/CB1200CZ11.csv"
| StarcoderdataPython |
1766057 | from collections import Counter
def palindrome_permutation(string):
string = string.replace(" ", "")
counter = Counter()
for letter in string:
counter[letter] += 1
odd = 0
for total in counter.values():
odd += total % 2
if odd > 1:
return False
return Tr... | StarcoderdataPython |
8086964 | def sortByHeight(a):
treePositions = [x for x in range(len(a)) if a[x] == -1]
people = sorted([x for x in a if x != -1])
for tree in treePositions:
people.insert(tree, -1)
return people
| StarcoderdataPython |
182558 | <reponame>zhiming-shen/Xen-Blanket-NG
import fcntl
import os
def close_fds(pass_fds=()):
try:
MAXFD = os.sysconf('SC_OPEN_MAX')
except:
MAXFD = 256
for i in range(3, MAXFD):
if i in pass_fds:
continue
try:
os.close(i)
except OSError:
... | StarcoderdataPython |
11273899 | from .apitools import ApiTools
def setup(bot):
bot.add_cog(ApiTools(bot))
| StarcoderdataPython |
6428012 | # Make a class called User. Create two attributes called first_name
# and last_name, and then create several other attributes that are typically stored
# in a user profile. Make a method called describe_user() that prints a summary
# of the user’s information. Make another method called greet_user() that prints
# a per... | StarcoderdataPython |
4926127 | --- Lib/site.py Tue Jul 20 04:28:28 2004
+++ Lib/site.py.new Mon Apr 4 10:47:12 2005
@@ -186,6 +186,7 @@
else:
sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
if sys.platform == 'darwin':
+ sitedirs.append( os.path.join('__PREFIX__', 'lib', 'p... | StarcoderdataPython |
9729094 | subscription_key = "82d9b1e05e16413d8bcca30f32b1ca83"
assert subscription_key
# You must use the same region in your REST call as you used to get your
# subscription keys. For example, if you got your subscription keys from
# westus, replace "westcentralus" in the URI below with "westus".
#
# Free trial subscription k... | StarcoderdataPython |
1784349 | <filename>sanic_ext/extensions/http/cors.py
import re
from dataclasses import dataclass
from datetime import timedelta
from types import SimpleNamespace
from typing import Any, FrozenSet, List, Optional, Tuple, Union
from sanic import HTTPResponse, Request, Sanic
from sanic.exceptions import SanicException
from sanic.... | StarcoderdataPython |
1653590 | from flask import Flask, redirect, url_for, request, render_template, Response, stream_with_context
import ancv_html_scraper as ancv
import logging
from logging.handlers import RotatingFileHandler
from database.db import initialize_db, drop_db
from database.models import Restaurants
import json
from pymongo import Mong... | StarcoderdataPython |
4826130 | <filename>libtaxii/__init__.py
# Copyright (c) 2017, The MITRE Corporation
# For license information, see the LICENSE.txt file
"""
The main libtaxii module
"""
import six
from six.moves import urllib
import libtaxii.messages_10 as tm10
import libtaxii.messages_11 as tm11
import libtaxii.clients as tc
from .constants... | StarcoderdataPython |
6417088 | import os
import matplotlib.pyplot as plt
import cPickle as pickle
import tensorflow as tf
from showattendtell.core.test_solver import CaptioningSolver
from showattendtell.core.model import CaptionGenerator
from showattendtell.core.utils import load_coco_data
from showattendtell.core.bleu import evaluate
dir_path = o... | StarcoderdataPython |
11346025 | """
Curses keycode parser. Exports (see function docstrings for more info):
- `key_to_name_mods`: parses curses keycode and returns the key name and its modifiers.
- `key_to_username`: parses curses keycode and returns the user-readable key name incl. modifiers
2020 by <NAME>
** LICENSE: The Unlicense **
This is f... | StarcoderdataPython |
5070621 | <gh_stars>1000+
# -----------------------------------------------------------------------------
# yacc_simple.py
#
# A simple, properly specifier grammar
# -----------------------------------------------------------------------------
from .calclex import tokens
from ply import yacc
# Parsing rules
precedence = (
... | StarcoderdataPython |
9717179 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import unittest
import sys
from .common_imports import StringIO, etree, HelperTestCase, _str, _bytes, _chr
try:
unicode
except NameError:
unicode = str
ascii_uni = _bytes("a").decode("utf8")
klingon = _bytes("\\uF8D2").decode("unicode_escape") ... | StarcoderdataPython |
4987186 | import pandas as pd
NAMES ={
'locations':["Coal Oil Point"],
'collector':["UAV: Matrice 100"],
'device': ["RTL-SDR New"]
}
SOURCES = [
{
"name": "CHANNEL_SCAN-1",
'label': "SB 1",
'location': 0,
'vehicle': 0,
'device': 0,
"altitude-adjust": -14.11,
},
{
... | StarcoderdataPython |
3508323 | from scenarios import *
scenario = (
send_stanza("<presence from='{jid_one}/{resource_one}' to='#aaa%{irc_server_one}/{nick_one}' ><x xmlns='http://jabber.org/protocol/muc'/></presence>"),
sequences.connection("irc.localhost", '{jid_one}/{resource_one}'),
expect_stanza("/presence"),
expect_stanza("/mes... | StarcoderdataPython |
269 | <reponame>jaraco/hgtools
import os
import pytest
from hgtools import managers
def _ensure_present(mgr):
try:
mgr.version()
except Exception:
pytest.skip()
@pytest.fixture
def tmpdir_as_cwd(tmpdir):
with tmpdir.as_cwd():
yield tmpdir
@pytest.fixture
def hg_repo(tmpdir_as_cwd):... | StarcoderdataPython |
5159630 | import numpy as np
import torch
from tqdm import tqdm
from .. import effdet_wrapper as det
from ..module import BoundingBoxDetector
from ..util import from_PIL_to_cv
class YetAnotherEfficientDetDetector(BoundingBoxDetector):
def __init__(self, anchor_ratios, anchor_scales,
compound_coef, num_classes, mode... | StarcoderdataPython |
8105017 | # -*- coding: utf-8 -*-
import os
import cv2
import math
import torch
import numpy as np
import torch.nn.functional as F
class Detection:
def __init__(self):
caffemodel = "./checkpoint/Widerface-RetinaFace.caffemodel"
deploy = "./checkpoint/deploy.prototxt"
self.detector = cv2.dnn.readNetF... | StarcoderdataPython |
25810 | <gh_stars>0
from datetime import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from kitsune.sumo.models import ModelBase, LocaleField
from kitsune.sumo.urlresolvers import reverse
from kitsune.sumo.utils import auto_delete_files
class Media(ModelB... | StarcoderdataPython |
1650652 | <reponame>BlueBrain/Spack
from spack import *
from spack.pkg.builtin.py_pyarrow import PyPyarrow as BuiltinPyPyarrow
class PyPyarrow(BuiltinPyPyarrow):
__doc__ = BuiltinPyPyarrow.__doc__
version('6.0.1', sha256='423990d56cd8f12283b67367d48e142739b789085185018eb03d05087c3c8d43')
for v in ('@6.0.1',):
... | StarcoderdataPython |
29220 | <reponame>jiadaizhao/LintCode<filename>1301-1400/1387-Binary Trees With Factors/1387-Binary Trees With Factors.py
class Solution:
"""
@param A:
@return: nothing
"""
def numFactoredBinaryTrees(self, A):
A.sort()
MOD = 10 ** 9 + 7
dp = {}
for j in range(len(A)):
... | StarcoderdataPython |
6449490 | from opserver.plugins.alarm_base import *
from opserver.sandesh.alarmgen_ctrl.sandesh_alarm_base.ttypes import *
import json
class ProcessStatus(AlarmBase):
"""Process Failure.
NodeMgr reports abnormal status for process(es) in NodeStatus.process_info"""
def __init__(self):
AlarmBase.__init__(self,... | StarcoderdataPython |
6547547 | <reponame>M0gician/lightRaven<gh_stars>1-10
from .base import SamplingBase
from .imptsamp import IS
from .pdis import PDIS
from .wis import WIS
from .cwpdis import CWPDIS
| StarcoderdataPython |
4928669 | <filename>sts2/game/arena.py
# Copyright (C) 2020 Electronic Arts Inc. All rights reserved.
import numpy
class Arena:
def __init__(self, arena_size):
self.arena_size = arena_size
self.max_x = arena_size[0] / 2
self.min_x = -self.max_x
self.max_z = arena_size[1] / 2
self.m... | StarcoderdataPython |
3496889 | import gym
import jax
import jax.numpy as jnp
import coax
import haiku as hk
from numpy import prod
import optax
# the name of this script
name = 'ppo'
# the Pendulum MDP
env = gym.make('Pendulum-v0')
env = coax.wrappers.TrainMonitor(env, name=name, tensorboard_dir=f"./data/tensorboard/{name}")
def func_pi(S, is_t... | StarcoderdataPython |
110508 |
from .code import stupid_sum, stupid_mul
| StarcoderdataPython |
4978262 | import numpy
from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
ext_modules=[
Extension('_filter', ['speaker_filter/_filter.pyx'], include_dirs=[numpy.get_include()]),
]
setup(
name = 'diy-speaker-filter',
cmdclass = {'build_ext': build_ext},
ext_m... | StarcoderdataPython |
6705666 | <filename>library/migrations/0026_auto_20180825_2056.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-08-25 20:56
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('library', '0025_auto_201... | StarcoderdataPython |
11398906 | from __future__ import absolute_import, print_function
import os
import pytest
from bokeh.io import output_file
from .webserver import SimpleWebServer
@pytest.fixture(scope='session', autouse=True)
def server(request):
server = SimpleWebServer()
server.start()
def stop_server():
server.stop()
... | StarcoderdataPython |
8041844 | <reponame>jolo-dev/show-solidarity<filename>tests/test_lambda.py<gh_stars>0
# from function.put_object import handler
# import json
# from os import path
# import pytest
# @pytest.fixture
# def test_event():
# with open(path.join(path.dirname(__file__), "event.json"), "r") as f:
# event = json.load(f)
# ... | StarcoderdataPython |
4883766 | <reponame>LukeHackett/rpi-temperature-sensor
#!/usr/bin/env python3
import os
import json
import time
import argparse
import urllib.request
import Adafruit_DHT
# Sensor Settings
# Set sensor type : Options are DHT11,DHT22 or AM2302
SENSOR = Adafruit_DHT.DHT11
GPIO_PIN = os.getenv('GPIO_PIN', 17)
# Open Weather Appli... | StarcoderdataPython |
1783425 | <filename>test/unit/messages/bloxroute/test_bloxroute_version_manager_v7.py<gh_stars>10-100
from unittest import skip
from bxcommon import constants
from bxcommon.messages.bloxroute.ack_message import AckMessage
from bxcommon.messages.bloxroute.bdn_performance_stats_message import BdnPerformanceStatsMessage
from bxcom... | StarcoderdataPython |
3321566 | <gh_stars>0
import random
import time
import matplotlib.pyplot as plt
class Find():
def __init__(self):
self.alphabet=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
self.word= 'SORRY'
self.splitted= ... | StarcoderdataPython |
5046054 | <gh_stars>1-10
import json
import discord_pass
import fnmatch
import datetime
import math
import asyncio
intervals = (
('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60
('minutes', 60),
('seconds', 1),
)
def check_blacklist(ctx):
with open("sto... | StarcoderdataPython |
6623217 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="multiview_gpu",
version="0.1.0",
author="<NAME>",
author_email="<EMAIL>",
description="GPU-accelerated multiview clustering and dimensionality reduction",
long_description=long_descrip... | StarcoderdataPython |
3207290 | #!usr/bin/python
"""
Script to download Open Street Map data of land use. Converts to GeoJSON
<NAME>
WB-DIME
Jan 31 2017
"""
from country_bounding_boxes import (
country_subunits_containing_point,
country_subunits_by_iso_code
)
from utils.overpass_client import OverpassClient
from numpy import floor
fro... | StarcoderdataPython |
8141196 | import math
import random
import pytorch_lightning as pl
import torch
import os
import pickle
import cv2
import numpy as np
from torch.utils import data
from datasets.init_dataset import get_dataset
from ACT_utils.ACT_utils import tubelet_in_out_tubes, tubelet_has_gt
from MOC_utils.gaussian_hm import gaussian_radius,... | StarcoderdataPython |
1893741 | # internal
from src.ui.resources import icons
from .order_details import OrderDetails
from src.ui.components import BaseWidget, Table
# pyqt
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QSize, QDateTime
from PyQt5.QtWidgets import (QMainWindow, QWidget, QFrame, QTabWidget,
QHBoxLa... | StarcoderdataPython |
11392003 | <gh_stars>0
# coding=utf-8
import mock
from dmutils.asset_fingerprint import AssetFingerprinter
@mock.patch(
'dmutils.asset_fingerprint.AssetFingerprinter.get_asset_file_contents'
)
class TestAssetFingerprint(object):
def test_url_format(self, get_file_content_mock):
get_file_content_mock.return_valu... | StarcoderdataPython |
5178704 | <gh_stars>1-10
"""
Author: <NAME>
Created: 10.01.2021
"""
from datetime import datetime
from granturismo_stats import api
week_number = datetime.now().isocalendar()[1]
for mode in (api.SportsMode.DAILY_A, api.SportsMode.DAILY_B, api.SportsMode.DAILY_C):
event_details = api.get_event_details(mode)
event_deta... | StarcoderdataPython |
40761 | v_carro = float(input("Informe o valor: "))
total_mes_carro = (0.004 * v_carro) +v_carro
p_inicial = 10000
renda_total = (0.007 * p_inicial) + p_inicial
mes = -1
while True:
mes += 1
total_mes_carro = (0.004 * total_mes_carro) + total_mes_carro
if renda_total < total_mes_carro:
renda_total = (0.007 ... | StarcoderdataPython |
1609812 | """
MyToolBox is a collection of reusable tools.
Author: <EMAIL>
Copyright (C) CERN 2013-2021
"""
import sys
AUTHOR = "<NAME> <<EMAIL>>"
COPYRIGHT = "Copyright (C) CERN 2013-2021"
VERSION = "0.1.0"
DATE = "01 Mar 2013"
__author__ = AUTHOR
__version__ = VERSION
__date__ = DATE
PY2 = sys.hexversion < 0x03000000
PY3... | StarcoderdataPython |
1813326 | <gh_stars>1-10
n = int(input())
s = input()
for i in reversed(range(1, n+1)):
if i == 1:
print(f"1 bottle of {s} on the wall, 1 bottle of {s}.")
print(f"Take it down, pass it around, no more bottles of {s}.")
elif i == 2:
print(f"2 bottles of {s} on the wall, 2 bottles of {s}.")
... | StarcoderdataPython |
6574016 | import pytest
@pytest.fixture(scope='function')
def talon(ctre):
return ctre.WPI_TalonSRX(1)
@pytest.fixture(scope='function')
def cdata(talon, hal_data):
return hal_data['CAN'][1]
def test_talon_init(ctre, hal_data):
assert 1 not in hal_data['CAN']
ctre.WPI_TalonSRX(1)
assert 1 in hal_data['CA... | StarcoderdataPython |
11331764 | def main():
print("""Library Memrise Scraping - Author: <NAME>""")
print(f"Package: {__package__}")
print("Github: https://github.com/tquangsdh20/memrise")
# if __name__ == main():
# main()
| StarcoderdataPython |
9691756 | <filename>motor.py
from gpiozero import Motor
import pygame
from pygame.locals import *
motor = Motor(2, 3)
motor.enable()
done = false
while not done:
event = pygame.event.poll()
if event.type == pygame.QUIT:
done = true
elif event.type == pygame.KEYUP:
if event.key == pygame.K_w:
... | StarcoderdataPython |
1660903 | <gh_stars>1-10
#!/usr/bin/env python
# coding=utf-8
# Import third-party packages.
import numpy
import torch
class Agent:
"""Agent trainer.
"""
BATCH_SIZE = 32
MIN_SAMPLE = 64
LR = 0.00025
L2 = 0.0030
def __init__(self, model, memory):
"""Special method for object initialisation.
:param model: the pre... | StarcoderdataPython |
1611678 | <reponame>legionscript/Django-3.2-Series<gh_stars>0
# Generated by Django 3.2.3 on 2021-05-31 20:23
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Artist',
... | StarcoderdataPython |
9744843 | """
======================================================
Experiment Infrastructure (:mod:`mlpy.experiments`)
======================================================
.. currentmodule:: mlpy.experiments
.. autosummary::
:toctree: generated/
:nosignatures:
Experiment
Tasks
=====
.. autosummary::
:toctre... | StarcoderdataPython |
6482548 | <gh_stars>1-10
import numpy as np
import sys
import os
import requests
import pylru
import schedule
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#get parent dir path: memory_py
sys.path.insert(0, parentdir)
from SolrClient import SolrClient
from utils.query_util import tokenize
from utils.s... | StarcoderdataPython |
3385820 | #
# Copyright (c) 2015 Cossack Labs Limited
#
# 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.