id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
47373 | from pyntcloud import PyntCloud
import pyembree
import numpy as np
import trimesh
from trimesh import sample, ray, triangles
from trimesh.ray.ray_pyembree import RayMeshIntersector
import pandas as pd
cloud = PyntCloud.from_file("/home/mjia/Documents/ShapeCompletion/test.ply")
sample = cloud.get_sample(name='mesh_ran... | StarcoderdataPython |
15382 | import os
# from signal import pause
from gpiozero import Button
from datetime import datetime
def take_screen():
screen_btn = Button(2)
while True:
if screen_btn.is_pressed:
timestamp = datetime.now()
cmd = "scrot -u d 5 $n {}.png".format('screen_' + str(timestamp))
... | StarcoderdataPython |
3238012 | <reponame>tilleyd/compy<filename>compy/image/__init__.py
"""The image module contains various functions to work with images."""
from . import alter
from . import errors
from . import filter
from . import generate
from . import io
from . import metrics
| StarcoderdataPython |
1739541 | #!/usr/bin/python
import cookielib
import urllib
import urllib2
import time
import json
import sys
login_url = 'https://access.ripe.net'
udm_url = 'https://atlas.ripe.net/atlas/udm.html'
data_url = 'https://atlas.ripe.net/atlas/udmgrid.json'
cookie_filename = '/tmp/ripeatlas.cookie'
result_url = 'https://atlas.ripe.ne... | StarcoderdataPython |
185373 | <filename>allauth/socialaccount/providers/snapchat/tests.py
from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase
from .provider import SnapchatProvider
class SnapchatOAuth2Tests(OAuth2TestsMixin, TestCase):
provider_id = SnapchatProvider.id
def get_mock... | StarcoderdataPython |
1744756 | from __future__ import absolute_import, division, print_function
import six
import logging
import os
import json
import numpy as np
import torch
from madminer.utils.ml import ratio_losses, flow_losses
from madminer.utils.ml.models.maf import ConditionalMaskedAutoregressiveFlow
from madminer.utils.ml.models.maf_mog im... | StarcoderdataPython |
177909 | class CloudWatchEvent:
def __init__(self,
schedule_expression: str,
is_active: bool,
name: str =None):
self.name = name
self.schedule_expression = schedule_expression
self.is_active = is_active
| StarcoderdataPython |
155025 | <gh_stars>0
def restart():
prompt = input("Type [y] to play again or any other key to quit. ")
if prompt.lower() == "y":
return True
else:
return False
| StarcoderdataPython |
1678615 | from .ENV import *
from .DJANGO import *
from .GRAPPELLI import *
| StarcoderdataPython |
1765106 | <filename>splitter.py
import argparse
from pydub import AudioSegment
from pydub.silence import split_on_silence
# https://docs.python.org/ja/3/howto/argparse.html
# https://www.pydoc.io/pypi/pydub-0.9.5/autoapi/silence/index.html
parser = argparse.ArgumentParser()
parser.add_argument("-in", "--input_file", ty... | StarcoderdataPython |
3307061 | import numpy as np
from plugin.seg import (
remove_outliers,
helper_object_points,
max_min,
prepare_data,
list_of_objects,
)
from plugin.kde_seg import prep_obj_data
from plugin.encode import input_nn, flat_input
from plugin.projections import prespective_project
# Function for pred the input
def ... | StarcoderdataPython |
1746740 | """empty message
Revision ID: 942ab33b9e92
Revises: <PASSWORD>
Create Date: 2019-01-04 18:05:51.874866
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '942ab33b9e92'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### ... | StarcoderdataPython |
167961 | <reponame>xeddmc/pastebin-django<gh_stars>10-100
from pygments.formatters import HtmlFormatter
class ListHtmlFormatter(HtmlFormatter):
"""
Wraps the code inside an <ol> element and each individual line around a <li> element,
giving us both free line numbers and better behavior with line wrapping.
... | StarcoderdataPython |
3281721 | import os
import logging
import pandas as pd
import numpy as np
import urllib.request
import requests
import re
import io
import zipfile
import json
from pyseir import OUTPUT_DIR
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data')
def load_zip_get_file(url, file, decoder='utf-8'):
... | StarcoderdataPython |
147998 | <filename>aiovkbot/handlers.py
import re
import json
import asyncio
import logging
from functools import wraps
from aiovkbot.errors import (PermissionDeniedError,
InvalidCommandError,
NotMatchPattern)
def rename(name):
def decorator(func):
def wrapper(*args, **kwar... | StarcoderdataPython |
3238971 | <filename>spopt/BaseClass.py
from abc import ABC, abstractmethod
class BaseSpOptSolver(ABC):
"""Base class for all spatial optimization model solvers.
"""
@abstractmethod
def solve(self):
"""Solve the optimization model."""
pass
class BaseSpOptExactSolver(BaseSpOptSol... | StarcoderdataPython |
165925 | from collections import defaultdict
class Graph:
def __init__(self,V,directed=False):
self.V = V
self.directed = directed
self.graph = defaultdict(list)
def add_edge(self,a,b):
self.graph[a].append(b)
if not self.directed:
self.graph[b].append(a)
def color_greedy(self):
result = [-1]*self.V
... | StarcoderdataPython |
3280538 | import argparse
import timeit
import toml
from time import sleep
from datetime import datetime as dt
from downloader import RedditorDownloader
def main():
__version__ = toml.load("pyproject.toml")["tool"]["poetry"]["version"]
default_dir = "./redditor-downloader/downloads"
parser = argparse.ArgumentPar... | StarcoderdataPython |
3366504 | <filename>dcd_onlyS.py
#!/usr/bin/env python
#vim:fileencoding=UTF-8
from cafysis.file_io.dcd import DcdFile
import copy
import sys
if len(sys.argv) != 4:
print('Usage: SCRIPT [input DCD] [last index of RNA (count from 0)] [output DCD]')
sys.exit(2)
last_mp = int(sys.argv[2])
dcd = DcdFile(sys.argv[1])
dcd.... | StarcoderdataPython |
3224606 | # flake8: noqa
from elastalert.loaders.rules_loader import RulesLoader
from elastalert.loaders.file_rules_loader import FileRulesLoader
# Used to map the names of rule loaders to their classes
loader_mapping = {"file": FileRulesLoader}
| StarcoderdataPython |
3294476 | #!/usr/bin/env python3
"""
Tetris for Python / Tkinter
<NAME>
https://github.com/olemb/tetris/
http://tetris.wikia.com/wiki/Tetris_Guideline
"""
import random
from dataclasses import dataclass, replace
import tkinter
shapes = {
# See README.md for format.
'O': ['56a9', '6a95', 'a956', '956a'],
'I': ['45... | StarcoderdataPython |
1620248 | <filename>book_scraper_selectolax.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# script by <NAME>
# released under MIT License
# github.com/RuchirChawdhry/Python
# ruchirchawdhry.com
# linkedin.com/in/RuchirChawdhry
from selectolax.parser import HTMLParser
import urllib.request
import re
from more_itertools impo... | StarcoderdataPython |
1723535 | <reponame>saurabh896/python-1
from PIL import Image,ImageDraw,ImageFont
im = Image.open("pic.jpg")
x,y = im.size
font = ImageFont.truetype("verdana.ttf", x/3)
dr = ImageDraw.Draw(im)
dr.text((3*x/4,0),font=font,text="4",fill="#FF0000")
im.save("pictuer_has_number.jpg")
| StarcoderdataPython |
199624 | <gh_stars>1-10
'''
Simple Cam Test - BGR and Gray
Create by pythonprogramming.net ==> See the tutorial here:
https://pythonprogramming.net/loading-video-python-opencv-tutorial
Adapted by <NAME> - MJRoBot.org @8Feb18
'''
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret, frame = ca... | StarcoderdataPython |
4833568 | <gh_stars>100-1000
# Copyright (c) Lawrence Livermore National Security, LLC and other Conduit
# Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
# other details. No copyright assignment is required to contribute to Conduit.
"""
file: t_conduit_docs_tutorial_python_examples.py
"""
import sy... | StarcoderdataPython |
45129 | # © 2020 [<NAME>](mailto:<EMAIL>)
import html
import logging
from xeda.utils import try_convert
from xml.etree import ElementTree
from ..flow import Flow, DebugLevel
from functools import reduce
logger = logging.getLogger()
def supported_vivado_generic(k, v, sim):
if sim:
return True
if isinstance(v,... | StarcoderdataPython |
3339179 | <reponame>starius/gohere
#!/usr/bin/env python
""" Install Go into a local directory. """
import argparse
import errno
import hashlib
import logging
import os
import platform
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import textwrap
try:
import urllib2
except:
# Pytho... | StarcoderdataPython |
41012 | <filename>src/openpersonen/setup.py
"""
Bootstrap the environment.
Load the secrets from the .env file and store them in the environment, so
they are available for Django settings initialization.
.. warning::
do NOT import anything Django related here, as this file needs to be loaded
before Django is initial... | StarcoderdataPython |
3329464 | import numpy as np
# Zwicker and Fastl weighting function
x = np.array(
[
0.0985854,
14.826764,
15.364039,
15.863559,
16.297388,
16.533346,
16.844551,
17.052244,
17.335314,
17.599474,
17.816587,
18.014925,
18.23... | StarcoderdataPython |
3394644 | import aergo.herapy as herapy
def test_tx(aergo) -> None:
print("------ Set Sender Account -----------")
sender_private_key = \
"<KEY>"
sender_account = aergo.new_account(private_key=sender_private_key)
print(" > Sender Address: {}".format(sender_account.address))
aergo.get_account()
... | StarcoderdataPython |
4802374 | from custom.devices.PSI.java.abstract.java_device import JavaDevice
from math import log10
class PBR(JavaDevice):
def __init__(self, config: dict):
super(PBR, self).__init__(config, "custom/devices/PSI/java/lib/config/device_PBR.config")
self.interpreter = {
"1": self.get_temp_settings... | StarcoderdataPython |
1796639 | <reponame>crrapi/Zane
import os
import datetime
import traceback
import asyncio
import asyncpg
import sys
try:
import uvloop
except ImportError:
if sys.platform == "win32":
pass
elif sys.platform == "linux":
print(
"""UvLoop is not installed. Please install it with "pip install ... | StarcoderdataPython |
178647 | <reponame>dskrypa/tz_aware_dt<filename>tz_aware_dt/__init__.py
from importlib import import_module
__attr_module_map = {
# tz_aware_dt
'TZ_LOCAL': 'tz_aware_dt',
'TZ_UTC': 'tz_aware_dt',
'ISO8601': 'tz_aware_dt',
'DATETIME_FMT': 'tz_aware_dt',
'DATE_FMT': 'tz_aware_dt',
'TIME_FMT': 'tz_awar... | StarcoderdataPython |
3295146 | from .controller_factory import ControllerFactory
from .feedforward_controller import FeedforwardController
from .ffgru_controller import FFGRUStateTuple, FFGRUController
from .gru_controller import GRUStateTuple, GRUController
from .lstm_controller import LSTMStateTuple, LSTMController
from .rnn_controller import RNNS... | StarcoderdataPython |
177266 | <reponame>AGH-Narzedzia-Informatyczne/dobblethon
# #
# Dobblethon Core v0.1.1 #
# #
##############################
#
# range(a,b) -> <a, b-1>
# randint(a,b) -> <a, b>
#
# Constants can't be freely edited, specific relations between the values n... | StarcoderdataPython |
182606 | # -*- coding: utf-8 -*-
"""
Created on Mon May 27 22:05:19 2019
@author: <NAME>
"""
import pandas as pd
from keras.layers import Input, TimeDistributed, Bidirectional, Conv2D, BatchNormalization, MaxPooling2D, Flatten, LSTM, Dense, Lambda, GRU, Activation, Dropout
from keras import applications
from keras... | StarcoderdataPython |
45774 | from menu import Menu
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
coffee_maker = CoffeeMaker()
money_machine = MoneyMachine()
menu = Menu()
def coffee_machine():
while True:
choose = input(f'What would you like: ({menu.get_items()})').lower()
if choose == 'report'... | StarcoderdataPython |
90543 | #Crie um programa que escreva "Ol<NAME>!" na tela.
print('Ol<NAME>!')
| StarcoderdataPython |
1687430 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: <NAME> 刘祥德
@license: (C) Copyright 2019-now, Node Supply Chain Manager Corporation Limited.
@contact: <EMAIL>
@software:
@file: sort.py
@time: 2019/12/21 13:41
@version 1.0
@desc:
"""
import os
import json
import cv2
from pathlib import Path
import numpy as np
def... | StarcoderdataPython |
77216 |
import numpy as np
import cv2
import os
def render(img_rgb):
img_rgb = cv2.resize(img_rgb, (500,500))
numDownSamples = 2 # number of downscaling steps
numBilateralFilters = 50 # number of bilateral filtering steps
# -- STEP 1 --
# downsample image using Gaussian pyramid
img_color =... | StarcoderdataPython |
4838152 | <gh_stars>0
#coding:utf-8
__author__ = '<NAME>'
__date__ = '2017/6/16 14:35'
from random import Random
from django.core.mail import send_mail
from users.models import EmailVerifyRecord
from MOOC.settings import EMAIL_FROM
def random_str(randomlength=8):
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUu... | StarcoderdataPython |
3227946 | import sys
import hydra
import torch
from omegaconf.listconfig import ListConfig
import logging
from pathlib import Path
log = logging.getLogger(__name__)
# https://github.com/pytorch/examples/blob/8df8e747857261ea481e0b2492413d52bf7cc3a8/imagenet/main.py#L363
class AverageMeter(object):
"""Computes and stores ... | StarcoderdataPython |
3239762 | """Programa para GERAR AFND, AFD, ELIMINAR MORTOS E INALCANÇÁVEIS
Criado por <NAME>
Modificado por <NAME>
Ciencias da Computação - UFFS"""
import os
import sys
import string
so = sys.platform # Pega qual é o SO
so_clear = ''
if (so == 'linux'): ... | StarcoderdataPython |
1771072 | <reponame>pedroxian/jeriko-source
#python 2.7.15
print "Hello, Dcoder!"
many.print ai.c ++mi sata:data mmz.r
roots.ror ai.c t.rm retry.banking item.2
pillows.cat pullcase.firsthand
mull.time extend.lord -war.zones
py.item class.erlang it.far
away.from.home
class.1 6.memories call.dawn | StarcoderdataPython |
3256277 | # Copyright 2016 - Nokia
#
# 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, sof... | StarcoderdataPython |
138253 | #!/usr/bin/env python
'''
<NAME> - Jan 2016
This script configures the sysadmin user and configures domain0
Will come back and properly throw this with logging, etc
'''
VERSION="v.2.3.005"
CONTENTDIR="/u02/app/content"
import getopt
import logging
from os.path import basename
import signal
import sys
import time
impor... | StarcoderdataPython |
1709033 | <reponame>G00dBye/YYMS<filename>scripts/portal/portal_002.py
# Limbert's General Store (913070000) - continue script
# Constants
NEINHEART = 1106003
CYGNUS = 1106001
JAAH = 1106005
MOB = 9001050
# Script answer init
sm.removeEscapeButton()
sm.setSpeakerID(JAAH)
sm.setPlayerAsSpeaker()
# Actions
sm.forcedInput(0)
sm.... | StarcoderdataPython |
1646516 | <filename>data_structures/_queue.py
from node import Node
class _Queue(object):
"""
Queue is a classic data structure built upon Node. It follows the FIFO rule, such that
the first element in shall be the first one out. Like a queue in line.
"""
def __init__(self, iterable=[]):
self.front ... | StarcoderdataPython |
1728415 | from src.boson import Boson
from os import path
import pickle as pc
import dynet as dy
import numpy as np
import json
dir='/home/lnn/Documents/OpenNRE-Ina/OpenNRE-PyTorch/mnre_data'
print("Loading model from {}...".format('/home/lnn/Downloads/minimal-span-parser-master/models/top-down-model_dev=87.21'))
model = dy.Par... | StarcoderdataPython |
3291248 | import base64
import binascii
import logging
from typing import Optional, NamedTuple, Dict
PermaLink = NamedTuple(
"PermaLink",
[
("model_name", Optional[str]),
("request_data", Dict),
("model_id", Optional[str]),
("task_name", Optional[str]),
],
)
def int_to_slug(i: int) ... | StarcoderdataPython |
3253407 | <gh_stars>0
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import redirect
from store.models import Ticket, Review
from ticket.already_commented import already_commented
@login_required
def update_review(request):
"""
Create or upda... | StarcoderdataPython |
53290 | <reponame>Marshellson/UGA_IMF
prenom = input("Votre prenom svp ")
langue = input("Votre langue: ") # Langue devait etre "francais" ou "anglais"
if langue == "francais":
print("Bonjour %s" % prenom)
elif langue == "anglais":
print("Hello %s" % prenom)
else:
print("ERREUR")
| StarcoderdataPython |
3226256 | import json
import subprocess
import os
PROFILE_FILE = 'profile.json'
SOURCES_ID_FILE = 'sources_id.json'
DESTS_ID_FILE = 'dests_id.json'
FRONTEND_FIXTURES_FILE = 'frontend_fixtures.json'
FLOW_REQUEST_DATA_FILE = 'flow_requests_data_{}.json'
CONSENT_CONFIRM_FILE = 'consent_confirmation_data_{}.json'
ENDPOINTS_FILE = ... | StarcoderdataPython |
1682438 | #irods configuration
IRODS = {
'openid_microservice':'',
}
#In back-end services, None. In Front-end, list of back-end API base path
#BACKEND=["https://<site>"]
BACKEND=None
| StarcoderdataPython |
1610468 | <filename>TrainInfoProcess/utils/info.py
'''
@date: 2021-07-30
@author: ZhuYing-CSU
@description:
该文件中所有变量仅用于对DataFrame中的车站数据进行处理
以下是各个变量的说明:
originStations: 题目所给的csv数据中,出现的所有站点名称
stations: 对相邻站点(或同地区站点)进行合并后,线路下行方向站点名称
substitutions: 上述合并操作时所用的字典,用于替换站点名
nearestStation: 在生成列车开行方... | StarcoderdataPython |
3310579 | """
Code to perform simulations of the Ising model on a three block
SBM with chain-like structure.
Opposing external fields are on the two end blocks.
<NAME>, Sep 2019.
"""
#Python functions:
import pandas as pd
import numpy as np
import networkx as nx
from tqdm import tqdm as tqdm
#My own functions:
from ising_b... | StarcoderdataPython |
143041 | <reponame>statgen/locuszoom-hosted<filename>locuszoom_plotting_service/users/adapters.py
from typing import Any
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.conf import settings
from django.core.exceptions import ValidationE... | StarcoderdataPython |
1766611 | <reponame>DavidBarcenas/django-photosgram
from django.urls import path
from users.views import SignupView, UpdateProfileView, login_view, logout_view, UserDetailView
urlpatterns = [
path('login/', login_view, name="login"),
path('logout/', logout_view, name="logout"),
path('signup/', SignupView.as_view(),... | StarcoderdataPython |
1619739 | #!/usr/bin/python
"""This file contains code for use with "Think Bayes",
by <NAME>, available from greenteapress.com
Copyright 2013 <NAME>
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
1, Original link -
refer to https://github.com/AllenDowney/ThinkBayes/blob/master/code/redline_data.py
2, As http://devel... | StarcoderdataPython |
74589 | <filename>mnist/main.py
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from zoo.pipeline.api.net.torch_net import TorchNet
from zoo.pipeline.api.net.torch_criterion import T... | StarcoderdataPython |
37436 | <reponame>StudentCV/TableSoccerCV
#Copyright 2016 StudentCV
#Copyright and related rights are licensed under the
#Solderpad Hardware License, Version 0.51 (the “License”);
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at http://solderpad.org/licenses/SHL-0.51.
#... | StarcoderdataPython |
3213207 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# API calls to interact with Google Big Query
# TODO:
# - Build in push date overlap to handle late-reported data
from __future__ import absolute_import
from datetime import datetime, timedelta, time
from services.gservice import GoogleServiceFetcher
from constants import JO... | StarcoderdataPython |
3250988 | <gh_stars>10-100
from icedata.datasets.biwi.data import *
from icedata.datasets.biwi.parser import *
from icedata.datasets.biwi.dataset import *
| StarcoderdataPython |
3297337 | <gh_stars>10-100
#Importing flask
from flask import Flask, render_template
app = Flask(__name__)
#URL to be specified
#http://127.0.0.1:5000/
@app.route('/')
def hello_world():
return 'Hello, World!'
#http://127.0.0.1:5000/about
@app.route('/about')
def about_flask():
return render_template(... | StarcoderdataPython |
36536 | <gh_stars>0
import os
import sys
here = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(here, '..', '..', '..', 'test_utils'))
from fixtures import event, lambda_context
| StarcoderdataPython |
3352822 | <reponame>gianhiltbrunner/sbb-cli
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import urllib.parse
import urllib.request
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--from', help='Departure station', required=True)
parser.add_argument('-t', '--to', help='Arrival statio... | StarcoderdataPython |
75161 | # Copyright (c) 2021 SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
"""
Created on 2021-01-05 09:38
@author: johannes
"""
from abc import ABC
import pandas as pd
class Frame(pd.DataFrame, ABC):
"""
Stores data from one... | StarcoderdataPython |
97894 | import requests
from bs4 import BeautifulSoup
import re
import pandas
import csv
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
page_no = 1
restaurant_reviews =[]
for page in range(0, 813):
print(page_no)
re... | StarcoderdataPython |
145060 | import sys
from phonemizer import phonemize
backend='espeak'
lang=sys.argv[1]
if lang=="en":
lang="en-us"
elif lang=="fr":
lang="fr-fr"
#for line in sys.stdin:
# print(phonemize(line, language=lang, backend=backend))
# try:
# print(phonemize(line, language=lang, backend=backend))
# except:
# ... | StarcoderdataPython |
1662124 | from .shared import compute_stats
__all__ = ["compute_stats"]
| StarcoderdataPython |
3217488 | <gh_stars>10-100
"""Example that represents the activity related CSV files of the fitbit dataset published on Zenodo
"""
import os
import pandas as pd
from tasrif.data_readers.zenodo_fitbit_dataset import ZenodoFitbitDataset
from tasrif.processing_pipeline import ComposeOperator, NoopOperator, SequenceOperator
from t... | StarcoderdataPython |
3382288 | # GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... | StarcoderdataPython |
6198 | <reponame>HARPLab/inquire
"""
An agent which uses demonstrations and preferences.
Code adapted from Learning Reward Functions
by Integrating Human Demonstrations and Preferences.
"""
import itertools
import os
import time
from pathlib import Path
from typing import Dict, List
import arviz as az
from inquire.agents.a... | StarcoderdataPython |
192598 | import itertools
import numpy as np
import sys
from collections import defaultdict, namedtuple
#Credit:
#https://github.com/dennybritz/reinforcement-learning
EpisodeStats = namedtuple("Stats",["episode_lengths", "episode_rewards"])
def make_epsilon_greedy_policy(Q, epsilon, decay, nA):
"""
Creates an epsilon... | StarcoderdataPython |
3269904 | <filename>1h_NGL_3D_Viewer/pyscripts/pdbmapper/PdbParser.py
'''
pdbparser.py - <NAME> - 6/1/2017
Parse local or external (PDB Database) 3D structure files (.pdb, .cif)
Usage:
parser = PdbParser("2128-1.pdb").pdb_processing()
output: [['L', 'DIQ...'], ['H', 'EVQL...']]
'''
import os
from Bio.PDB import... | StarcoderdataPython |
47704 | <gh_stars>0
from sqlalchemy import Column, Date, Integer, String, Float
from database import Base
class Currency(Base):
__tablename__ = "currency"
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String)
abbreviated = Column(String)
dolar_quotation = Column(Float)
dat... | StarcoderdataPython |
171151 | <filename>copy_weights.py
import tensorflow as tf
class WeightCopier:
def __init__(self,q,target_q):
params_q = tf.trainable_variables(scope=q.weight_scope)
params_target = tf.trainable_variables(scope=target_q.weight_scope)
updates = []
for v1,v2 in zip(sorted(params_q, key=lambda v: v.name),sorted(param... | StarcoderdataPython |
1762362 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-05-24 22:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('activityinfo', '0087_auto_20190524_1401'),
]
oper... | StarcoderdataPython |
3287909 | <reponame>johnnewto/FLIR-pubsub
# import the necessary packages
from threading import Thread
import cv2, time
from FLIR_pubsub.FLIR_client_utils import *
class Flir_VideoStream:
""" Maintain live FLIRCam feed without buffering. """
def __init__(self, src=0, name="FlirVideoStream", verbose = False):
"""
src... | StarcoderdataPython |
3303784 | <reponame>amihaita/uie<gh_stars>0
import sqlite3
import time
import datetime
import random
conn = sqlite3.connect('tutorial.db')
c = conn.cursor()
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL, datestamp TEXT, keyword TEXT, value REAL)")
def data_entry():
c.execute("INSERT... | StarcoderdataPython |
178810 | from .vtn_effnet import VTN
from .options import VTNOptions
class VTNBuilder:
def __new__(cls, *args, **kwargs):
opt = VTNOptions(*args, **kwargs)
return VTN(opt)
| StarcoderdataPython |
3667 | """ TextRNN model configuration """
class TextRNNConfig(object):
def __init__(
self,
vocab_size=30000,
pretrained_embedding=None,
embedding_matrix=None,
embedding_dim=300,
embedding_dropout=0.3,
lstm_hidden_size=128,
output_dim=1,
**kwargs
... | StarcoderdataPython |
3240141 | from time import sleep
from pytest_bdd import scenarios, when, then, given, parsers
from pages.login_page import LoginPage
from pages.secure_page import SecurePage
#Scenario
scenarios('../features/heruko.feature')
# Shared Given Steps
@given('open the login page')
def open_page(browser):
login_page = LoginPage(bro... | StarcoderdataPython |
1748739 | import copy
import mock
import pytest
from datadog_checks import aerospike
from . import common
pytestmark = pytest.mark.unit
METRICS = [
'aerospike.datacenter.dc_timelag',
'aerospike.datacenter.dc_rec_ship_attempts',
'aerospike.datacenter.dc_delete_ship_attempts',
'aerospike.datacenter.dc_remote_s... | StarcoderdataPython |
4816235 | <gh_stars>1-10
from itertools import islice
from typing import Any, List, Protocol
class LedgerClient(Protocol):
def apdu_exchange(self, INS: int, data: bytes, P1: int, P2: int) -> bytes:
...
def chunk(seq: bytes, size: int) -> List[bytes]:
it = iter(seq)
chunks = list(iter(lambda: tuple(islice(... | StarcoderdataPython |
72355 | <gh_stars>10-100
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.IndexView.as_view(), name="vendor-home"),
# Authentication
path('login', views.LoginView.as_view(), name="vendor-login"),
path('logout', views.LogoutView.as_view()... | StarcoderdataPython |
3305594 | import numpy as np
import graphClasses as gc
import copy
# INPUT HERE what level precarpet would you like?
precarpet_level = 2
# building the level 0 cross carpet
sC0 = gc.Graph()
sC0.add_vertex("a", np.array([0, 0.5]))
sC0.add_vertex("b", np.array([0.5, 1]))
sC0.add_vertex("c", np.array([1, 0.5]))
sC0.add_vertex("d... | StarcoderdataPython |
3274664 | <reponame>dataloop-ai/dtlpy
#! /usr/bin/env python3
# This file is part of DTLPY.
#
# DTLPY is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... | StarcoderdataPython |
1622217 | <filename>find-object-from-mask.py
import cv2
# Mask values of the object to be detected
min_blue=91
min_green=21
min_red=49
max_blue=111
max_green=255
max_red=255
# file path of the video in which we want to find object
video_path = './data/cup.mov'
camera = cv2.VideoCapture(video_path)
if not camera.isOpened... | StarcoderdataPython |
1736838 | <gh_stars>0
import functools
import os
from summarize_from_feedback.sample import main, HParams
from summarize_from_feedback.query_response_model import ModelSpec, SampleHParams, RunParams
from summarize_from_feedback.tasks import TaskHParams, TaskQueryHParams, TaskResponseHParams
print("Hi")
# SUBREDDIT: r/{subreddi... | StarcoderdataPython |
3335208 | #!/usr/bin/env python3
"""
Testing simple arithmetic FHE operations using the Python Frontend.
"""
from pyabc import *
import logging
def test_simple_arithmetic():
p = ABCProgram(logging.DEBUG)
with ABCContext(p, logging.DEBUG):
def main(a : NonSecretInt, x = 3):
b = (2 * 6) / x
... | StarcoderdataPython |
3271565 | <reponame>faraazkhan/aws-control-tower-customizations<filename>source/yorm/tests/test_types_standard.py
# pylint: disable=missing-docstring,unused-variable,expression-not-assigned
import pytest
from expecter import expect
from yorm.types import Object, String, Integer, Float, Boolean
def describe_object():
obj... | StarcoderdataPython |
1739790 | from discord import Embed
from discord.ext.commands import Context
from discord.ext import commands
from core.cls import Bot
from difflib import get_close_matches as gcm
class ErrorHandler(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_e... | StarcoderdataPython |
1673084 | """
The MIT License (MIT)
Copyright (c) 2021 lucaso60
Copyright (c) 2015-present Rapptz
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
... | StarcoderdataPython |
1704735 | <gh_stars>1-10
"""BitMEX API Connector."""
import requests
from time import sleep
import json
from . import errors
import math
import uuid
from .accessTokenAuth import AccessTokenAuth
from .apiKeyAuthWithExpires import APIKeyAuthWithExpires
# https://www.bitmex.com/api/explorer/
class BitMEX(object):
"""BitMEX A... | StarcoderdataPython |
96161 | <gh_stars>0
from ml_privacy_meter.utils import optimizers
from ml_privacy_meter.utils import losses
from ml_privacy_meter.utils import logger
from ml_privacy_meter.utils import attack_data
from ml_privacy_meter.utils import attack_utils | StarcoderdataPython |
3268872 | <reponame>DazEB2/SimplePyScripts<filename>Crypto Git Repository/create_local_repo.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
if __name__ == '__main__':
import api
repo = api.repo
print('Repo:', repo)
print()
api.print_log()
| StarcoderdataPython |
1754445 | from django.conf.urls.defaults import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^events/$', views.list, name='events.list'),
)
| StarcoderdataPython |
1627544 | <gh_stars>0
from collections import defaultdict
import pickle
import math
import os
import time
#import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from dcgan import DCGANGenerator64x64, SDDCGANDiscriminator64x64
from util import str2bool, decode_png_observation, encode_png_observatio... | StarcoderdataPython |
3340028 | # -*- coding: utf-8 -*-
"""
Copyright (c) 2017, <NAME>.
Distributed under the terms of the GPL v3 License.
The full license is in the file LICENSE, distributed with this software.
Created on Mar 13, 2018
@author: jrm
"""
import os
import time
import tempfile
from os.path import join, exists
from atom.atom import se... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.