id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1746097 | import torch
import math
from Net import ActorCritic
from Utils import buffer
class PPOAgent():
def __init__(self, state_dim, action_dim, gamma, std, eps_clip, kepoch, lr, device):
self.gamma = gamma
self.std = std
self.eps_clip = eps_clip
self.kepoch = kepoch
self.device = ... | StarcoderdataPython |
1763320 | <reponame>cybrnode/zkt-sdk-rest-api
from typing import List
from fastapi import websockets
from fastapi.testclient import TestClient
from app.main import app
from pyzkaccess.data import User
client = TestClient(app)
class TestIDKWHATTOCALLTHISCLASS:
TEST_DEVICE_IP = "192.168.10.201"
def setup(self):
... | StarcoderdataPython |
3245752 | <reponame>jonepatr/lets_face_it<filename>code/glow_pytorch/glow/modules.py
import numpy as np
import scipy.linalg
import torch
import torch.nn as nn
import torch.nn.functional as F
from glow_pytorch.glow import thops
class ActNorm2d(nn.Module):
"""
Activation Normalization
Initialize the bias and scale w... | StarcoderdataPython |
28691 | <gh_stars>0
from infra.controllers.contracts import HttpResponse
class NotFoundError(HttpResponse):
def __init__(self, message) -> None:
status_code = 404
self.message = message
body = {
'message': self.message
}
super().__init__(body, status_code)
| StarcoderdataPython |
157727 | <filename>xpdf_python/debug.py
from wrapper import *
if __name__ == '__main__':
if len(sys.argv) > 1:
pdf_loc = sys.argv[1]
else:
pdf_loc = '/path/to/pdf'
test = to_text(pdf_loc)
print(test) | StarcoderdataPython |
198041 | import skimage
from skimage.measure import label, regionprops
import matplotlib.pyplot as plt
import cv2
import numpy as np
import os
from imageio import imwrite
# following previous labeling method
lesion_class_label = 0
def convert(warped_mask):
bboxes = []
if warped_mask.max() == 1:
mask_contour, ... | StarcoderdataPython |
124453 | import logging
from django.conf import settings
from django.contrib import messages
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.http import HttpResponseRedirect
from django.template.loader import render_to_string
from django.utils.encoding import smart_text
from django.con... | StarcoderdataPython |
4833703 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Usage: forever.py command args
"""
import sys
import time
import subprocess
def main():
try:
cmd = ' '.join(sys.argv[1:])
i = 1
while True:
print '=== Iteration {} ==='.format(i)
status = subprocess.call(cmd, she... | StarcoderdataPython |
3270743 | <reponame>rraval/velocity-bingo
import random
from writer import Safe, runWriter, latex_escape
def writeMain(phrases, pages):
yield Safe(r'''
\documentclass[11pt]{article}
\usepackage[margin=0.25in,landscape]{geometry}
\usepackage{fontspec}
\usepackage{polyglossia}
\usepack... | StarcoderdataPython |
134325 | <reponame>AurelienGasser/substra-backend
import os
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.throttling import AnonRateThrottle
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from libs.expiry_token_authentication import token_expire_... | StarcoderdataPython |
3361406 | <reponame>RensDimmendaal/scikit-lego
import inspect
import numpy as np
from scipy.optimize import minimize_scalar
from sklearn.base import BaseEstimator, ClassifierMixin, OutlierMixin
from sklearn.mixture import GaussianMixture
from sklearn.utils import check_X_y
from sklearn.utils.multiclass import unique_labels
fro... | StarcoderdataPython |
84895 | #!/usr/bin/env python
import numpy as np
from tqdm import tqdm
from astropy.constants import G as Ggrav
from .low_level_utils import fast_dist
G = Ggrav.to('kpc Msun**-1 km**2 s**-2').value
def all_profiles(bins, positions, velocities, masses, two_dimensional=False, zcut=None,
ages=None, pbar_msg=... | StarcoderdataPython |
1612996 | from __future__ import division
'''
***********************************************************
File: softmaxModels.py
Allows for the creation, and use of Softmax functions
Version 1.3.0: Added Discretization function
Version 1.3.1: Added Likelihood weighted Importance sampling
**********************************... | StarcoderdataPython |
4823791 | <gh_stars>1-10
from .utils import Atom, Residue, ActiveSite
import numpy as np
import pandas as pd
from sklearn.metrics import jaccard_similarity_score
from .k_means import *
from .agglomerative import *
aa3 = "ALA CYS ASP GLU PHE GLY HIS ILE LYS LEU MET ASN PRO GLN ARG SER THR VAL TRP TYR".split()
def compute_simila... | StarcoderdataPython |
141588 | <filename>tests/test_options.py
# SPDX-License-Identifier: Apache-2.0
"""
Tests topology.
"""
import unittest
import numpy
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn import datasets
from skl2onnx import to_onnx, update_registered_converter
from skl2onnx.algebra.onnx_ops import OnnxIdentity, ... | StarcoderdataPython |
169690 | <gh_stars>1-10
"""
Script to calculate the surface area of gridded data.
The output from this script is used when summing up total precipitation and
total area of precipitation
Created: Oct 2016
Author: <NAME> <EMAIL>
"""
import os, errno
from netCDF4 import Dataset
import netCDF4
import numpy as np
import datetime a... | StarcoderdataPython |
1706266 | # Collaborators (including web sites where you got help: (enter none if you didn't need help)
#
def factorial_calc(x): #you may choose the name of the parameter
return # be sure to return the factorial
if __name__ == '__main__':
# Test your code with this first
# Change the argument to try differ... | StarcoderdataPython |
1662512 | <reponame>KATO-Hiro/AtCoder
# -*- coding: utf-8 -*-
def main():
n, m = map(int, input().split())
for i in range(1, n + 1):
if i != m:
print(i)
exit()
if __name__ == '__main__':
main()
| StarcoderdataPython |
3385504 | <reponame>Cynthia-Borot-PNE/Geotrek-admin
from geotrek.authent.serializers import StructureSerializer
from geotrek.common.serializers import PictogramSerializerMixin, BasePublishableSerializerMixin
from geotrek.infrastructure import models as infrastructure_models
class InfrastructureTypeSerializer(PictogramSerializ... | StarcoderdataPython |
124049 | <filename>symupy/runtime/logic/states.py
"""
This module defines the basic states required to execute and launch a simulation.
The states are defined as:
* **Compliance**: This state is defined to check availability of files and candidates.
* **Connect**: This state is defined to process
* **I... | StarcoderdataPython |
63509 | <filename>src/decisionengine_modules/GCE/sources/GCEBillingInfoSourceProxy.py
from decisionengine.framework.modules import Source, SourceProxy
GCEBillingInfoSourceProxy = SourceProxy.SourceProxy
Source.describe(GCEBillingInfoSourceProxy)
| StarcoderdataPython |
1643800 | '''
Copyright 2010 <NAME>
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 |
3392807 | # Generated by Django 3.2.2 on 2021-05-13 10:12
import ai.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ai', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='project',
name='data',
... | StarcoderdataPython |
3261001 | <reponame>vaalu/fxalpha2.0
import json
from kafka import KafkaConsumer
topic_name='3499'
consumer = KafkaConsumer( topic_name,
auto_offset_reset='latest',
bootstrap_servers=['localhost:9092'],
api_version=(0, 10),
consumer_timeout_ms=1000)
while True:
for msg in cons... | StarcoderdataPython |
3251140 | import os
import sys
from distutils.core import setup
if sys.version_info[:2] < (2, 7):
required = ['ordereddict']
else:
required = []
long_desc = open('enum/doc/enum.rst').read()
setup( name='enum34',
version='1.0.4',
url='https://pypi.python.org/pypi/enum34',
packages=['enum'],
... | StarcoderdataPython |
1728063 | #!/usr/bin/env python3
# Programa simple para aprender a usar Qt
from __future__ import with_statement
import sys
import matplotlib
matplotlib.use('Qt4Agg')
from PyQt4 import QtGui, QtCore
from ellipse_plot import Ui_MplMainWindow
from polarization_routines import plot_ellipse, getAnglesFromEllipse, getAnglesFromJon... | StarcoderdataPython |
1720555 | from carla_utils import carla
cc = carla.ColorConverter
import re
import numpy as np
import collections
import pygame
def find_weather_presets():
rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
name = lambda x: ' '.join(m.group(0) for m in rgx.finditer(x))
presets = [x for x in ... | StarcoderdataPython |
3308557 | from typing import List, Tuple
from abides_core import Message
from abides_markets.order_book import OrderBook
from abides_markets.orders import LimitOrder, Side
SYMBOL = "X"
TIME = 0
class FakeExchangeAgent:
def __init__(self):
self.messages = []
self.current_time = TIME
self.mkt_open ... | StarcoderdataPython |
1748832 | r"""
ECEI2D
=======
contains 2D version of synthetic Electron Cyclotron
Emission Imaging Diagnostic.
Unit Conventions
-----------------
In ECEI2D, Gaussian unit is used by default. The units for common quantities
are:
length:
centi-meter
time:
second
mass:
gram
magnetic field:
Gauss
temperature:
... | StarcoderdataPython |
1678425 | import argparse
import sys
from pathlib import Path
import day03
def main(*argv):
parser = argparse.ArgumentParser("Advent of Code - Day 3")
parser.add_argument("filename", type=str, help="The input filename")
args = parser.parse_args(argv)
with open(Path(args.filename), 'rt') as file:
lines... | StarcoderdataPython |
3349789 | import mango
from decimal import Decimal
from mango.marketmaking.orderreconciler import NullOrderReconciler
def test_nulloperation():
existing = [
mango.Order.from_basic_info(mango.Side.BUY, price=Decimal(1), quantity=Decimal(10)),
mango.Order.from_basic_info(mango.Side.SELL, price=Decimal(2), q... | StarcoderdataPython |
3309955 | import logging
import numpy as np
from openpnm.algorithms import ReactiveTransport
from openpnm.utils import Docorator, SettingsAttr
from openpnm.integrators import ScipyRK45
from openpnm.algorithms._solution import SolutionContainer
docstr = Docorator()
logger = logging.getLogger(__name__)
__all__ = ['TransientReacti... | StarcoderdataPython |
3337981 | <filename>json_field.py
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
try:
import json # json module added in Python 2.6.
except ImportError:
from django.utils import simplejson as json
# https://bitbucket.org/offline/django-annoying
class JSONField(models.TextField... | StarcoderdataPython |
4813003 | <reponame>lilsweetcaligula/MIT6.00.1x
import operator
def ParsePolishExpression(exp):
if type(exp) != str:
raise TypeError("expression must be of type string")
try:
supportedOperators = { '/': operator.div,\
'*': operator.mul,\
'+':... | StarcoderdataPython |
3325860 | <reponame>brettkelly/Bible-kjv<filename>sqlGen.py
#!/usr/bin/python3
import json
import os
import os.path
from string import punctuation
BOOKFILE = './Books.json'
SRCDIR = './kjv-data'
bookData = json.load(open(BOOKFILE))
def getBookByLongName(bookName):
for b in books:
if b.longName == bookName:
... | StarcoderdataPython |
3387846 | <reponame>leuder/interest_rate
import unittest
from pynterest_rate import Compound
class TestCompoundClass(unittest.TestCase):
def setUp(self):
self.compound = Compound(0.05, 1, 22.517)
def test_futurevaluecalculation(self):
self.assertEqual(
round(self.compound.calulate_future_va... | StarcoderdataPython |
1736280 | # -*- coding: utf-8 -*-
"""
..
.. seealso:: `SPARQL Specification <http://www.w3.org/TR/rdf-sparql-query/>`_
Developers involved:
* <NAME> <http://www.ivan-herman.net>
* <NAME> <http://www.wikier.org>
* <NAME> <http://www.dayures.net>
* <NAME> <https://indeyets.ru/>
Organizations involved:
* `World... | StarcoderdataPython |
3367269 | <gh_stars>1-10
import numpy as np
from scipy import sparse
from .topology import get_mesh_edges
def barycentric_matrix(uv, tris, num_verts):
"""
Return the barycentric coordinate matrix B such that
B * verts = verts_new
where verts_new yield the barycentric interpolation according to uv
of ... | StarcoderdataPython |
1694543 | # -*- coding: utf-8 -*-
import json
import os
import sys
try:
# For Python 3.0 and later
from urllib import parse
from urllib.request import urlopen, HTTPError, URLError, Request
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen, HTTPError, URLError, Request
import pk... | StarcoderdataPython |
3390404 | <gh_stars>1-10
"""Logarithm of another distribution."""
import numpy
import chaospy
from ..baseclass import Distribution, OperatorDistribution
class Logn(OperatorDistribution):
"""
Logarithm with base N.
Args:
dist (Distribution):
Distribution to perform transformation on.
ba... | StarcoderdataPython |
1669487 | <filename>801-900/804.UniqueMorseCodeWords.py
#
# 804. Unique Morse Code Words
#
# International Morse Code defines a standard encoding where each letter is
# mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps
# to "-...", "c" maps to "-.-.", and so on.
#
# For convenience, the full table for... | StarcoderdataPython |
1749396 | import numpy as np
from cv2 import cv2
import os
import pafy
import argparse
from tensorflow.keras.models import load_model
from collections import deque
output_directory = 'Youtube_Videos'
os.makedirs(output_directory, exist_ok = True)
Activities = ["Biking", "Drumming", "Basketball", "Diving","Billiards","HorseRid... | StarcoderdataPython |
3351780 | <gh_stars>1-10
"""
Django settings for oscardropship project.
Generated by 'django-admin startproject' using Django 2.2.12.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/setti... | StarcoderdataPython |
3361439 | # -*- coding: utf-8 -*-
import itertools
from prompt_smart_menu.helpers import InvalidArgError, Kwarg, NestedDict
from prompt_smart_menu.smart_menu import MenuNode
import pytest
def dummy(*args, **kwargs):
pass
class TestMenuNode:
_nest = {'prompt': {'toolkit', 'menu'}, 'exit': None}
def test_init_c... | StarcoderdataPython |
3359468 | <gh_stars>0
from flask import Flask, render_template, request
import numpy as np
import pandas as pd
import joblib as joblib
app = Flask(__name__)
@app.route('/a')
def test():
return "Flask is being used for Development today"
@app.route('/')
def home():
return render_template('home.html')
... | StarcoderdataPython |
17016 | <filename>tests/test_get_value.py
#!/usr/bin/env python
from numpy.testing import assert_array_almost_equal, assert_array_less
import numpy as np
from heat import BmiHeat
def test_get_initial_value():
model = BmiHeat()
model.initialize()
z0 = model.get_value_ptr("plate_surface__temperature")
assert_... | StarcoderdataPython |
108532 | import unittest, penmon as pm
class Test(unittest.TestCase):
def test_daylight_hours(self):
station = pm.Station(41.42, 109)
day = station.day_entry(135)
day.temp_min = 19.5
day.temp_max = 28
self.assertEqual(day.daylight_hours(), 14.3, "daylighth_hours")
if _... | StarcoderdataPython |
159649 | import frameworks.tc_scikit.features.bag_of_words as bag_of_words
import frameworks.tc_scikit.features.character_embeddings as character_embeddings
import frameworks.tc_scikit.features.character_ngrams as character_ngrams
import frameworks.tc_scikit.features.dependency_distribution_spacy as dependency_distribution_spac... | StarcoderdataPython |
4808984 | <reponame>dysposin/python-ircbot
#!/usr/bin/python3
from vote import vote
class Elections:
def __init__(self):
self.elections = {}
def add_election(self, name):
self.elections[name] = vote.Vote(name)
def close_election(self, name):
self.elections[name].close_voting()
def vote(... | StarcoderdataPython |
3273249 | <reponame>acc-cosc-1336/cosc-1336-spring-2018-artgonzalezacc<gh_stars>0
import unittest
from src.homework.homework3 import sum_odd_numbers
from src.homework.homework3 import list_of_even_numbers
class TestHomework3(unittest.TestCase):
def test_sum_odd_numbers_w_value_11(self):
self.assertEqual(36, sum_od... | StarcoderdataPython |
191409 | <reponame>dcdanko/AriesK<gh_stars>0
import sqlite3
from os.path import join, dirname
from unittest import TestCase
from ariesk.ram import RotatingRamifier
from ariesk.grid_builder import GridCoverBuilder
from ariesk.dbs.kmer_db import GridCoverDB
from ariesk.pre_db import PreDB
from ariesk.utils.parallel_build impor... | StarcoderdataPython |
1731211 | <reponame>antopen/alipay-sdk-python-all
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class SpiDetectionDetail(object):
def __init__(self):
self._code = None
self._content = None
self._data_id = None
self._details =... | StarcoderdataPython |
1746182 | '''Escreva um programa que lê um inteiro N e uma seqüência de N números inteiros, e imprime a soma dos números pares da
seqüência lida.'''
soma = 0
n = int(input('Quantos números deseja ler? '))
for valores in range(1,n+1):
valores = int(input(f'digite o {valores}º valor: '))
if valores % 2 == 0:
soma ... | StarcoderdataPython |
4834024 | <reponame>softformance/django-social-photostream<filename>tests/urls.py
# -*- coding: utf-8
from __future__ import unicode_literals, absolute_import
from django.conf.urls import url, include
from django_social_photostream.urls import urlpatterns as django_social_photostream_urls
urlpatterns = [
url(r'^', include... | StarcoderdataPython |
3322193 | import numpy as np
from c4.evaldiff import evaldiff
from c4.engine.base import Engine
from c4.evaluate import Evaluator, INF
class GreedyEngine(Engine):
def __init__(self):
self._evaluator = Evaluator()
self.evaluate = self._evaluator.evaluate
def choose(self, board):
moves = board.m... | StarcoderdataPython |
1642689 | from django.urls import path
from . import views
urlpatterns = [
path('get_products', views.GetProductsInfo.as_view(), name="get_products"),
path('get_orders', views.GetOrdersInfo.as_view(), name="get_orders"),
path('get_customers', views.GetCustomersInfo.as_view(), name="get_customers"),
p... | StarcoderdataPython |
13474 | ##########################################################################
#
# MRC FGU Computational Genomics Group
#
# $Id$
#
# Copyright (C) 2009 <NAME>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Fre... | StarcoderdataPython |
3363614 | <reponame>pyvec/arca<filename>arca/__init__.py
from ._arca import Arca
from .backend import BaseBackend, VenvBackend, DockerBackend, CurrentEnvironmentBackend, VagrantBackend
from .result import Result
from .task import Task
__all__ = ["Arca", "BaseBackend", "VenvBackend", "DockerBackend", "Result", "Task", "CurrentE... | StarcoderdataPython |
46325 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import rospy
import message_filters
from std_msgs.msg import Int32, Float32
from pololu_drv8835_rpi import motors
rospy.init_node('message_sync', anonymous=False)
speed_desired = 0.5 # desired wheel speed in rpm
angle_desired = 0.0 # desired angle - 0
k_p_angle = 4*480... | StarcoderdataPython |
1703819 | <reponame>SharadRawat/AV-Robo
#!/usr/bin/python
import numpy as np
class MotorController(object):
def __init__(self, max_speed, max_omega):
# These params are to be tuned.
self.kp = 3
self.ka = 8
self.kb = 0
self.max_speed = max_speed
self.max_omega = max_omega
def compute_vel(self, state, goal):
... | StarcoderdataPython |
49375 | #!python3.6
import math
import MusicTheory.NaturalTone
import MusicTheory.Accidental
#NaturalToneに変化記号+,-を付与した値や名前を返す
class ToneAccidentaler:
def __init__(self):
self.__NatulasTone = MusicTheory.NaturalTone.NaturalTone()
self.__Accidental = MusicTheory.Accidental.Accidental()
# tone: C+,B-のような形式... | StarcoderdataPython |
1625249 | <reponame>joshiaj7/CodingChallenges
class Solution:
def findWords(self, words: List[str]) -> List[str]:
ans = []
truth = {
'q': 1,
'w': 1,
'e': 1,
'r': 1,
't': 1,
'y': 1,
'u': 1,
'i': 1,
'o':... | StarcoderdataPython |
3336342 | <reponame>HsOjo/OjoPyADB<gh_stars>1-10
import re
from pyadb import common
from pyadb.utils import ShellLib
from .sub_command import *
class ADB(ShellLib):
MODE_BOOTLOADER = 'bootloader'
MODE_RECOVERY = 'recovery'
MODE_SIDELOAD = 'sideload'
MODE_SIDELOAD_AUTO_REBOOT = 'sideload-auto-reboot'
STATE... | StarcoderdataPython |
16938 | from ubuntui.utils import Padding
from ubuntui.widgets.hr import HR
from conjureup.app_config import app
from conjureup.ui.views.base import BaseView, SchemaFormView
from conjureup.ui.widgets.selectors import MenuSelectButtonList
class NewCredentialView(SchemaFormView):
title = "New Credential Creation"
def... | StarcoderdataPython |
1674992 | <gh_stars>1-10
#!/usr/bin/env python
"""
WordAPI.py
Copyright 2014 Wordnik, 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
Unles... | StarcoderdataPython |
4116 | <reponame>JohnnySn0w/BabbleBot
import random
prefix = [
'Look at you! ',
'Bless ',
'Bless! ',
'I heard about that! ',
'Amen!',
'You and the kids doing alright?',
'Miss ya\'ll!'
]
suffix = [
'. Amen!',
'. God bless america',
'. God bless!',
' haha',
'. love ya!',
'. love ya\'ll!',
]
def add_pre_suf(sentence):
if ... | StarcoderdataPython |
3237153 | #!/usr/bin/env python
from flask import Flask, jsonify, abort, request, make_response
from flask_script import Manager, Server
import requests
import json
import os
import time
import yaml
import config
import issuer
# Load application settings (environment)
config_root = os.environ.get('CONFIG_ROOT', '../config')... | StarcoderdataPython |
1675022 | <reponame>NextThought/pypy-numpy
from __future__ import division, print_function
from os.path import join, split, dirname
import os
import sys
from distutils.dep_util import newer
from distutils.msvccompiler import get_build_version as get_msvc_build_version
def needs_mingw_ftime_workaround():
# We need the mingw... | StarcoderdataPython |
1666466 | from enum import Enum
Stage = Enum("Stage", "Interphase Mitosis")
# class DNA(object):
class Cell(object):
def __init__(self, cell_id, non_mitosis_len, no_food):
self.is_mitosis = False
self.cell_id = int(cell_id)
self.mitosis_countdown = int(non_mitosis_len)
self.mitosis_countdown_legnth = self.mitosis_... | StarcoderdataPython |
4819159 | <reponame>tbsschroeder/dbas
from nose.tools import *
from splinter import Browser
import logging
from selenium.webdriver.remote.remote_connection import LOGGER
LOGGER.setLevel(logging.WARNING)
_multiprocess_can_split_ = True # if the pipeline crashes please disable the multiprocess
ROOT = 'http://localhost:4284'
BRO... | StarcoderdataPython |
63020 | <reponame>Lznah/SrealityAdresarScrapper<gh_stars>0
import re
from classes.page import Page
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from unidecode import unidecode
class AgentsPage(Page):
def __init__(self, url, agent_arr):
Page._... | StarcoderdataPython |
74855 | <filename>test/core/end2end/fuzzers/generate_client_examples_of_bad_closing_streams.py
#!/usr/bin/env python2.7
# Copyright 2015 gRPC 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
... | StarcoderdataPython |
3384957 | # -*- coding: utf-8 -*-
from collections import deque
import gym
import numpy as np
import sys
from RL.PPO import PPO
class Chief(object):
def __init__(self, scope, parameter_dict, SESS, MEMORY_DICT, COORD, workers):
env = gym.make(parameter_dict['GAME'])
self.ppo = PPO(scope, parameter_dict, env, ... | StarcoderdataPython |
1653333 | <reponame>adonayab/python_proj1_manager_app
from flask import redirect, render_template, session, flash, request
from models import User, Message
from app import db
from messages.forms import TaskForm
from utils.helpers import badge_general, badge_urgent
from flask import Blueprint
tasks = Blueprint('tasks', __name__... | StarcoderdataPython |
1766026 | <gh_stars>1-10
__author__ = 'tomaszroszko'
| StarcoderdataPython |
1712063 | <reponame>julienc91/utools<filename>utools/math.py
# -*- coding: utf-8 -*-
""" Useful mathematical functions.
"""
from math import factorial
try:
from math import gcd # python 3.5
except ImportError:
from fractions import gcd
def is_prime(n):
""" Miller-Rabin primality test. Keep in mind that this is ... | StarcoderdataPython |
3295492 | # Copyright 2017 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | StarcoderdataPython |
197110 | # -*- coding: utf-8 -*-
# @Time : 2018/05/18
# @Author : <NAME>
import datetime
import json
import cv2
import numpy as np
import time
import core
import os
from PIL import Image, ImageDraw
def transformation_points(src_img, src_points, dst_img, dst_points):
src_points = src_points.astype(np.float64)
dst_p... | StarcoderdataPython |
4833834 | <gh_stars>10-100
import os
from amitools.vamos.path import VolumeManager, resolve_sys_path
from amitools.vamos.cfgcore import ConfigDict
def path_volume_resolve_sys_path_test(tmpdir):
rsp = resolve_sys_path
p = str(tmpdir)
assert rsp(p) == p
# user home
assert rsp("~") == os.path.expanduser("~")
... | StarcoderdataPython |
119100 | <reponame>Tree-frog-code/trans
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# main_app.py
import trans as tr
opt = None
text = None
try:
opt = sys.argv[1]
text = " ".join(sys.argv[2:])
except:
logger.critical('書式が正しくない可能性があります。')
exit()
opt = opt.strip("-")
print(tr.convert(text=text, lang=opt))
| StarcoderdataPython |
1710317 | # -*- coding: utf-8 -*-
# Copyright 2015 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unittests for the cache.py module."""
from __future__ import print_function
import datetime
import os
import mock
from chro... | StarcoderdataPython |
4831581 | #!/usr/bin/env python
# coding=utf-8
# ====================================================
# File Name : pg_degw.py
# Creation Date : 05-09-2018
# Created By : <NAME>
# Contact : <EMAIL>
# ====================================================
from __future__ import print_function, absolute_import
import ... | StarcoderdataPython |
1743396 | """Test Dynalite __init__."""
import homeassistant.components.dynalite.const as dynalite
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, CONF_ROOM
from homeassistant.setup import async_setup_component
from tests.async_mock import call, patch
from tests.common import MockConfigEntry
async def test_... | StarcoderdataPython |
3214589 | # coding=utf-8
"""
翻转链表中第m个节点到第n个节点的部分
这个是翻转链表的升级版
还是困惑了我2个小时的时间
再一次强化了链表不关心位置,只关心指针指向
大体思路:
找到 翻转的前一位 prev
翻转需要翻转的那一部分,同时找到翻转前最后一位指向元素 以及翻转前的第一位 (因为成为翻转后的最后一位)
然后 前一位 prv 指向翻转后
然后链接后的最后一位 指向翻转前指向的最后那位
m =3 , n = 5
input: 0->1-2->3->4->5->6->7->null
可见翻转的部分为 2->3->5
prev = 1
bf = 6
output: 0->1->4->3->2->5->6->7-... | StarcoderdataPython |
3272324 | <filename>main.py
from json import dumps
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
# Api routes
from routes.Main import Main
from routes.v1.Index import Index
from routes.v1.Ship import Ship
app = Flask(__name__)
api = Api(app)
api.add_resource(Main, "/")
api.add_resource(Ind... | StarcoderdataPython |
4817275 | <reponame>kolea2/synthtool
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | StarcoderdataPython |
49439 | <filename>desktop/core/ext-py/greenlet-0.3.1/tests/test_weakref.py
import gc
import greenlet
import weakref
import unittest
class WeakRefTests(unittest.TestCase):
def test_dead_weakref(self):
def _dead_greenlet():
g = greenlet.greenlet(lambda:None)
g.switch()
return g
... | StarcoderdataPython |
3276868 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
class Migration(DataMigration):
languages = (
('English', 'en'),
(... | StarcoderdataPython |
3244061 | from tableauscraper import TableauScraper as TS
url = "https://public.tableau.com/views/Covid-19ImpactDashboard/Covid-19Impact?:embed=y&:showVizHome=no&:host_url=https%3A%2F%2Fpublic.tableau.com%2F&:embed_code_version=3&:tabs=no&:toolbar=yes&:animate_transition=yes&:display_static_image=no&:display_spinner=no&:displa... | StarcoderdataPython |
3359223 | <filename>Tutorial_Kivy_HashLDash/22kivy.py
# 19 - Python Kivy - Criando um Popup
# https://www.youtube.com/watch?v=w0BwoGl18Fk&list=PLsMpSZTgkF5AV1FmALMgW8W-TvrfR3nrs&index=19
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.wind... | StarcoderdataPython |
3282141 | <filename>Tools/python37/Lib/site-packages/Crypto/Cipher/ChaCha20_Poly1305.py
# ===================================================================
#
# Copyright (c) 2018, <NAME> <<EMAIL>>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provide... | StarcoderdataPython |
1712002 | <reponame>Ally-s-Lab/miRmedon
import os
def alignment_to_emiRbase(fastq_file, path_to_star, threads, star_ref_dir, path_to_samtools):
params = '''--runThreadN {}
--alignIntronMin 1
--outFilterMultimapNmax 200
--outFilterMatchNmin 12
--outFilterMatchNm... | StarcoderdataPython |
1654586 | <reponame>teddy-owen/Tools<gh_stars>0
from django.contrib import messages
################################################################################
# Exposed
################################################################################
def flash_alert(request,type,text):
'''
(obj,str,str)->void
Creates ... | StarcoderdataPython |
1648019 | ## TODO: test case should cover, n_class from 3 to 256, test ignore index, test speed and memory usage
import random
import numpy as np
import torch
import torch.nn as nn
import torchvision
from label_smooth import LabelSmoothSoftmaxCEV3
torch.manual_seed(15)
random.seed(15)
np.random.seed(15)
torch.backends.cudnn.... | StarcoderdataPython |
3335973 | import os
from unittest.mock import patch, call
import pytest
from dev.tasks.pypi import Pypi
@patch('dev.tasks.pypi.os.environ')
@patch('dev.tasks.pypi.run_command')
def test_up(run_command_mock, environ_mock):
environ_mock.get.return_value = 'abc'
Pypi('upload', extra_args=[])
run_command_mock.asser... | StarcoderdataPython |
3203248 | # begin20210418181255
import numpy as np
import pyfftwpp
if __name__ == "__main__":
M, N, dim = 7, 8, 2
x = np.array([0.8, -0.9])[None, :]
y = np.array([-1.1, 1.2])[None, :]
# end20210418181255
#begin20210418181632
m = np.arange(0, M)[:, None]
n = np.arange(0, N)[:, None]
φ_pow_m = n... | StarcoderdataPython |
3288077 | <filename>xpresso/routing/router.py
import sys
import typing
if sys.version_info < (3, 8):
from typing_extensions import Protocol
else:
from typing import Protocol
import starlette.middleware
from starlette.routing import BaseRoute
from starlette.routing import Router as StarletteRouter
from starlette.types i... | StarcoderdataPython |
1729842 | <reponame>cleiver/codeandtalk.com
#!/usr/bin/env python3
import os, sys, json, datetime
# read all the events
# list the ones that have youtube value which is not - and that does NOT have the video directory.
# list the ones that have no youtube entry or that it is empty
# Only show events that have already finished.... | StarcoderdataPython |
4829008 | <reponame>urchinpro/L2-forms
import sys
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
import simplejson
from django.core.management.base import OutputWrapper
from django.db import models
import slog.models as slog
TESTING = 'test' in sys.argv[1:] or 'jenkins' in sys.argv[1:]
... | StarcoderdataPython |
3274693 | from settings import WATCHED_SOURCES
from parsers import default
PARSERS = {}
for source, parsers in WATCHED_SOURCES.items():
parsers = [parsers] if type(parsers) == str else parsers
parser_modules = []
for module_name in parsers:
if module_name:
try:
exec('from parsers... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.