id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3259788
import io import gzip from pathlib import Path import re import zlib from ncompress import decompress as unlzw class MavReader: ''' Opens AVNMAV file and returns stream of data ''' empty = re.compile(b'\s+\n') newline = re.compile(b'1\n') def __init__(self, filepath, stations=False): ...
StarcoderdataPython
3273973
<gh_stars>0 def fun(mystr): return len(mystr) list1 = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'] result = list(map(fun,list1)) print(result)
StarcoderdataPython
3284405
<filename>TweetIngest/send.py import sys import logging import datetime import time import os import enhancedjsonencoder from azure.eventhub import EventHubClient, Sender, EventData from telemetry import Telemetry class EventHubSender(object): def __init__(self, connectionString): print("Initiating Even...
StarcoderdataPython
80829
<reponame>ealpizarp/climate_crawler # Costa Rica Institute of Technology # A web scrapper that fetches information about the world climate from https://en.tutiempo.net/climate # and store it in an local output csv file and in the Hadopp distributed file system # Permission is hereby granted, free of charge, to a...
StarcoderdataPython
1712758
<reponame>KapJI/moonraker-telegram-bot import logging import time from concurrent.futures import ThreadPoolExecutor from apscheduler.schedulers.base import BaseScheduler from telegram import ChatAction, Message, Bot from configuration import ConfigWrapper from camera import Camera from klippy import Klippy logger = ...
StarcoderdataPython
1721365
<reponame>ayush-1506/dialogy """ .. _duration_entity: Module provides access to an entity type (class) to handle locations. Import classes: - LocationEntity """ from typing import Any, Dict import attr from dialogy import constants as const from dialogy.types.entity import BaseEntity @attr.s class DurationEnti...
StarcoderdataPython
50293
<filename>pf_py_common/py_object_copier.py class PyObjectCopier: pass
StarcoderdataPython
3373732
<reponame>Arya07/SSM-Pytorch<gh_stars>0 # -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by <NAME> # -------------------------------------------------------- """Factory method for easily getting i...
StarcoderdataPython
4800399
from numpy import Inf, linspace, meshgrid, reshape from numpy.linalg import norm from numpy.ma import masked_array from numpy.random import rand from .convex_body import ConvexBody from ..util import arr_map class Box(ConvexBody): def sample(self, N): return 2 * rand(N, self.dim) - 1 def is_member(se...
StarcoderdataPython
4824000
import inspect import torch import collections import textwrap import functools import warnings from typing import Dict, List, Set, Type import torch._jit_internal as _jit_internal from torch.jit.frontend import get_default_args, get_jit_def, get_class_properties from torch.jit._builtins import _find_builtin from torc...
StarcoderdataPython
1620733
<reponame>linherest/pgoapi # Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/networking/responses/encounter_tutorial_complete_response.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from goo...
StarcoderdataPython
3301333
<reponame>carthage-college/django-djbeca # -*- coding: utf-8 -*- import datetime from django import forms from django.conf import settings from django.contrib.auth.models import User from djauth.managers import LDAPManager from djbeca.core import choices from djbeca.core.models import GenericChoice from djbeca.core.m...
StarcoderdataPython
1745801
<gh_stars>1-10 # __init__.py __version__ = "0.1.0" __author__ = "<NAME>" """ The :mod:`scifin.timeseries` module includes methods for time series analysis. """ from .timeseries import (Series, TimeSeries, CatTimeSeries, get_list_timezones, build_from_csv, build_from_dataframe, build_from_list...
StarcoderdataPython
1604658
def answer_five(): return census_df.groupby('STNAME')['COUNTY'].count().idxmax() answer_five()
StarcoderdataPython
1659674
<reponame>duttaprat/proteinGAN """The discriminator of WGAN.""" import tensorflow as tf from common.model import ops from model.ops import block def discriminator_fully_connected(x, labels, df_dim, number_classes, kernel=(3, 3), strides=(2, 2), dilations=(1, 1), pooling='avg', update...
StarcoderdataPython
1661403
from utils.decorators import timer, debug from utils.task import Task def all_orientations(): orientations = [] for facing in range(6): for rotation in range(4): orientations.append((facing, rotation)) return orientations def transform_position(pos, orientation, rotation): # Cred...
StarcoderdataPython
3286619
from loguru import logger from fastapi import Request from fastapi.responses import JSONResponse from starlette import status from utils.constant.ResponseCode import ResponseCodeType class BaseDatabaseException(Exception): pass class TableCreateException(BaseDatabaseException): pass class DatabaseCreateE...
StarcoderdataPython
4446
<gh_stars>10-100 """ A customer walks into a store. Do the steps to interact with them: - Get *a* (not *the*) greeter - Interact with them Simple wired application: - Settings that say what punctuation to use - Registry - Two factories that says hello, one for the FrenchCustomer context - A default Customer and...
StarcoderdataPython
4811376
import hashlib import bcrypt from pymongo import MongoClient from online_judge.db import db user_collection = db['users'] class User(object): @staticmethod def exists(username): return user_collection.find_one({'username': username}) is not None def __init__(self, username, password=None, salt=...
StarcoderdataPython
1649742
# Copyright 2018/2019 The RLgraph authors. 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
StarcoderdataPython
1790038
<reponame>QuantLet/spd_trading<gh_stars>1-10 import numpy as np from sklearn.neighbors import KernelDensity from ..utils.smoothing import bspline def density_estimation(sample, X, h, kernel="epanechnikov"): """Kernel Density Estimation over the sample in domain X. Routine for `sklearn.neighbors.KernelDensit...
StarcoderdataPython
1762562
from bancointer.bancointer import BancoInter from decouple import config cert = (config("PUBLIC_KEY"), config("PRIVATE_KEY")) bi = BancoInter(config("CPFCNPJ_BENEF"), config("X-INTER-CONTA-CORRENTE"), cert) reponse = bi.consulta(nosso_numero="00709421471") print(reponse["situacao"])
StarcoderdataPython
61016
from asyncio import FastChildWatcher import os from unicodedata import category from flask import request, current_app, url_for from flask_restful import Resource from datetime import datetime from flask_jwt_extended import ( jwt_required, current_user ) from werkzeug.utils import secure_filename from sqlalchemy.or...
StarcoderdataPython
1621424
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
StarcoderdataPython
3245966
<reponame>gitter-badger/mlmodels<filename>mlmodels/model_tch/vae/util.py import os, sys import numpy as np import scipy as sci import matplotlib.pyplot as plt import pandas as pd import cv2 """ functionality: sine wave npz generation and image gerneration """ # default image shape 64x64x3 # default npz element size ...
StarcoderdataPython
1728726
<reponame>DTenore/skulpt import _sk_fail; _sk_fail._("ctypes")
StarcoderdataPython
4837916
<gh_stars>0 #!/usr/bin/python3 # ------------------------------------------------------------------------------ """@package ble_lights.py Sets the attached light values and notifies when they change. """ # ------------------------------------------------------------------------------ # <NAME> <EMAIL> ...
StarcoderdataPython
3243102
<reponame>schallerdavid/perses """ Test storage layer. TODO: * Write tests """ __author__ = '<NAME>' ################################################################################ # IMPORTS ################################################################################ import os import os.path import tempfile f...
StarcoderdataPython
109210
<gh_stars>0 """ *Temporal Number* """ from abc import ABCMeta __all__ = ["TemporalNumber"] class TemporalNumber: __metaclass__ = ABCMeta
StarcoderdataPython
4840591
import json import os import pyotp import requests from urllib import parse as url_parse from cli_tasks import common from lib.auth487 import common as acm APP_PORT = int(os.getenv('APP_PORT', 8080)) AUTH_INFO_FILE = os.path.join(os.path.dirname(__file__), 'test_data', 'test-auth-info.json') with open(AUTH_INFO_FILE)...
StarcoderdataPython
1770312
from simple_ddl_parser import DDLParser def test_no_unexpected_logs(capsys): ddl = """ CREATE EXTERNAL TABLE test ( test STRING NULL COMMENT 'xxxx', ) PARTITIONED BY (snapshot STRING, cluster STRING) """ parser = DDLParser(ddl) out, err = capsys.readouterr() assert out == "" ...
StarcoderdataPython
1779738
<reponame>Guymer/fmc def load_airport_list(): # Import standard modules ... import csv import os # Create the empty list ... airports = [] # Make database path ... dbpath = f"{os.path.dirname(__file__)}/../openflights/data/airports.dat" # Check that database is there ... if not os...
StarcoderdataPython
83602
<filename>src/train/features/__init__.py from sklearn.pipeline import FeatureUnion from .features import ( Speed, NetClearance, DistanceFromSideline, Depth, PlayerDistanceTravelled, PlayerImpactDepth, PreviousDistanceFromSideline, PreviousTimeToNet, Hitpoint, Out, WeirdNetCl...
StarcoderdataPython
1725813
<filename>djexperience/service/admin.py from django.contrib import admin from .models import Service, TypeService, Protest @admin.register(Service) class ServiceAdmin(admin.ModelAdmin): list_display = ('__str__', ) search_fields = ('title',) @admin.register(TypeService) class TypeServiceAdmin(admin.ModelAdm...
StarcoderdataPython
1734096
<gh_stars>0 from .models import QueueItem def enqueue(queue_type='s'): item = QueueItem.objects.create(item_type=queue_type) return item.id def peek(queue_type,queue_id, upto_first_n=1): # check if job_id is one of the first N items from the head of queue top_items = QueueItem.objects.filter(item_type...
StarcoderdataPython
3236861
import numpy as np import tensorflow as tf import tensorflow.python.platform from tensorflow.models.rnn import rnn from tensorflow.models.rnn import rnn_cell from bi_rnn import bi_rnn from utils import * ############################################### # NN creation functions # #################...
StarcoderdataPython
90748
from django import forms from django.core.exceptions import ValidationError from htmx_tutorial.clients.models import Client from htmx_tutorial.clients.utils import get_max_order class SimpleClientForm(forms.Form): input_text = forms.CharField() first_name = forms.CharField(required=False) last_name = for...
StarcoderdataPython
3232948
import Room import Constants as c class E24_R2(Room.Room): def __init__(self): super().__init__('Amnesia Totale', 'https://escaperoomromaexitus.com/quest/amnesiatotale/', 'E24_R2') def get_prices(self): p = ['2 GIOCATORI – € 25,00 a persona', '3 GIOCATORI – € 20,00 a persona', ...
StarcoderdataPython
1764789
# Code Author: <NAME> # Uniform Preprocessing file for performing Out-painting for SML project from segmentation_models import Unet, Nestnet, Xnet import numpy as np from keras import backend as K from keras.models import Model from keras.layers import Flatten, Dense, Dropout from keras.layers import Conv2D from ker...
StarcoderdataPython
170054
<gh_stars>10-100 """Collect macro definitions from header files. """ # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # 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 ...
StarcoderdataPython
4825776
<filename>tests/llvm/observation_spaces_test.py # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """Integrations tests for the LLVM CompilerGym environments.""" import os import sys from typin...
StarcoderdataPython
1689761
<reponame>NickolausDS/deriva-action-provider import os import json import csv from deriva.core import urlquote from deriva.core.ermrest_config import tag from . import tableschema2erm # we'll use this utility function later... def topo_sorted(depmap): """Return list of items topologically sorted. depmap...
StarcoderdataPython
1686887
#!/usr/bin/env python # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Prints "1" if Chrome targets should be built with hermetic Xcode. Prints "2" if Chrome targets should be built with hermetic Xcode,...
StarcoderdataPython
1604339
<gh_stars>0 s = input() t = input() u = list(s) v = list(t) com1 = [] com1.append(u[0]) p = 0 for i in range(len(u)): for j in range(len(u)): if j == len(u) - 1: u[0] = com1[j] else: com1.append(u[j + 1]) u[j + 1] = com1[j] if u == v: print("Yes") ...
StarcoderdataPython
1787889
<filename>Chapter 07/Chap07_Example7.141.py<gh_stars>0 def my_generator_function(): num = 1 print('Printing first') yield num num += 1 print('Printing second') yield num num += 1 print('Printing third') yield num num += 1 print('Printing at last') yi...
StarcoderdataPython
1775253
#!/usr/bin/env python # -*- coding: UTF-8 -*- import platform from selenium import webdriver from bs4 import BeautifulSoup # Check Python version # print(platform.python_version()) # Using the right PhantomJS for the corresponding OS if platform.system() == "Windows": PHANTOMJS_EXE = "./PhantomJS/phantomjs.exe"...
StarcoderdataPython
3367145
import pytest from floodlight.io.utils import get_and_convert # Test get_and_convert function @pytest.mark.unit def test_get_and_convert() -> None: sample_dict = {"foo": "1"} # get assert get_and_convert(sample_dict, "foo", int) == 1 # convert assert type(get_and_convert(sample_dict, "foo", int)...
StarcoderdataPython
167420
<gh_stars>0 import numpy as np from g2p.data import DoubleBets def mean_score(eval_func, pred, label_seq): return np.mean([ eval_func(p, DoubleBets.arpabet.unwrap_iseq(l)) for p, l in zip(pred, label_seq.t()) ])
StarcoderdataPython
3246994
from .database import * from .LyceumGroup import * from .LyceumUser import * from .Settings import * from .Student import * from .Task import * from .ActiveTop import *
StarcoderdataPython
3383410
import os from django.core.management.base import BaseCommand from django.conf import settings from crawler import search_changelog, _parse_changelog_text from allmychanges.models import Repo from allmychanges.utils import cd, get_package_metadata, download_repo class Command(BaseCommand): help = u"""Up...
StarcoderdataPython
193629
<filename>rlbench/tasks/stack_chairs.py from pyrep.objects.proximity_sensor import ProximitySensor from pyrep.objects.object import Object from pyrep.objects.shape import Shape from rlbench.backend.conditions import DetectedCondition, NothingGrasped, Condition from rlbench.backend.spawn_boundary import SpawnBoundary ...
StarcoderdataPython
95685
<reponame>Basdanso/reimbursementApi from unittest import TestCase from daos.account_dao_postgres import AccountDaoPostgres from entities.account import Account account_dao = AccountDaoPostgres() #account_dao = AccountDaoLocal() test_account = Account(0, "Bas", "<EMAIL>", "password", "<PASSWORD>", 2000) def test_cr...
StarcoderdataPython
1734223
<reponame>aruymgaart/AMATH import numpy as np from scipy.signal import convolve2d from skimage.color import rgb2grey import matplotlib.pyplot as plt import pickle, copy def getCanImg(MX,s,fr,x,y,w=10,h=15,offy=1): return MX[s][fr][y+offy-h:y+offy+h,x-w:x+w,:] def rgbDifference(im1, im2): ret = np.ones(im1.shape) * 9...
StarcoderdataPython
86453
#!/usr/bin/env python import os import glob HERE = os.path.dirname(__file__) files = glob.glob(os.path.join(HERE, '../data/json/*.json')) from codetalker import testing import codetalker.contrib.json as json parse_rule = testing.parse_rule(__name__, json.grammar) def make_parse(fname): text = open(fname).read(...
StarcoderdataPython
3279777
import sys K,L,R = map(int ,input().split(' ')) bad_apples = set() for line in sys.stdin: y,x = map(lambda x: int(x) - 1 ,line.split(' ')) bad_apples.add((y,x)) new_bad_apples = set() for i in range(R): for apple in bad_apples: if apple[0] + 1 < K: new_bad_apples.add((apple[0]+1, app...
StarcoderdataPython
122078
from .Badge import Badge as BadgeDBModel from .BadgeCondition import BadgeCondition as BadgeConditionDBModel from .BadgeType import BadgeType as BadgeTypeDBModel from .Organization import Organization as OrganizationDBModel from .OrganizationType import OrganizationType as OrganizationTypeDBModel from .OrgPos import Or...
StarcoderdataPython
1783248
<filename>util/correlation/get_hw_stats.py #!/usr/bin/env python from optparse import OptionParser import os import subprocess this_directory = os.path.dirname(os.path.realpath(__file__)) + "/" import sys sys.path.insert(0,os.path.join(this_directory,"..","job_launching")) import common import re import shutil import ...
StarcoderdataPython
3266511
<filename>src/resources/python/grab_team.py import requests import pandas as pd import json import time import os, sys import pickle import datetime as dt import constants from nba_api.stats.library import data from nba_api.stats.endpoints import franchisehistory,commonteamroster,leaguegamelog, leaguedashteamstats, lea...
StarcoderdataPython
44047
#!/usr/bin/env python # -*- coding: utf-8 -*- import time from bms_state_machine import BMSChargeStateMachine, BMSChargeModel, BMSChargeController # 48V 16S LiFePO4 Battery # Absorption: 58V (56.4 for longer life) # Float: 54.4V # Restart bulk voltage: Float-0.8 (max of 54V) # Inverter Cut-off: 42.8V-48V (depending ...
StarcoderdataPython
1653676
import os from typing import Any import ftputil.error from PyQt5.QtCore import QMutex from backend_file import BackendFile class FTPBackendFile(BackendFile): _file: Any _file_mutex: QMutex = QMutex() _host: ftputil.FTPHost _path: str _pos: int _size: int def __init__(...
StarcoderdataPython
1742459
from weblab.core.coordinator.clients.weblabdeusto import WebLabDeustoClient import os import time from weblab.core.reservations import WaitingReservation, ConfirmedReservation, WaitingConfirmationReservation from weblab.data.command import Command from weblab.data.experiments import ExperimentId import threading imp...
StarcoderdataPython
1753268
<filename>tests/test_data/test_pipelines/test_random_degradations.py # Copyright (c) OpenMMLab. All rights reserved. import numpy as np import pytest from mmedit.datasets.pipelines import (DegradationsWithShuffle, RandomBlur, RandomJPEGCompression, RandomNoise, ...
StarcoderdataPython
191381
<reponame>Arbupa/DAS_Sistemas<filename>Ene-Jun-2019/Ejemplos/Code Golf/albertos-solution.py for j in [6,11,4,19,61,100,1001,5001,55556,777778]: print(' '.join([str(i) for i in range(1,j)]),end='' if j==777778 else '\n')
StarcoderdataPython
1629537
<gh_stars>0 from __future__ import absolute_import from .message import Message, ExceptionMessage from . import log, parallel_backend_loaded, remote_import from ..util.check_deleted import check_deleted import pynbody import gc import six.moves.cPickle as pickle import numpy as np from six.moves import zip import time ...
StarcoderdataPython
1694071
# # This file is part of pysmi software. # # Copyright (c) 2015-2020, <NAME> <<EMAIL>> # License: http://snmplabs.com/pysmi/license.html # import sys try: import unittest2 as unittest except ImportError: import unittest from pysmi.parser.smi import parserFactory from pysmi.codegen.pysnmp import PySnmpCodeGen ...
StarcoderdataPython
4806850
<filename>Spread_Strat/Inflation_Spread.py<gh_stars>1-10 # -*- coding: utf-8 -*- """ Created on Sat Apr 25 03:00:21 2020 Gold vs Silver combined with 10Y bond price to check inflation or deflation @author: <NAME> @contact: <EMAIL> """ import DB.dbFetch as dbFetch import pandas as pd import datetime as dt i...
StarcoderdataPython
3227134
from itertools import count import logging import networkx import ailment from claripy.utils.orderedset import OrderedSet from ...utils.graph import dfs_back_edges, subgraph_between_nodes, dominates, shallow_reverse from .. import Analysis, register_analysis from .utils import replace_last_statement from .structurer...
StarcoderdataPython
1742542
from django.test import TestCase from dali.gallery.models import Gallery, Picture, _get_viewable_size, _get_thumbnail_size from dali.gallery.tests.utils import create_picture, get_image, get_temp_name class GalleryTestCase(TestCase): fixtures = ['gallery.json'] def setUp(self): self.gallery = Gallery....
StarcoderdataPython
3258317
<gh_stars>10-100 # Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 # model file: example-models/misc/moving-avg/stochastic-volatility-optimized.stan import torch import pyro import pyro.distributions as dist def init_vector(name, dims=None): return pyro.sample(name, dist.Normal(t...
StarcoderdataPython
154226
<filename>train.py<gh_stars>1-10 from Trainer import * from TrainerOptions import * opt = TrainerOptions() opt.parse_args() trainer = Trainer(opt) trainer.train()
StarcoderdataPython
4808267
import sys with open(sys.argv[1], "rb") as fin: with open(sys.argv[2], "w") as fout: fout.write("package %s\n" % sys.argv[3]) fout.write("var %s = []byte{" % sys.argv[4]) while True: chunk = fin.read(1024) if not chunk: break for c in chun...
StarcoderdataPython
3311556
import unittest from fearquantlib.wavelib import __max_successive_series_len as max_len class TestMxSuccSeriesLen(unittest.TestCase): def test_fn(self): arr = [1,7,3,4,5,2,4,5,6,1,0,4] l = max_len(arr, asc=False) self.assertEqual(3,l)# 6,1,0 l2 = max_len(arr) # 2,4,5,6, s...
StarcoderdataPython
3263290
<filename>src/modules/geodesy/src/geodesy_conversion_UTM.py #!/usr/bin/env python """Converts geodetic coordinate system to and from UTM""" from __future__ import print_function from __future__ import division import math import utm from geodesy import Geodesy class GeodesyConverterUTM(Geodesy): def __init__(s...
StarcoderdataPython
45524
''' A função inverte strings e coloca todas as letras em maiúsculo: ''' def fazAlgo(string): pos = len(string)-1 string = string.upper() while pos >= 0: print(string[pos], end="") pos = pos - 1 fazAlgo("amora")
StarcoderdataPython
1638423
"""Place of record for the package version""" __version__ = "2.0.0"
StarcoderdataPython
3345885
<reponame>ian-chong/bucketlist-backend """ Package to manage the API configurations """
StarcoderdataPython
196056
# -*- coding: utf-8 -*- """ @author: <NAME> @contact: <EMAIL> @time: 2022/05/05 1:06 PM """ import sys if './' not in sys.path: sys.path.append('./') from screws.freeze.base import FrozenOnly class _2nCSCG_CellTypeWr2Metric_Base(FrozenOnly): """ A base for all cell types w.r.t. metric. For each type of cscg ...
StarcoderdataPython
54592
from django.contrib import admin from safe.models import PublicKey, Credential, UserSecret class PublicKeyAdmin(admin.ModelAdmin): raw_id_fields = ['user'] readonly_fields = ['created', 'modified'] list_display = ['user', 'created', 'modified'] class UserSecretInline(admin.StackedInline): model = U...
StarcoderdataPython
1610465
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import logging import itertools import numpy as np from allel.util import asarray_ndim, check_dim0_aligned, ensure_dim1_aligned from allel.model.ndarray import GenotypeArray from allel.stats.window import windowed_statistic, ...
StarcoderdataPython
1607594
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( author="<NAME>", author_email="<EMAIL>", name="temporal-infinities", version="0.1.0", description="Infinities for datetime, date and timedelta.", long_description=long_description, long_...
StarcoderdataPython
4814913
<reponame>rh01/Deep-reinforcement-learning-with-pytorch import argparse import pickle from collections import namedtuple import os import numpy as np import matplotlib.pyplot as plt import torch def discount(sequence, Gamma = 0.99): R = 0 reward = [] for r in sequence[::-1]: R = r + Gamma * R ...
StarcoderdataPython
3380917
import logging from django.contrib import messages from django.shortcuts import redirect from django.utils.translation import ugettext_lazy as _ from django.views.generic import FormView from pretix.base.models import Order from pretix.base.services.mail import mail from pretix.control.permissions import EventPermiss...
StarcoderdataPython
1767802
from utils.solution_base import SolutionBase class Solution(SolutionBase): def solve(self, part_num: int): self.test_runner(part_num) func = getattr(self, f"part{part_num}") result = func(self.data) return result def test_runner(self, part_num): test_inputs = self.get...
StarcoderdataPython
4815445
<reponame>Wikunia/hakank #!/usr/bin/python -u # -*- coding: latin-1 -*- # # Coins grid problem in Z3 # # Problem from # <NAME>: "A coin puzzle - SVOR-contest 2007" # http://www.svor.ch/competitions/competition2007/AsroContestSolution.pdf # ''' # In a quadratic grid (or a larger chessboard) with 31x31 cells, one should...
StarcoderdataPython
3236018
<gh_stars>1000+ # Copyright 2021 Huawei, Inc. # 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. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
StarcoderdataPython
1667802
<gh_stars>1-10 from rest_framework import serializers from .models import NotificationUser , Notification from push_notifications.models import GCMDevice class NotificationUserSerializer(serializers.ModelSerializer): class Meta: model = NotificationUser fields = '__all__' class NotificationUserRel...
StarcoderdataPython
40159
<reponame>KaroliShp/Quantumformatics import pytest from pytest_mock import mocker from hamcrest import * import numpy as np from src.dirac_notation.ket import Ket from src.dirac_notation.bra import Bra from src.dirac_notation.matrix import Matrix @pytest.mark.parametrize('input_1,input_2,expected_output_1,expected_o...
StarcoderdataPython
1650680
import numpy as np from abc import ABC, abstractmethod from .model import Model from ..util.metrics import mse, mse_prime class Layer(ABC): def __init__(self): self.input = None self.output = None @abstractmethod def forward(self, input): raise NotImplementedError @abstractme...
StarcoderdataPython
3347023
""" This top-level module conditionally imports some other sub modules in a way that tracks their third party deps """ # Local from . import setup_tools from .import_tracker import track_module from .lazy_import_errors import lazy_import_errors from .lazy_module import LazyModule
StarcoderdataPython
1781945
<gh_stars>0 import hashlib def hash_text(text): return hashlib.md5(text.encode('ascii')).hexdigest()
StarcoderdataPython
1648886
<gh_stars>0 # Import necesarry modules import json import urllib.request, urllib.parse # Class for the Geocoder API class Geocoder(): # Contructor of the class def __init__(self): # Initialize variables self.google_api_key_ = '<KEY>' self.here_app_id_ = 'Mnswcv5a6ivjZ2XGDR4s' self.here_app_code_ = 'EZ1q...
StarcoderdataPython
120458
<reponame>benrdavison/brd_mod import pandas as pd import sys import os from brd_mod.brdstats import * from brd_mod.brdgeo import * from brd_mod.brdecon import * if __name__ == "__main__": print("test")
StarcoderdataPython
1632834
<reponame>bopopescu/conpaas-1 import unittest from core import test_agent from core import test_git from core import test_clouds suites = [ unittest.TestLoader().loadTestsFromTestCase(test_agent.TestAgent), unittest.TestLoader().loadTestsFromTestCase(test_git.TestGit), unittest.TestLoader().loadTestsFromT...
StarcoderdataPython
157137
<reponame>bunjdo/bunjgames from common.consumers import Consumer from whirligig.models import Game from whirligig.serializers import GameSerializer class WhirligigConsumer(Consumer): @property def routes(self): return dict( next_state=lambda game, from_state: game.next_state(from_state), ...
StarcoderdataPython
54063
<filename>final/160401069/sunucu.py<gh_stars>1-10 #<NAME> - 160401069 import socket import sys import datetime import pickle host = "127.0.0.1" port = 142 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) print("Baglama Basarili") except : print("Baglanti hata...
StarcoderdataPython
97542
from collections import Collection import regex as re import numpy as np from bn.values.array_val import ArrayVal from bn.values.boolean_val import BooleanVal from bn.values.double_val import DoubleVal from bn.values.none_val import NoneVal from bn.values.relational_val import RelationalVal from bn.values.set_val impo...
StarcoderdataPython
116029
# -*- coding: utf-8 -*- from .compras import ( AdicionarOrcamentoCompraView, AdicionarPedidoCompraView, OrcamentoCompraListView, OrcamentoCompraVencidosListView, OrcamentoCompraVencimentoHojeListView, PedidoCompraListView, PedidoCompraAtrasadosListView, PedidoCompraEntregaHojeListView, ...
StarcoderdataPython
1689075
from .menulistener import MenuListener __red_end_user_data_statement__ = "No personal data is stored." def setup(bot): n = MenuListener(bot) bot.add_cog(n) bot.loop.create_task(n.reload())
StarcoderdataPython
60464
from django.contrib.contenttypes.models import ContentType from nautobot.dcim.models import Site from nautobot.extras.choices import CustomFieldTypeChoices from nautobot.extras.jobs import Job from nautobot.extras.models import CustomField class TestCreateSiteWithCustomField(Job): class Meta: name = "Sit...
StarcoderdataPython
3380036
<filename>catkin_ws/src/ros_cap/src/cosa.py #! /usr/bin/env python3 import copy import cv2 import numpy as np from keras.models import load_model from phue import Bridge import pygame import time import rospy # General Settings prediction = '' action = '' score = 0 img_counter = 500 # pygame.event.wait() # Turn on/...
StarcoderdataPython