id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6280 |
import numpy as np
import random
from collections import namedtuple
def generate_prob_matrix(n):
matrix = np.random.rand(n, n)
for i in range(n):
matrix[i][i] = 0
for i in range(n):
matrix[i] = (1/np.sum(matrix[i]))*matrix[i]
return matrix
def categorical(p):
return np.random... | StarcoderdataPython |
11206362 | from typing import Any, Dict, Tuple
import structlog
from scenario_player.exceptions.config import ScenarioConfigurationError
log = structlog.get_logger(__name__)
class ScenarioConfig:
"""Thin wrapper class around the "scenario" setting section of a loaded scenario .yaml file.
The configuration will autom... | StarcoderdataPython |
5031172 | <gh_stars>0
from random import randint
import pygame
pygame.font.init()
class kareEnemy:
def __init__(self, health, name, x, y, color, width, height):
self.name = name
self.health = health
self.x = x
self.y = y
self.color = color
self.width = width
... | StarcoderdataPython |
25502 | <filename>examples/lolcode_rockstar.py
from rockstar import RockStar
lolcode_code = """HAI
CAN HAS STDIO?
VISIBLE "HAI WORLD!"
KTHXBYE"""
rock_it_bro = RockStar(days=400, file_name='helloworld.lol', code=lolcode_code)
rock_it_bro.make_me_a_rockstar()
| StarcoderdataPython |
1629163 | <filename>detection.py
"""
This module detects objects in images
takes RGB image as input
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1)
# import pathlib
import tensorflow as tf
# import time
from object_detection.utils import label_map_util
from object_detection.utils import... | StarcoderdataPython |
4837431 | <gh_stars>0
print("the car is exiting") | StarcoderdataPython |
3348634 | <reponame>FrySabotage/selenium<gh_stars>1-10
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache Licens... | StarcoderdataPython |
1700929 | '''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
# Write your code here
n = int(input())
arr = [int(i) for i in inp... | StarcoderdataPython |
125539 | <filename>stsc/__main__.py
#!/usr/bin/env python3
import stsc.parser as parser
from stsc.run import run
from stsc.look import look
from stsc.progress import progress
from stsc.test import test
def main():
prs = parser.make_parser()
args = prs.parse_args()
if args.command == 'run':
run(prs,args)
... | StarcoderdataPython |
4850190 | <filename>tests/test_modules.py<gh_stars>0
import pytest
import torch
import pytorch_toolbelt.modules.encoders as E
from pytorch_toolbelt.modules.backbone.inceptionv4 import inceptionv4
from pytorch_toolbelt.modules.fpn import HFF
from pytorch_toolbelt.utils.torch_utils import maybe_cuda, count_parameters
skip_if_no_... | StarcoderdataPython |
6604616 | <reponame>vimofthevine/underbudget4
""" Integration tests for budget generator APIs """
from jsonpath_ng.ext import parse
from parameterized import parameterized
from underbudget.tests.base import BaseTestCase
class BudgetGeneratorsTestCase(BaseTestCase):
""" Integration tests for budget generator APIs """
... | StarcoderdataPython |
42879 | <reponame>JackLPK/MiniTCM<filename>minitcm/app.py<gh_stars>0
import sys
import toml
import wx
from minitcm import CONFIG_FP
from minitcm.mainframe import MainFrame
class MyApp(wx.App):
def OnInit(self):
#
try:
toml.load(CONFIG_FP)
except Exception as e:
print(f'Er... | StarcoderdataPython |
1815971 | <filename>wrappers/python/tests/ledger/test_build_node_request.py<gh_stars>100-1000
import json
import pytest
from indy import ledger, error
@pytest.mark.asyncio
async def test_build_node_request_works_for_missed_fields_in_data_json(did_trustee):
destination = "destination"
data = { }
with pytest.raises... | StarcoderdataPython |
1785328 | <gh_stars>0
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time : 2018/10/21 12:41
# @Author : <NAME>
# @Email : <EMAIL>
# @File : CompanyTyc.py
# @Software : PyCharm
# coding: utf-8
from XX.Model.SqlAlchemy.BaseModel import *
from sqlalchemy import Column, Integer, Index, String
from sqlalchemy.ext... | StarcoderdataPython |
1864182 | <reponame>al-arz/the-tale
import getpass
SERVICE_USER = getpass.getuser()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': SERVICE_USER,
'USER': SERVICE_USER,
'PASSWORD': SERVICE_USER,
'HOST': '',
'PORT': '',
}
}
TIME_ZONE... | StarcoderdataPython |
1884291 | import artm
import dill
import glob
import inspect
import json
import os
import pandas as pd
import pickle
import shutil
import warnings
from artm.wrapper.exceptions import ArtmException
from copy import deepcopy
from inspect import signature
from numbers import Number
from six import iteritems
from typing import (
... | StarcoderdataPython |
3565064 | # Copyright 2017-2021 object_database 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 ... | StarcoderdataPython |
1604637 | # coding=utf-8
"""
一些通用的小工具。
"""
import json
import os
from functools import partial
from pymel import core as pm
__author__ = '<NAME>'
__version__ = '0.01'
class Singleton(object):
"""
单例模式的基类,窗口类型的类都会继承这个类
"""
_instance = None
def __new__(cls, *args, **kw):
if cls._instance is None:... | StarcoderdataPython |
199651 | <reponame>alecperkins/fairdistrict
import pymongo
connection = pymongo.Connection()
db = connection.redistrict
def printCount(*args):
if len(args) > 0:
if args[0] % 1000 == 0:
print args[0]
else:
print
print db.districts.count(), 'districts'
print db.block... | StarcoderdataPython |
11292773 | '''
给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
进阶:
你能在线性时间复杂度内解决此题吗?
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 ... | StarcoderdataPython |
6548051 | from itertools import chain, count
INPUT_FILE = "../../input/11.txt"
STEPS = 100
HEIGHT = 10
WIDTH = 10
EnergyLevelGrid = list[list[int]]
def parse_input() -> EnergyLevelGrid:
"""
Parses the input and returns an EnergyLevelGrid
"""
with open(INPUT_FILE) as f:
return [[int(x) for x in line.st... | StarcoderdataPython |
6601281 | # 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
# "License"); you may not u... | StarcoderdataPython |
8079970 | <gh_stars>0
# Generated by Django 4.0.1 on 2022-01-21 07:50
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CO2_MM_MLO',
fields=[
('id', mo... | StarcoderdataPython |
9694958 | """
Writes MESS input for a molecule
"""
import os
import numpy
from ioformat import build_mako_str
from ioformat import indent
from ioformat import remove_trail_whitespace
from mess_io.writer import util
# OBTAIN THE PATH TO THE DIRECTORY CONTAINING THE TEMPLATES #
SRC_PATH = os.path.dirname(os.path.realpath(__file... | StarcoderdataPython |
1968225 | <gh_stars>10-100
# -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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
#
... | StarcoderdataPython |
319497 | from rest_framework.generics import (CreateAPIView, RetrieveUpdateAPIView,
RetrieveDestroyAPIView, ListAPIView
)
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from .models import GovermentListing
from .serializer import Go... | StarcoderdataPython |
4979190 | <filename>blebulb.py<gh_stars>10-100
import sys
if sys.version_info[0] > 2:
from tkinter import *
from tkinter.colorchooser import askcolor
else:
from Tkinter import *
from tkColorChooser import askcolor
import colorsys
import math, sys, time
from bledevice import scanble, BLEDevice
bulb = None
WRITE... | StarcoderdataPython |
6677398 | # Generated by Django 2.0.4 on 2018-07-11 21:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('members', '0009_auto_20180711_2149'),
]
operations = [
migrations.RemoveField(
model_name='quota',
name='amount',
... | StarcoderdataPython |
5182323 | <reponame>noemiacintia/Atividades-Python
'''A sequência de Fibonacci é uma das sequências de números bastante famosas. Ela inicia da seguinte forma:
1,1,2,3,5,8,13,21,...
Sendo que:
2 é a soma (1+1)
3 é a soma (1+2)
5 é a soma (2+3)
8 é a soma (3+5)
e assim por diante...
Construa um programa que gere uma sequên... | StarcoderdataPython |
3549117 | <gh_stars>1-10
from discord.ext import commands
from discord.ext.commands import Context
from discord.ext.commands.errors import CheckFailure
from app.services.logger import Logger
logger = Logger.generate_log()
def is_guild_owner():
def predicate(ctx: Context):
return ctx.guild is not None and ctx.guild... | StarcoderdataPython |
3598361 | import pickle
import errno
import pathlib
import sys
import datetime
import os
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
DEFAULT_NOTES_WHEN_MISSING_C... | StarcoderdataPython |
8079035 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 22 12:18:53 2020
@author: Taoufik.ELKHIRAOUI
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
from plotly.offline import plot
import math
import time
# Inputs
T, S0, p, u, d, k = 250... | StarcoderdataPython |
31108 | import scipy.stats as stat
import pandas as pd
import plotly.graph_objs as go
from hidrocomp.graphics.distribution_build import DistributionBuild
class GenPareto(DistributionBuild):
def __init__(self, title, shape, location, scale):
super().__init__(title, shape, location, scale)
def cumulative(se... | StarcoderdataPython |
1716311 | import torch
import torch.nn as nn
import torch.nn.functional as F
from time import time
import numpy as np
from torch.autograd import Function
import sys
import ctypes
lib=ctypes.cdll.LoadLibrary("/root/Pointnet_Pointnet2_pytorch/libmorton/encode.so")
lib.encode.restype=ctypes.c_uint64
def timeit(tag, t):
print(... | StarcoderdataPython |
3561403 | from discordbot.discordminigames.singleplayergames.singleplayergame import SinglePlayerGame, WON, LOST, QUIT
from discordbot.messagemanager import MessageManager
from discordbot.utils.emojis import STOP, COLORS as COLORS_EMOJI, ARROW_LEFT, CHECKMARK, REPEAT
from minigames.mastermind import Mastermind, COLORS
class Ma... | StarcoderdataPython |
207535 | """
VTGS Relay Daemon -- https://github.com/zleffke/cdh_sim
"""
__title__ = "CDH SIM"
__version__ = "0.0.0"
__author__ = "<NAME>, KJ4QLP"
__email__ = "<EMAIL>"
__desc__ = "VCC CDH Simulator"
__url__ = "vtgs.hume.vt.edu"
| StarcoderdataPython |
9631337 | <reponame>siddharthkul/F.Block
# This file is responsible for containing the
# a target hash to get to and modify the difficulty level (d(t)) according to the
# Authored by <NAME> and <NAME> November 18th, 2017
# Imports
import random
import string
# Ignore all Warnings for demo (Please comment out otherwise)
impor... | StarcoderdataPython |
11383012 | from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib import admin
from . import other_admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^other-admin/', include(other_admin.site.urls)),
]
| StarcoderdataPython |
1996406 | <reponame>toastwaffle/LiME
"""Proxy module to access all the database models."""
# pylint: disable=unused-import
# For brevity, we break with the convention of only importing modules.
from .setting import Setting
from .tag import Tag
from .tag_group import TagGroup
from .task import Task
from .user import User
| StarcoderdataPython |
12863026 | <reponame>marvincosmo/Python-Curso-em-Video
""" 67 - Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo
usuário. O programa será interrompido quando o número solicitado for negativo. """
while True:
n = int(input('Informe um número para ver sua tabuada: '))
i... | StarcoderdataPython |
11236456 | import json
class Params:
def __init__(self, path):
self.JsonFile = None
self.Read(path)
self.LogPath = self.GetVal('Log path')
self.CreateStructure = int(self.GetVal('Create Structure'))
self.Model = self.GetVal('Pretrained Model')... | StarcoderdataPython |
1692074 | <filename>tmp/python/update_posts.py
import os
files_in_directory = os.listdir('posts/')
for every_file in files_in_directory:
fin = open("posts/" + every_file)
fout = open("updated_posts/" + every_file, "wt")
line = fin.readlines()
line.pop(1)
line.pop(3)
line[0] = "---\n" + "toc: true \n... | StarcoderdataPython |
6701423 | # BSD 3-Clause License
#
# Copyright (c) <NAME> 2016,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of ... | StarcoderdataPython |
11270210 | <filename>helpers/pyband/tests/transaction_test.py
import requests
from pyband.client import Client
import pytest
from pyband import Transaction
from pyband.message import MsgRequest
from pyband.wallet import Address, PrivateKey
from pyband.client import Client
TEST_RPC = "https://api-mock.bandprotocol.com/rest/"
cl... | StarcoderdataPython |
1746809 | def f():
return f<ref>oo
foo = 1 | StarcoderdataPython |
3375585 | from nose2.tools import such
with such.A("system") as it:
@it.should("do something")
def test():
pass
it.createTests(globals())
| StarcoderdataPython |
1903078 | <reponame>korvec/microsex
from FUN.util import op_a_dec
def bloque_puntero_datos(punteros_anterior, registro_datos, desplazamiento, senal_control_PD):
IXR = punteros_anterior[0]
IYR = punteros_anterior[1]
PP = punteros_anterior[2]
habilitacion_IX = senal_control_PD[0]
habilitacion_IY = senal_cont... | StarcoderdataPython |
3351772 | import logging
from crawler.site_map import SiteMap
from crawler.links.link import Link
from crawler.pages.page_fetcher import PageFetcher
class Crawler:
"""Crawls the given domain
Attributes:
site_map: The site map of the crawled domain.
"""
site_map = None
def __init__(self, s... | StarcoderdataPython |
4874421 | """
面试题45:把数组排成最小的数
题目:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
例:
输入数组{3, 32, 321}, 打印321323。
"""
def sort_array_for_min_number(nums):
"""
:param nums: int list
:return: min number string
"""
from functools import cmp_to_key
# def cmp(a, b):
# return -1 if a + b < b + a else 1
... | StarcoderdataPython |
12801524 | <reponame>Toure/Rhea
__author__ = "<NAME>"
__license__ = "Apache License 2.0"
__version__ = "0.1"
__email__ = "<EMAIL>"
__status__ = "Alpha"
import pytest
def test_authentication():
pass
def test_user_creation():
pass
def test_tenant_creation():
pass
def test_project_creation():
pass
def test_... | StarcoderdataPython |
11219896 | <filename>authentication/tests/test_user_model.py
from django.test import TestCase
from authentication.models import User
# Create your tests here.
class UserModelTestCase(TestCase):
def setUp(self):
User.objects.create(email="<EMAIL>",
password="password")
User.objec... | StarcoderdataPython |
9762004 | <filename>policyiteration.py
from AldousBroder import AldousBroder
from AldousBroder import maze_to_mdp
import re
"""
<NAME>, <NAME>, <NAME>
"""
def policy_iteration(grid, gamma):
"""
Performs policy iteration on a given grid of MDPState objects.
"""
is_policy_changed = True
policy = [['... | StarcoderdataPython |
153008 | """
Routines for solving the KS equations via Numerov's method
"""
# standard libs
import os
import shutil
# external libs
import numpy as np
from scipy.sparse.linalg import eigsh, eigs
from scipy.linalg import eigh, eig
from joblib import Parallel, delayed, dump, load
# from staticKS import Orbitals
# internal lib... | StarcoderdataPython |
11212528 | <gh_stars>0
input = """409 194 207 470 178 454 235 333 511 103 474 293 525 372 408 428
4321 2786 6683 3921 265 262 6206 2207 5712 214 6750 2742 777 5297 3764 167
3536 2675 1298 1069 175 145 706 2614 4067 4377 146 134 1930 3850 213 4151
2169 1050 3705 2424 614 3253 222 3287 3340 2637 61 216 2894 247 3905 214
99 797 80 6... | StarcoderdataPython |
9671048 | import datetime as dt
from datetime import timedelta as td
from models import base_db_model
from utils import time_utils, database_utils
import discord
class Timer(base_db_model.BaseDBModel):
def __init__(self, userid: str, td_secs: int, msg: str, discord_message, include_seconds=True, start_time=None,
... | StarcoderdataPython |
138844 | import copy
import time
import json
import logging
log = logging.getLogger(__name__)
import torch
from optim import lbfgs_modified
import config as cfg
def store_checkpoint(checkpoint_file, state, optimizer, current_epoch, current_loss,\
verbosity=0):
r"""
:param checkpoint_file: target file
:param sta... | StarcoderdataPython |
208435 | <gh_stars>0
# SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributio... | StarcoderdataPython |
5125668 | <filename>lists/generate_imlist.py
import os
num_bgs_train = 100
num_bgs_test = 20
train_data_file = 'train.txt'
test_data_file = 'test.txt'
train_file = '/media/hao/DATA/Combined_Dataset/Training_set/training_fg_names.txt'
train_file_bg = '/media/hao/DATA/Combined_Dataset/Training_set/training_bg_names.txt'
test_fi... | StarcoderdataPython |
9781200 | <reponame>aristo-master/uzuwiki<gh_stars>0
import os
import json
from datetime import datetime
from django import forms
from commons.file import file_utils
from commons import wiki_conf_consts
from commons import page_conf_consts
from commons import file_name_tools
from logging import getLogger
logger = getLogger(__na... | StarcoderdataPython |
11357055 | <filename>simple-backend/nlpviewer_backend/urls.py
"""nlpviewer_backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL t... | StarcoderdataPython |
9660720 | import numpy as np
from whole_body_mpc_msgs.msg import StateFeedbackGain
import copy
class StateFeedbackGainInterface():
def __init__(self, nx, nu, frame_id="world"):
self._msg = StateFeedbackGain()
self._msg.header.frame_id = frame_id
self._msg.nx = nx
self._msg.nu = nu
se... | StarcoderdataPython |
4883958 | <filename>lib/dyson/utils/quotes.py
def is_quoted(data):
return len(data) > 1 and data[0] == data[-1] and data[0] in ('"', "'") and data[-2] != '\\'
def unquote(data):
""" removes first and last quotes from a string, if the string starts and ends with the same quotes """
if is_quoted(data):
retur... | StarcoderdataPython |
9724942 | #
# AggHelp.py -- help classes for the Agg drawing
#
# <NAME> (<EMAIL>)
#
# Copyright (c) <NAME>. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
import aggdraw as agg
from ginga import colors
class AggContext(object):
def __in... | StarcoderdataPython |
131601 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import theano
import theano.tensor as T
from .. import activations, initializations, regularizers, constraints
from ..utils.theano_utils import shared_zeros
from ..layers.core import Layer
class Convolution1D(Layer):
def __init__(self, input_dim, nb... | StarcoderdataPython |
12860410 | from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import io
import random
import numpy as np
def visualizationpreprocess(age,sex,cp,trestbps,restecg,chol,fbs,thalach,exang,oldpeak,slope,ca,thal,result):
if sex=="male":
sex=1
else: sex=0
... | StarcoderdataPython |
5094331 | <gh_stars>1-10
import numpy
import sys
import png
# TODO: figure out argparse
# CELL SPEC: [[0, 0, 'G', sys.maxsize, sys.maxsize, sys.maxsize, sys.maxsize]]
# ^ ^ ^ ^ ^ ^ ^
# address | | | | | |
# generati... | StarcoderdataPython |
5005053 | <gh_stars>1-10
import os
import argparse
import subprocess
import pytest
from .. import support
def setup_module(module):
test_dir = support.get_test_dir(__file__)
subprocess.run('cd {:} && make clean && make'.format(test_dir), shell=True)
@pytest.mark.parametrize('name', support.get_test_files(__file__))
d... | StarcoderdataPython |
11380505 | <reponame>KwabenaYeboah/Solved-python-programming-Challenges-Source-code
#This program converts a user string into morse code
#ALGORITHM in pseudocode
#The main function:
# 1.get a string from the user
# 2.morse code converter function accepts
# string an argurment
#The morse code converter function(string):
... | StarcoderdataPython |
8008932 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 10 22:00:13 2018
@author: <NAME>
"""
import os
import time
import shutil
import requests
import pandas as pd
from threading import Thread
from datetime import datetime
from bs4 import BeautifulSoup as bs
#export to csv ibovespa composition
def get_ibov():
now = datetim... | StarcoderdataPython |
1747972 | # coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
import re # noqa: F401
from typing import Any, Dict, List, Optional, Union, Literal # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator, Field, Extra # noqa: F401
from aries_cloudcontroller.m... | StarcoderdataPython |
271003 | """This submodule contains tools for creating svg files from paths and path
segments."""
# External dependencies:
from __future__ import division, absolute_import, print_function
from math import ceil
from os import getcwd, path as os_path, makedirs
from xml.dom.minidom import parse as md_xml_parse
from svgwrite impor... | StarcoderdataPython |
9798969 | <gh_stars>10-100
"""
This module is dedicated to noise models used in other methods.
Each noise class should implement the ``__call__`` method. See the examples :class:`EGreedyNoise` and :class:`OrnsteinUhlenbeckNoise`.
"""
import numpy as np
class EGreedyNoise:
"""This class implements simple e-greedy noise. The... | StarcoderdataPython |
3378877 | <reponame>elliotbonneville/fidesops<filename>src/fidesops/schemas/saas/strategy_configuration.py
from enum import Enum
from typing import Any, Dict, Optional, Union
from pydantic import BaseModel, validator, root_validator
class StrategyConfiguration(BaseModel):
"""Base class for strategy configuration"""
class... | StarcoderdataPython |
179077 | <filename>update.py
# April Fools Script
# By <NAME>
# I will not be held responsible for:
# any shenanigans
import os
import platform
import getpass
os.system("printf '\n\e[1;31;5;5m WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n'")
os.system("printf '\e[0;33;1;1m YOUR SYSTEM IS INFECTED.\n'")
os.sy... | StarcoderdataPython |
2339 | <reponame>Code-Master1234/Turtle_Flags_File_Hub<gh_stars>0
import turtle as t
def rectangle(horizontal, vertical, color):
t.pendown()
t.pensize(1)
t.color(color)
t.begin_fill()
for counter in range(2):
t.forward(horizontal)
t.right(90)
t.forward(vertical)
... | StarcoderdataPython |
6631770 | # -*- coding: utf-8 -*-
"""Classes wrapping ASGI requests in a nicer interface"""
import http.cookies
import re
from typing import Tuple
import urllib.parse
class FormDataError(Exception):
"""Represents an error handling form data"""
pass
class RequestData:
"""Simple object container for attaching data... | StarcoderdataPython |
55303 | #PLOTS
##################################################
#if(plot_opacity == True):
# p_plot = np.linspace(2.0,6.0,21)
# a_plot = np.logspace(np.log10(0.001),np.log10(10.),21)
#
# EXT_plot = EXT(a_plot,p_plot)
# ALB_plot = ALB(a_plot,p_plot)
#
# plt.close()
# fig = plt.figure()
# ax = fig.ad... | StarcoderdataPython |
1784781 | <gh_stars>1-10
import torch
import torch.nn as nn
from module.weight_init import *
class DenseNet_conv(nn.Module):
'''
doc
'''
def __init__(self, in_c, L=5, k=12, bn=False):
'''
dense block
:param in_c: input channel number
:param L: layer number in dense block
... | StarcoderdataPython |
378879 | ###################################################
#
# Script to launch the training
#
##################################################
from __future__ import print_function
import os, sys
from utils.help_functions import parse_config
import shutil
# config file to read from
if len(sys.argv) > 1:
config_file ... | StarcoderdataPython |
133228 | <filename>modules/extract_resnet_prelu.py
import torchvision
import torch
import torch.nn as nn
import torch.nn.functional as F
encode_out_r = []
def hook_r(module, input, output):
encode_out_r.append(output)
class deconvBlock(nn.Module):
def __init__(self, in_channels, out_channels,
kern... | StarcoderdataPython |
322950 | from picklable_itertools import iter_, chain
from fuel.datasets import Dataset
from fuel.utils.formats import open_
class TextFile(Dataset):
r"""Reads text files and numberizes them given a dictionary.
Parameters
----------
files : list of str
The names of the files in order which they shoul... | StarcoderdataPython |
9645737 | # -*- coding: utf-8 -*-
# Copyright 2014 Mirantis, 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 requi... | StarcoderdataPython |
5059777 | <filename>modules/keras_extensions/feature_extractor.py<gh_stars>1-10
from keras.applications.vgg19 import VGG19, preprocess_input
from keras.models import Model
from keras.layers import Lambda
import tensorflow as tf
import numpy as np
from colorama import Fore
def create_feature_extractor(input_shape:tuple, layers_t... | StarcoderdataPython |
85849 | <filename>doxyparser/compound/types/docsect3.py<gh_stars>0
#!/usr/bin/env python3
"""
Model representation of a docSect3Type from doxygen
<xsd:complexType name="docSect3Type" mixed="true">
<xsd:sequence>
<xsd:element name="title" type="xsd:string" />
<xsd:choice maxOccurs="unbounded">
<xsd:element name... | StarcoderdataPython |
8087336 | import numpy as np
class Point:
def __init__(self, x, y):
self.xy = np.array((x, y), dtype=np.float64)
def __eq__(self, other):
return np.allclose(self.xy, other.xy)
| StarcoderdataPython |
6609080 | #Saves boxplot for each cell type's length data as png
#Data generated in calculate_gc.py
#Exports #-cell-L-content-box-plot.png
import pandas as pd
import matplotlib.pyplot as plt
#Repeat for each DHS file
files = ['1','2','4','8']
data = []
for entry in files:
file_name = 'data/mm10_data/DHS_'+entry+'_lengths... | StarcoderdataPython |
6538403 | /home/runner/.cache/pip/pool/24/0e/c3/98877d359b6c8fa9e3f148d066e3f292d68b0934f7c07a3b8d67cf65ce | StarcoderdataPython |
9687592 | from . import downhill
| StarcoderdataPython |
4984704 | class Role(object):
def __init__ (self, role_name):
self.health = 0
self.mana - 0
self.weapon_slot = None
self.base_attack_bonus = 0
class Fighter(Role):
def __init__ (self):
super(Fighter, self).__init__()
self.health = 125
self.mana = 50
self.weapon_slot = IronShortSword()
self.base_attack_bonus ... | StarcoderdataPython |
5124814 | <filename>pydashlite/arrays/flatten.py
from typing import Iterable, TypeVar, List, Union
from ..tools import isIterable
V = TypeVar('V')
def flatten(array: Iterable[Union[V, Iterable[V]]]) -> List[V]:
return flattenDepth(array)
def flattenDeep(array: Iterable[Union[V, Iterable[V]]]) -> List[V]:
return fla... | StarcoderdataPython |
3532896 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
# @Project :GBN_Pro
# @File :ProHost1
# @Date :2021/6/3 13:19
# @Author :CuiChenxi
# @Email :<EMAIL>
# @Software :PyCharm
-------------------------------------------------
"""
import socket
import threading
import... | StarcoderdataPython |
11213621 | ############################################################################
# Original work Copyright 2017 Palantir Technologies, Inc. #
# Original work licensed under the MIT License. #
# See ThirdPartyNotices.txt in the project root for license information. #
# All modifi... | StarcoderdataPython |
6569328 | from pathlib import Path
import polyglot
_eval_limited = None
def get_eval_limited():
global _eval_limited
if _eval_limited is None:
path = Path(__file__).absolute()
eval_file = path.parent / "eval_limited.rb"
# Reading the file via polyglot does not work for whatever reason.
... | StarcoderdataPython |
369439 | <reponame>Szynal/Graph-Coloring-NIA<filename>src/brute_force_algorithm.py
from algorithm import Algorithm
from copy import deepcopy
from individual import Individual
from math import ceil, floor
from matplotlib import pyplot as plt
from pathlib import Path
from datetime import datetime
import random
from gui.console im... | StarcoderdataPython |
5127184 | # IMPORTS
from bs4 import BeautifulSoup
import requests
# CONSTANTS
SP500_list = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies#S&P_500_component_stocks'
def scrape_sp500_wikipedia():
sp500_page = requests.get(SP500_list).content
soup = BeautifulSoup(sp500_page, 'html.parser')
sp500_table = soup.fin... | StarcoderdataPython |
5161668 | #Recommender by item description
import os
from EDA import EDA
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer
class Recommender_By_Description:
def __init__(self):
#TODO: combine all columns into one ... | StarcoderdataPython |
84500 | <reponame>otimgren/chessdotcom-crawler<filename>crawlers/list_crawler.py
"""
This crawler goes through player profiles based on a list. Used to get new data for profiles that were
crawled through earlier.
"""
import sqlalchemy as sal
from sqlalchemy_utils import database_exists, create_database
from chess_crawler.cr... | StarcoderdataPython |
324511 | # https://edabit.com/challenge/Yj2Rew5XQYpu7Nosq
# Create a function that returns the number of frames shown in a given number of minutes for a certain FPS.
def frames(minutes: int, fps: int) -> int:
try:
total_frames = (minutes * 60) * fps
return total_frames
except TypeError as err:
... | StarcoderdataPython |
270209 | <gh_stars>0
_formats = {
'cic': [100, "CIrculant Columns"],
'cir': [101, "CIrculant Rows"],
'chb': [102, "Circulant Horizontal Blocks"],
'cvb': [103, "Circulant Vertical Blocks"],
'hsb': [104, "Horizontally Stacked Blocks"],
'vsb': [104, "Vertically Stacked Blocks"]
}
| StarcoderdataPython |
11278511 | # SPDX-FileCopyrightText: 2022 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: MIT
import datetime
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import timezone
from nfctokens.models import NFCToken, NFCTokenLog
class Command(BaseCommand):
help = ""
d... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.