id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3293752 | <filename>scripts/pegasus_check_clusters.py
#!/usr/bin/python
#
# Copyright (c) 2018, Xiaomi, Inc. All rights reserved.
# This source code is licensed under the Apache License Version 2.0, which
# can be found in the LICENSE file in the root directory of this source tree.
"""
Basic usage:
> vim ~/.bashrc
export PYTHO... | StarcoderdataPython |
148642 | #!/usr/bin/env python
#coding=utf-8
import urllib
import base64
import hmac
import time
from hashlib import sha1 as sha
import os
import sys
import md5
import StringIO
from threading import Thread
import threading
import ConfigParser
import logging
from logging.handlers import RotatingFileHandler
from xml.sax.saxutils ... | StarcoderdataPython |
3202361 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-03 13:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ApiKey'... | StarcoderdataPython |
1602356 | # Created by <NAME> - Intel Intelligent Systems Lab - 2020
import os
import tensorflow as tf
def checkpoint_cb (checkpoint_path, steps_per_epoch=-1, num_epochs=10):
# Create a callback that saves the model's weights every epochs
checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=os.pat... | StarcoderdataPython |
91641 | #
# Created by <NAME> on 05/02/2019.
#
from typing import List
import numpy as np
from numpy.random import RandomState
from sklearn.utils import resample
from phenotrex.util.logging import get_logger
from phenotrex.structure.records import TrainingRecord
class TrainingRecordResampler:
"""
Instantiates an ob... | StarcoderdataPython |
141477 | <reponame>kubanmar/similarity_threshold_clusterer
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="threshold_clusterer",
version="1.0",
author="<NAME>",
author_email="<EMAIL>",
description="A clustering method for small clusters in high ... | StarcoderdataPython |
1732921 | <filename>nf_common_source/code/services/dataframe_service/dataframe_helpers/dataframe_groupers.py
import pandas
from pandas.core.groupby import SeriesGroupBy
def group_and_sum_dataframe(
dataframe: pandas.DataFrame,
grouped_by_column_names_list: list,
column_to_sum_name: str,
result... | StarcoderdataPython |
3355969 | # Generated by Django 2.2.13 on 2020-08-23 13:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rescuemap', '0012_auto_20191106_2239'),
]
operations = [
migrations.AlterField(
model_name='rescueteam',
name='phon... | StarcoderdataPython |
42717 | <reponame>projectweekend/3spot
import json
from time import sleep
from boto import sqs
from boto.dynamodb2.table import Table
from boto.dynamodb2.exceptions import ConditionalCheckFailedException
from worker import config
from worker.models import Account
from worker.logs import get_logger
LOGGER = get_logger()
FEED_... | StarcoderdataPython |
3379525 | <reponame>BLUECARVIN/RL_baseline
import numpy as np
from utils.memory import SimpleMemoryBuffer
import gym
import torch
def train(env, args):
if args.memory == 'simple':
ram = SimpleMemoryBuffer(args.memory_max_size, args)
if args.agent == 'DDPG':
from DDPG import DDPG_Agent
agent = DDPG_Agent.DDPGAgent(env.... | StarcoderdataPython |
3375647 | <filename>python/071-080/Edit Distance.py
class Solution:
# @param {string} word1
# @param {string} word2
# @return {integer}
def minDistance(self, word1, word2):
n,m = len(word1), len(word2)
p = [[0]*(m+1) for _ in range(n+1)]
for i in range(1, n+1):
p[i][0]... | StarcoderdataPython |
4818134 | import time
t0t=time.time()
from os.path import join
import os
import numpy as n
import glob
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as p
import astropy.io.fits as fits
from scipy.interpolate import interp1d
from scipy.stats import norm as gaussD
plate = sys.argv[1]
mjd =... | StarcoderdataPython |
17067 | <gh_stars>10-100
import numpy as np
import pytest
from numpy.testing import assert_allclose
from numpy.testing import assert_array_equal
from sklearn.ensemble._hist_gradient_boosting.histogram import (
_build_histogram_naive,
_build_histogram,
_build_histogram_no_hessian,
_build_histogram_root_no_hess... | StarcoderdataPython |
1702527 | <reponame>ndevelder/amr-wind-channel-les<filename>submods/amrex/Tools/Release/ppCleanup.py
#!/usr/bin/env python
import os
import shutil
import sys
import getopt
import re
def ppCleanup(cwfile, infile, oufile):
try:
f = open(cwfile)
except IOError:
print "ERROR: ", cwfile, " doesn't appear to... | StarcoderdataPython |
1776045 |
import string, urlparse, httplib, urllib, random
import datetime, threading, sys, time, collections
AllShortcodes = [
('http://10.130.32.52:58080/driver-container/incomingMessages/USSybase1/sms', [90001], ['Hello', 'Ciao', 'Hola', 'Salut']),
('http://10.130.32.52:58080/driver-container/incomingMessages/USSyba... | StarcoderdataPython |
3236983 | import pickle
def make_pickle(a, b, c):
"""
Creates a new Python pickle with a, b, and c.
"""
with open('output_pickle.pickle', 'wb') as f:
pickle.dump({'a': a, 'b': b, 'c': c}, f, pickle.HIGHEST_PROTOCOL)
| StarcoderdataPython |
3205968 | <gh_stars>1-10
import sys
s = 12345
s = str(s)[::-1]
print("%d bit nums" % len(s))
for i in range(len(s)):
sys.stdout.write(s[i] + " ")
| StarcoderdataPython |
1761455 | # Runtime: 36 ms
# Beats 99.62% of Python submissions
class Solution:
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
ret_arr = []
for word in words:
map1 = {}
... | StarcoderdataPython |
6808 | from __future__ import annotations
from typing import Optional, Dict, List, Union, Type, TYPE_CHECKING
from datetime import date, datetime
import pandas as pd
import numpy as np
import re
import locale
try:
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
except locale.Error:
# Readthedocs has a problem, but dif... | StarcoderdataPython |
3347601 | <gh_stars>0
from django.test import TestCase
from .models import Question
import datetime
from django.utils import timezone
from django.urls import reverse
# Create your tests here.
class Question_model_test(TestCase):
def test_was_recent(self) :
future = timezone.now() + datetime.timedelta(days = 1)
... | StarcoderdataPython |
4819430 | from django.contrib import admin
from .models import EventType, Event, Rsvp
admin.site.register(EventType)
admin.site.register(Event)
admin.site.register(Rsvp)
| StarcoderdataPython |
3258307 | <reponame>JustinDPerkins/flask<filename>s3_app/__init__.py
from flask import Flask, render_template, request, redirect
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config.from_object("s3_app.config")
from .helpers import *
@app.route("/")
def index():
return render_template("index.html")
... | StarcoderdataPython |
4815899 | from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
# 20191028
from . import login_manager, db
# 20191108
from flask import current_app, request, url_for
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
class User(UserMixin, obj... | StarcoderdataPython |
1789416 | <filename>fline/utils/logging/trains.py<gh_stars>1-10
from trains import Task, Logger
import typing as tp
from fline.utils.logging.base import BaseLogger, EnumLogDataTypes
from fline.utils.data.image.convert import convert_tensor_image_to_numpy
class TrainsLogger(BaseLogger):
def __init__(
self,
... | StarcoderdataPython |
4837459 | from pathlib import Path
from gc3_query.lib.export_delegates.mongodb import storage_adapter_init
# fixme? from gc3_query.lib.open_api import API_SPECS_DIR
TEST_BASE_DIR: Path = Path(__file__).parent
# config_dir = TEST_BASE_DIR.joinpath("config")
config_dir = gc3_cfg.BASE_DIR.joinpath("etc/config")
def test_setup()... | StarcoderdataPython |
198743 | # Copyright 2020 SURF.
# 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, ... | StarcoderdataPython |
1645727 | from abc import abstractmethod
from datetime import datetime
import json
from math import ceil
from typing import List, Optional, Union, Dict
from urllib.parse import quote
from slacktastic.exceptions import ValidationError
from slacktastic.constants import (
BASE_URL,
BACKGROUND_COLOR_DEFAULTS,
FOOD_LABEL... | StarcoderdataPython |
3224589 | <reponame>Lilykos/scoap3-next
# -*- coding: utf-8 -*-
#
# This file is part of SCOAP3.
# Copyright (C) 2018 CERN.
#
# SCOAP3 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
... | StarcoderdataPython |
37997 | from .terminal import write, no_cursor
from .screen import Screen
__all__ = ["write", "no_cursor", "Screen"]
__version__ = "0.5.0"
| StarcoderdataPython |
3275125 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""
The plotting module contains various classes to generate typical SymEnergy
output plots. Data update callbacks are implemented in JavaScript. This allows
for interactive standalone plots, suited for Jupyter Notebooks.
Plots are arranged in 2D arrays. The two dimensio... | StarcoderdataPython |
1675570 | import discord, time, asyncio, os, random, json, requests
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, cooldown, MissingPermissions, check, has_role
from discord.utils import get
from termcolor import colored
class App(commands.Cog):
def __init__(self, client):
... | StarcoderdataPython |
3220127 | <gh_stars>1-10
CREATE_TABLES = """
DROP TABLE IF EXISTS staging_yellow_trips;
CREATE TABLE IF NOT EXISTS staging_yellow_trips (
VendorID INT,
tpep_pickup_datetime TIMESTAMP,
tpep_dropoff_datetime TIMESTAMP,
passenger_count INT,
trip_distance FLOAT,
RatecodeID INT,
store_and_fwd_flag TEXT,
PULocationID INT,
... | StarcoderdataPython |
3370975 | <reponame>Jbrunn/python-highcharts<filename>examples/highcharts/column-placement.py
# -*- coding: utf-8 -*-
"""
Highcharts Demos
Fixed placement columns: http://www.highcharts.com/demo/column-placement
"""
import datetime
from highcharts import Highchart
H = Highchart(width=850, height=400)
options = {
'chart': {
... | StarcoderdataPython |
1644550 | #!/usr/bin/env python
# This script post process the snt file -- either in single-line format or in multi-line format
# The output, however, will always be in single-line format
from sys import *
from optparse import OptionParser
import re;
usage = """
The script post process the snt file, the input could be single-l... | StarcoderdataPython |
108396 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
database audit hooks module.
"""
import pyrin.database.audit.services as database_audit_services
from pyrin.audit.decorators import audit_hook
from pyrin.audit.hooks import AuditHookBase
@audit_hook()
class AuditHook(AuditHookBase):
"""
audit hook class.
"""
... | StarcoderdataPython |
5992 | class Player:
def __init__(self, nickname, vapor_id, player_id, ip):
self.nickname = nickname
self.vapor_id = vapor_id
self.player_id = player_id
self.ip = ip
self.not_joined = True
self.loads_map = True
self.joined_after_change_map = True
class Players:
... | StarcoderdataPython |
3215101 | <gh_stars>0
class MultiplePlayersFoundException(Exception):
pass
| StarcoderdataPython |
1742208 | import os,shutil
import pypospack.utils
from pypospack.pyposmat.data import PyposmatConfigurationFile
from pypospack.pyposmat.data import PyposmatDataFile
from pypospack.pyposmat.visualization import Pyposmat2DDensityPlot
data_directory = os.path.join(
pypospack.utils.get_pypospack_root_directory(),
'd... | StarcoderdataPython |
4828172 | <filename>tower.py<gh_stars>0
import urllib
import requests
import socketio
from threading import Thread
from time import sleep
import PySimpleGUI as sg
from Methods import Method, Extent
class Tower:
def __init__(self, tower_id, gui):
self.tower_id = tower_id
self._gui = gui
self._load_tower_info(to... | StarcoderdataPython |
141068 | <reponame>Saad-K/snowflake-connector-python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2019 Snowflake Computing Inc. All right reserved.
#
from snowflake.connector.util_text import construct_hostname
def test_construct_hostname_basic():
assert construct_hostname('eu-central-1', 'account... | StarcoderdataPython |
1636142 | <reponame>zx273983653/vulscan
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2014-2015 pocsuite developers (http://seebug.org)
See the file 'docs/COPYING' for copying permission
"""
#命令行
from pocsuite import pocsuite_cli
#验证模块
from pocsuite import pocsuite_verify
#攻击模块
from pocsuite import pocsuite_at... | StarcoderdataPython |
3203591 | <gh_stars>1-10
""" Production Settings """
import json
import os
import dj_database_url
from django.core.exceptions import ImproperlyConfigured
from .dev import *
with open(os.path.join(BASE_DIR, 'secrets.json')) as secrets_file:
secrets = json.load(secrets_file)
def get_secret(setting, secrets=secrets):
"... | StarcoderdataPython |
1618621 | <reponame>jonclothcat/OpenPype
import os
import attr
import getpass
import pyblish.api
from avalon import api
from openpype.lib import env_value_to_bool
from openpype_modules.deadline import abstract_submit_deadline
from openpype_modules.deadline.abstract_submit_deadline import DeadlineJobInfo
@attr.s
class Deadlin... | StarcoderdataPython |
1652144 | <reponame>leo-gerv/discord-img-bot
import discord
from img.utils import arr_to_bytesIO
import tasks
import numpy as np
import img
async def run_code(message, in_img):
""" Runs the code in a runner if possible
Returns a tuple (success, result)
"""
success, result, errmsg = await tasks.run(messag... | StarcoderdataPython |
1678633 | # Original Link: https://github.com/kuangliu/pytorch-cifar/
# Original Author: <NAME>
# Original License: MIT
# Adapted to support Model quantization
'''MobileNetV2 in PyTorch.
See the paper "Inverted Residuals and Linear Bottlenecks:
Mobile Networks for Classification, Detection and Segmentation" for more details.
'... | StarcoderdataPython |
3363512 | <reponame>gabriel-venezian/napp-academy<gh_stars>0
import csv
from datetime import date, datetime
def carregar_arquivo_para_lista(nome_arquivo):
"""
Função recebe o nome de um arquivo csv e retorna a lista
de tuplas com
Args:
nome_arquivo (string): Nome do arquivo CSV
... | StarcoderdataPython |
1675840 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
try:
basestring
except NameError:
basestring = str
from compas_rhino.forms.base import BaseForm
import clr
from System.Drawing import Size
from System.Drawing import Point
from System.Drawing import C... | StarcoderdataPython |
1726677 | <filename>sqsgenerator/core/structure.py<gh_stars>10-100
import numbers
import itertools
import numpy as np
import typing as T
from operator import attrgetter as attr
from sqsgenerator.core.core import Structure as Structure_, Atom
class Structure(Structure_):
"""
Structure class used to store structural info... | StarcoderdataPython |
4818307 | <reponame>JunboLu/CP2K_kit
#! /usr/env/bin python
import psutil
import subprocess
from CP2K_kit.tools import log_info
from subprocess import check_call, Popen, STDOUT, CalledProcessError
def call_simple_shell(exe_dir, cmd):
'''
call_simple_shell: call shell scripts, and we do not need returns.
Args:
exe_d... | StarcoderdataPython |
3279327 | <filename>machin/frame/algorithms/utils.py
from machin.utils.logging import default_logger
from machin.model.nets.base import static_module_wrapper
import inspect
import torch
import torch.nn as nn
def soft_update(target_net: nn.Module, source_net: nn.Module, update_rate) -> None:
"""
Soft update target netwo... | StarcoderdataPython |
120881 | """
Reads in current year's Arctic sea ice extent from Sea Ice Index 2 (NSIDC)
Website : ftp://sidads.colorado.edu/DATASETS/NOAA/G02135/north/daily/data/
Author : <NAME>
Date : 5 September 2016
"""
### Import modules
import numpy as np
import datetime
import matplotlib.pyplot as plt
from mpl_toolkits.basema... | StarcoderdataPython |
1617392 | <reponame>ezequielwish/Python3
# Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário.
# No final, mostre o conteúdo da estrutura na tela.
dict_ = {'name': str(input('Nome: '))}
dict_['average'] = float(input(f'Média de {dict_["name"]}: '))
if dict_['average'] < 5:
dict_... | StarcoderdataPython |
3278754 | while True:
n = int(input())
if n == 0:
break
L = []
for i in range(n):
a = input()
L.append([a,a.upper()])
L.sort(key = lambda t : t[1])
print(L[0][0]) | StarcoderdataPython |
3335966 | # This file contains the functions needed for solving the Stokes system.
from params import rho_i,g,tol,B,rm2,rho_w,C,eps_p,eps_v,dt,quad_degree,Lngth,sigma_0,Hght,dim
from boundary_conds import mark_boundary,apply_bcs
from geometry import bed,s_mean0,lake_vol_0
from hydrology import Vdot
import numpy as np
from dolfi... | StarcoderdataPython |
3244337 | import os
import numpy as np
import math
import cv2
from scipy import ndimage
import time
label1= np.load('/mnt/sda1/downloads/BlazePose-tensorflow-master/data_configs_aic/aic_pre_cropped_17_single.npy')
file_name = np.load('/mnt/sda1/downloads/BlazePose-tensorflow-master/data_configs_aic/files_aic_pre_cropped_17_sing... | StarcoderdataPython |
1646112 | <reponame>tum-lkn/appaware<filename>clients/control/utils/iface_statistics/redis_pusher.py<gh_stars>0
import redis
import threading
import json
import logging
log = logging.getLogger(__name__)
class RedisPusher(threading.Thread):
def __init__(self, redis_ip: str, redis_port: int):
threading.Thread.__ini... | StarcoderdataPython |
1717362 | <reponame>boscp/aws-ops-wheel
# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.... | StarcoderdataPython |
12651 | from pathlib import Path
import logging
from .logger import Logger
from .log_formatter import LogFormatter
class FileLogger(Logger):
fmt = LogFormatter(use_colour=False, output_ts=False)
logger = None
def __init__(self, folder, format=None):
if format is None:
format = ("%(asctime)s|... | StarcoderdataPython |
1696872 | <reponame>locuslab/robust-nn-control
import torch
import torch.nn as nn
from torch.autograd import Function
import operator
from functools import reduce
import cvxpy as cp
from qpth.qp import QPFunction
from cvxpylayers.torch import CvxpyLayer
from sqrtm import sqrtm
import warnings
from constants import *
class MBP... | StarcoderdataPython |
3550 | import os
from pymongo import MongoClient
from dotenv import load_dotenv
def database_entry(data):
try:
load_dotenv()
mongo_string = os.getenv('MONGODB_AUTH_URI')
client = MongoClient(mongo_string)
database = client[os.getenv('MONGODB_DB')]
col = database['users']
c... | StarcoderdataPython |
1627203 | import requests
import sw_utilities as utils
from sw_entities import Planet, INT_PROPS, LIST_PROPS
# LECTURE 23 Exercise
# Objectives
# 1. Write list comprehensions
# 2. Write dictionary comprehensions
# 3. Work with class instances
# 3. Work with custom modules
# CONSTANTS
ENDPOINT = 'https://swapi.py4e.com/api'
... | StarcoderdataPython |
3332772 | from django.contrib import admin
# Register your models here.
from msgvis.apps.enhance import models
admin.site.register(models.Dictionary)
admin.site.register(models.Word)
admin.site.register(models.TopicModel)
admin.site.register(models.Topic)
admin.site.register(models.TopicWord)
admin.site.register(models.Message... | StarcoderdataPython |
199283 | <reponame>sambitpadhy567/CouchDB
# 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, ... | StarcoderdataPython |
3312260 | # -*- coding: utf-8 -*-
import sys
from odmltables import VERSION
from setuptools import setup
long_description = open("README.rst").read()
install_requires = ['xlrd >= 0.9.4',
'xlwt >= 1.0.0',
'numpy >= 1.8.2',
'quantities >= 0.10.1',
'... | StarcoderdataPython |
132257 | import datetime
import time
from time import mktime
from dateutil import parser
import feedparser
d = feedparser.parse('https://www.varzesh3.com/rss/all')
from DB.db_handler import update_last_check, get_all_rss
# d = feedparser.parse('http://www.irinn.ir/fa/rss/allnews')
rss = get_all_rss()[0]
entries = d.entries
e... | StarcoderdataPython |
3359947 | <reponame>HackRU/teamRU
from src.flaskapp.db import coll
from src.flaskapp.util import aggregate_team_meta
def team_confirm(email, team1_id, team2_id): # if request.method == 'POST'
"""Confirming an invitation from a team (i.e. team1 -confirms-> team2)
team1 is the team which is receiving and confirming the... | StarcoderdataPython |
167363 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root: return []
result = []
... | StarcoderdataPython |
3345013 | from sympy import *
from rodrigues_R_utils import *
x_1, y_1, z_1 = symbols('x_1 y_1 z_1')
px_1, py_1, pz_1 = symbols('px_1 py_1 pz_1')
sx_1, sy_1, sz_1 = symbols('sx_1 sy_1 sz_1')
x_2, y_2, z_2 = symbols('x_2 y_2 z_2')
px_2, py_2, pz_2 = symbols('px_2 py_2 pz_2')
sx_2, sy_2, sz_2 = symbols('sx_2 sy_2 sz_2')
scale = s... | StarcoderdataPython |
3285888 | # <NAME>
# <EMAIL>
from polynomial2d.polynomial2d import Polynomial2D
class ComputeSIP:
'''
ComputeSIP compute SIP given (x1,x2) as xyref, and coef2d from ConfReader. Note: x1 is the leading term in SIP.
Polynomial2D is used (pip install polynomial2d).
Use method compress() to compute the 1D coefficie... | StarcoderdataPython |
3386153 | <reponame>ouyang-w-19/decogo
# MINLP written by GAMS Convert at 04/21/18 13:52:37
#
# Equation counts
# Total E G L N X C B
# 250 125 27 98 0 0 0 0
#
# Variable counts
# x b i... | StarcoderdataPython |
1786287 | <reponame>cool-RR/grid_royale
# Copyright 2020 <NAME> and collaborators.
# This program is distributed under the MIT license.
from __future__ import annotations
import random
import weakref
import concurrent.futures
import numbers
import functools
import collections.abc
from typing import (Iterable, Union, Optional, ... | StarcoderdataPython |
61201 | # Copyright 2020 (c) Aalto University - All Rights Reserved
# ELEC-E8125 - Reinforcement Learning Course
# AALTO UNIVERSITY
#
#############################################################
import numpy as np
from time import sleep
from sailing import SailingGridworld
epsilon = 10e-4 # TODO: Use this criteria for Tas... | StarcoderdataPython |
1624021 | <gh_stars>0
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 <NAME> and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# 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... | StarcoderdataPython |
1667409 | <gh_stars>0
from config.settings.config_common import \
PANDAMA_DOMAIN, PANDAMA_PDP_PREURL, \
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_STORAGE_BUCKET_NAME, \
CHROMEDRIVER_PATH, GOOGLE_CHROME_BIN
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome im... | StarcoderdataPython |
3396455 | from nonebot import on_notice, NoticeSession, on_request, RequestSession
from nonebot.message import unescape
import cq
@on_notice("group_increase")
async def hello(session: NoticeSession):
await session.send(unescape(cq.at(session.event.user_id) + " 欢迎新人入群👏!"))
await session.bot.send_private_msg(
us... | StarcoderdataPython |
94093 | <filename>gliffyToDrawIO.py
#!/usr/bin/env python3
import json
import string
import random
import argparse
from bs4 import BeautifulSoup
draw_obj_keys = {'x': 1, 'y': 1,
'rotation': 1, 'id': 1,
'width': 1, 'height': 1,
'uid': 1, 'order': 1,
'lockAspectRatio': 1, 'lockShape': 1,
'constraints'... | StarcoderdataPython |
3287614 | <filename>merlin/util/registration.py
from typing import Tuple
from sklearn.neighbors import NearestNeighbors
from skimage import transform
import numpy as np
from scipy import signal
def extract_control_points(
referencePoints: np.ndarray, movingPoints: np.ndarray,
gridSpacing: float=0.5) -> Tuple[np... | StarcoderdataPython |
3261745 | #!/usr/bin/env python3
# vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# The piwheels project
# Copyright (c) 2017 <NAME> <https://github.com/bennuttall>
# Copyright (c) 2017 <NAME> <<EMAIL>>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the follow... | StarcoderdataPython |
115761 | from chatlib import (
__version__ as version,
__author__ as author
)
from setuptools import setup
from pathlib import Path
readme_path = Path(__file__).parent.joinpath("README.md")
with open(readme_path) as f:
readme_contents = f.read()
setup(
name="pychatlib",
version=version,
description="Pr... | StarcoderdataPython |
84483 | from mudes.app.mudes_app import MUDESApp
# app = HateSpansApp("multilingual-large", use_cuda=False)
# print(app.predict_hate_spans("ගෝඨාභය පොන්නයා විවාදෙට එන්නේ නැත්තේ ඇයි දන්නවා ද?", spans=True, language="xx"))
#
# tokens = app.predict_tokens("ගෝඨාභය පොන්නයා විවාදෙට එන්නේ නැත්තේ ඇයි දන්නවා ද?", language="xx")
# for t... | StarcoderdataPython |
3299623 | from .. import RiohConstants, parse_images
def parse_images_from_env(env):
return parse_images(env['wsgi.input'].read(int(env['CONTENT_LENGTH'])), env['CONTENT_TYPE'])
def is_rioh_request(env):
return (env['REQUEST_METHOD'] == 'POST' or env['REQUEST_METHOD'] == 'PUT') and \
env['CONTENT_TYPE'].st... | StarcoderdataPython |
1606067 | from django.views.generic import CreateView
from .forms import SampleModelForm
from .models import SampleModel
class SampleModelCreate(CreateView):
model = SampleModel
form_class = SampleModelForm
| StarcoderdataPython |
3349684 | <reponame>ziporah/goodwe
import logging
from typing import Union
from .exceptions import RequestRejectedException
logger = logging.getLogger(__name__)
MODBUS_READ_CMD: int = 0x3
MODBUS_WRITE_CMD: int = 0x6
MODBUS_WRITE_MULTI_CMD: int = 0x10
FAILURE_CODES = {
1: "ILLEGAL FUNCTION",
2: "ILLEGAL DATA ADDRESS",... | StarcoderdataPython |
160018 | from rest_framework import serializers
from account.models import Account
class RegistrationSerializer(serializers.ModelSerializer):
password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
class Meta:
model = Account
fields = ['email', 'username', 'password', '<PA... | StarcoderdataPython |
1607077 | <filename>main.py
from mlist import MLista
def main():
while True:
try:
capacity = int(input(" Podaj początkowy rozmiar listy "))
lista = MLista(capacity)
if capacity >= 0:
break
except ValueError:
print('Mozna wpisac tylko Integers')... | StarcoderdataPython |
1668353 | <reponame>lozaeric/icpc_undav
v = int(input())
g = v*0.08
print("{0:.2f}".format(g))
| StarcoderdataPython |
109900 | <reponame>dieloz/fooof
"""
Dealing with Line Noise
=======================
This example covers strategies for dealing with line noise.
"""
###################################################################################################
# sphinx_gallery_thumbnail_number = 2
# Import the spectral parameterization ... | StarcoderdataPython |
1697019 | from typing import (
AnyStr,
List,
)
import pytest
from botblox_config.cli import create_parser
from pytest import CaptureFixture
from ..conftest import assert_ip175g_command_is_correct_type, get_data_from_cli_args, run_command_to_error
class TestSetRxMode:
package: List[str] = ['botblox']
base_args... | StarcoderdataPython |
3376015 | <filename>src/Chapter10/Exercise1.py<gh_stars>0
"""
Exercise 1
Revise a previous program as follows: Read and parse the "From" lines and
pull out the addresses from the line. Count the number of messages from
each person using a dictionary.
After all the data has been read print the person with the most commits by
cr... | StarcoderdataPython |
1756233 | <gh_stars>0
import click
import os
import subprocess
import sys
from augur.runtime import pass_application
from augur.util import logger
@click.group('util', short_help='Miscellaneous utilities')
def cli():
pass
@cli.command('shell', short_help='Drop into a shell')
@pass_application
def shell(app):
app.shell(... | StarcoderdataPython |
3232299 | <filename>PostList.py
from Post import Post as P
from paths import BASE_PATH
import user
import usercollection
import RequestList
import datetime
import json
class PostList:
def __init__(self):
self.LPost= {}
def insert(self,post):
self.LPost[post.id] = post
def print(self,user):
... | StarcoderdataPython |
1677626 | <gh_stars>1-10
"""
This script is an example of how to use the L1 optimization reconstruction
module (regularized regression scheme). |br|
Firstly, a multitone signal is generated. The signal model is as follows.
There are two random tones randomly distributed in the spectrum
from 11kHz to 20kHz and two random tones... | StarcoderdataPython |
1674074 | # Copyright (c) 2021, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... | StarcoderdataPython |
4816922 | from random import randint
computador = randint(0,5)
print('-=-'*20)
print('Vou pensar em um número entre 0 e 5. Tente adivinhar')
print('-=-'*20)
jogador = int(input('Em que numero pensei? '))#jogador tenta adivinhar
if jogador == computador:
print('Parabens, me venceu')
else:
print('Ganhei, eu pensei no {} e nao ... | StarcoderdataPython |
69249 | from django.contrib.auth.models import User
from django.test import Client, TestCase
from django.urls import reverse
class WebpageTest(TestCase):
def setUp(self):
self.client = Client()
User.objects.create_user('temporary', '<EMAIL>', 'temporary')
def test_webpage(self):
rv = self.cl... | StarcoderdataPython |
3364483 | <reponame>tuix/tutorials<gh_stars>1-10
import grpc
from timeit import default_timer as timer
import logging
# import the generated classes
import model_pb2
import model_pb2_grpc
port = 8061
def run(text):
logging.basicConfig()
print("Calling HPP_Stub..")
with grpc.insecure_channel('localhost:{}'.format(... | StarcoderdataPython |
100454 | class Solution:
def isNumber(self, s: str) -> bool:
return re.compile('^[+-]?(\.\d+|\d+\.?\d*)([eE][+-]?\d+)?$').match(s.strip()) is not None | StarcoderdataPython |
1637028 | <gh_stars>10-100
# !/usr/bin/env python
# encoding: utf-8
#
# This file is part of ckanext-nhm
# Created by the Natural History Museum in London, UK
from collections import OrderedDict
from datetime import datetime
import ckan.model as model
from ckan.lib.search import make_connection
from ckan.plugins import toolkit
... | StarcoderdataPython |
188467 | <reponame>jham20x6/turbo-octo-broccoli
'''
Created on Feb 14, 2021
@author: jeff
This test runs through a slightly larger set of input, reading from file.
The main purpose here is handling more than just the 2 actions given in the default input.
'''
import simplejson as json
import unittest
from action_tracker.Tracker... | StarcoderdataPython |
1655214 | """
I have added this section, without learning OOP this is the way that we can
show how to use global and local variables.
Updating global variables in this way will lead into using OOP instance variables and methods.
Subroutines that return a value are called functions
They use the key word return
Follow the key word... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.