id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
180328 | <filename>server/main.py
from enum import Enum
from http import HTTPStatus
from flask import Flask, jsonify, request, Response, send_from_directory, abort
from flask_cors import CORS, cross_origin
from waitress import serve
from sys import platform
import subprocess
import os, json
# from werkzeug.wrappers import resp... | StarcoderdataPython |
3331136 | # @Author : FederalLab
# @Date : 2021-09-25 16:57:18
# @Last Modified by : <NAME>
# @Last Modified time: 2021-09-25 16:57:18
# Copyright (c) FederalLab. All rights reserved.
import os
import random
import pytest
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.da... | StarcoderdataPython |
4808713 | <filename>machineNumber.py<gh_stars>1-10
def floatPoint(mantisa):
normalizedMantisa = 0
for index, value in enumerate(mantisa):
normalizedMantisa += int(value)*pow(2,-index-1)
return normalizedMantisa
def machineNumber(sign, exp, mantisa):
expDecimal = int(exp,2)
expSize = len(exp)
ex... | StarcoderdataPython |
3256043 | import torch
import pytest
import numpy as np
import pytorch_tools as pt
import pytorch_tools.segmentation_models as pt_sm
INP = torch.ones(2, 3, 64, 64)
ENCODERS = ["resnet34", "se_resnet50", "efficientnet_b1", "densenet121"]
SEGM_ARCHS = [pt_sm.Unet, pt_sm.Linknet, pt_sm.DeepLabV3, pt_sm.SegmentationFPN, pt_sm.Segm... | StarcoderdataPython |
3371601 | import ConfigParser
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from utils import *
def get_exp_gr(exp_id, df, config):
column_name = config.get('Experiment', 'growth_rate_column')
return df.loc[exp_id][column_name]
def export_solution(compartment_data, solution, config):
... | StarcoderdataPython |
1609966 | # Copyright 2016 Google 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
#
# Unless required by applicable law or a... | StarcoderdataPython |
3358085 | <reponame>bjnortier/fusion-mujoco-py
import adsk.core, adsk.fusion, traceback
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from fusion_mujoco_py.export import write_stls_and_mojoco_xml
def run(context):
try:
app = adsk.core.Application.get()
pro... | StarcoderdataPython |
188272 | <filename>tools/create_buffer.py<gh_stars>0
#!/usr/bin/env python
# Copyright (c) 2003-2018, Xively All rights reserved.
#
# This is part of the Xively C Client library,
# it is licensed under the BSD 3-Clause license.
import argparse
import os.path
import struct
from pprint import pprint
h_file_name = ""
c_file_nam... | StarcoderdataPython |
3231321 | #! /usr/bin/env python
import numpy as np
from numpy import log
from scipy.special import gamma
def PoissonGamma(x, M, p, ind_var="kb"):
"""Return Poisson-Gamma distribution as a function of k or kb. The other one is passed
as a parameter. Depending on the argument ind_var.
"""
if ind_var == "kb":
... | StarcoderdataPython |
35705 | <reponame>musicpiano/mlmicrophysics
import xarray as xr
import argparse
from glob import glob
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", help="Input File Directory")
parser.add_argument("-o", "--output", help="Output file directory")
parser.add_argument("-x", "-... | StarcoderdataPython |
182424 | <gh_stars>1-10
# SPDX-License-Identifier: GPL-2.0
import pytest
import u_boot_utils
@pytest.mark.buildconfigspec('cmd_pinmux')
def test_pinmux_usage_1(u_boot_console):
"""Test that 'pinmux' command without parameters displays
pinmux usage."""
output = u_boot_console.run_command('pinmux')
assert 'Usage... | StarcoderdataPython |
1747204 | list_of_ints = [-10, -10, 1, 3, -100]
def max_product(arr):
s = sorted(arr)
option_one = s[0] * s[1] * s[-1]
option_two = s[-3] * s[-2] * s[1]
return max(option_one, option_two)
print(max_product(list_of_ints)) | StarcoderdataPython |
3335759 | from itertools import cycle
import numpy as np
from adapt.strategy.strategy import Strategy
class DLFuzzRoundRobin(Strategy):
'''A round-robin strategy that cycles 3 strategies that suggested by DLFuzz.
DLFuzz suggest 4 different strategy as follows:
* Select neurons that are most covered.
* Select neurons... | StarcoderdataPython |
1723527 | <filename>s06_estruturas_de_repeticao/s06_exercicios/s06_exercicio_18.py
"""
18) Escreva um algoritmo que leia certa quantidade de números
e imprima o maior deles e quantas vezes o maior número foi lido.
A quantidade de números a serem lidos deve ser fornecida pelo usuário.
"""
quantidade_numeros = int(input('Digite a... | StarcoderdataPython |
1799534 | """ Broadly applicable NGS processing/analysis functionality """
import os
import re
import subprocess
import errno
from attmap import AttMapEcho
from yacman import load_yaml
from .exceptions import UnsupportedFiletypeException
from .utils import is_fastq, is_gzipped_fastq, is_sam_or_bam
class NGSTk(AttMapEcho):
... | StarcoderdataPython |
62218 | <reponame>v7labs/darwin-lib<filename>darwin/importer/formats/darwin.py
from pathlib import Path
from typing import Optional
import darwin.datatypes as dt
from darwin.utils import parse_darwin_json
def parse_path(path: Path) -> Optional[dt.AnnotationFile]:
"""
Parses the given file into a darwin ``AnnotationF... | StarcoderdataPython |
3220104 | import os
from scielo_v3_manager.v3_gen import generates
def add_pids_to_xml(xml_sps, document, xml_file_path, pid_v2, v3_manager):
"""
Garante que o PID v3 esteja no XML e que ele esteja registrado no SPF,
seja no Article ou no v3_manager
"""
# add scielo_pid_v2, se aplicável
_add_scielo_pid... | StarcoderdataPython |
89329 | import os
import sys
import time
from unittest import TextTestResult
from xml.etree import ElementTree as ET
from django.test.runner import DiscoverRunner
from django.utils.encoding import smart_text
class EXMLTestResult(TextTestResult):
def __init__(self, *args, **kwargs):
self.case_start_time = time.t... | StarcoderdataPython |
1707751 | <reponame>bckim92/dotfiles
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@wookayin's ███████╗██╗██╗ ███████╗███████╗
██████╗ █████╗ ████████╗██╔════╝██║██║ ██╔════╝██╔════╝
██╔══██╗██╔══██╗╚══██╔══╝█████╗ ██║██║ █████╗ ███████╗
██║ ██║██║ ██║ ██║ ██╔══╝ ██║██║ ██╔... | StarcoderdataPython |
114452 | # -*- coding: utf-8 -*-
import json
import datetime
import requests
import boto3
import time
def initClient(access_key,secret_key,region):
return boto3.client(
'ecs',
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
region_name=region
)
def createClusterECS(ecsClient,cluserNam... | StarcoderdataPython |
1605933 | <filename>sintatico.py
from cmath import pi
from glob import glob
pilha = []
global x
#variavel de controle (se permanecer em 0 não é possível empilhar ou reduzir com os simbolos analisados, entao ha um erro no codigo)
global reduzOrEmpilha
#gramaticaItens = [qtd de itens a serem tirados da pilha, não terminal a ser... | StarcoderdataPython |
96339 | <filename>sdk/python/pulumi_alicloud/cen/get_private_zones.py<gh_stars>10-100
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from ... | StarcoderdataPython |
1739625 | from __future__ import unicode_literals
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
import django
from django.utils.functional import lazy
__all__ = ['User', 'AUTH_USER_MODEL']
# Django 1.5+ compatibility
if django.VERSION >= (1, 5):
AUTH_USER_MODEL = settings.AUTH_US... | StarcoderdataPython |
30557 | #!/usr/bin/env python
from browsers import browsers
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutExc... | StarcoderdataPython |
19103 | <gh_stars>10-100
import numpy as np
import tensorflow as tf
from .unet import UNet
def tf2pytorch(checkpoint_path, num_instrumments):
tf_vars = {}
init_vars = tf.train.list_variables(checkpoint_path)
# print(init_vars)
for name, shape in init_vars:
try:
# print('Loading TF Weight ... | StarcoderdataPython |
20423 | from oscar.apps.checkout.models import * # noqa
| StarcoderdataPython |
1710206 | <reponame>Akshay-N-Shaju/sync-project
print "hello"
print "hello"
print "hello"
| StarcoderdataPython |
3286644 | #!/usr/bin/env python
# encoding: utf-8
__copyright__ = "Copyright 2021, AAIR Lab, ASU"
__authors__ = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"]
__credits__ = ["<NAME>"]
__license__ = "MIT"
__version__ = "1.0"
__maintainers__ = ["<NAME>", "<NAME>"]
__contact__ = "<EMAIL>"
__docformat__ = 'reStructuredText'
import rospy... | StarcoderdataPython |
1739921 | # Copyright 2017 Google 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
#
# Unless required by applicable law or a... | StarcoderdataPython |
4840496 | <gh_stars>100-1000
from .lr_finder import *
from .one_cycle import *
from .fp16 import *
from .general_sched import *
from .hooks import *
from .mixup import *
from .rnn import *
| StarcoderdataPython |
1764313 | import sys
sys.path.append('../../')
import DDPG
import OurDDPG
import TD3
import utils
import numpy as np
import torch
import argparse
import os
import random
sys.path.append('../')
from common import make_env, get_frame_skip_and_timestep, perform_action, random_jitter_force, random_disturb
from evals import *
defa... | StarcoderdataPython |
1640356 | from django.contrib import admin
from .models import Theme, Description, Word
admin.site.register(Theme)
admin.site.register(Description)
admin.site.register(Word) | StarcoderdataPython |
3357859 | __all__ = ["Button", "Color", "Direction", "Port", "Stop"]
from .__stub.__button import Button
from .__stub.__color import Color
from .__stub.__direction import Direction
from .__stub.__port import Port
from .__stub.__stop import Stop
| StarcoderdataPython |
1458 | <reponame>awesome-archive/urh<filename>src/urh/ui/delegates/CheckBoxDelegate.py
from PyQt5.QtCore import QModelIndex, QAbstractItemModel, Qt, pyqtSlot
from PyQt5.QtWidgets import QItemDelegate, QWidget, QStyleOptionViewItem, QCheckBox
class CheckBoxDelegate(QItemDelegate):
def __init__(self, parent=None):
... | StarcoderdataPython |
3324046 | """
Code for Ordered-Neurons Sentence encoder
Modules re-used from: https://github.com/yikangshen/Ordered-Neurons
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as f
from ...utils.locked_dropout import LockedDropout
def embedded_dropout(embed, words, dropout=0.1, scale=None):
... | StarcoderdataPython |
178473 | from .device import SimulatedLakeshore340
from ..lewis_versions import LEWIS_LATEST
framework_version = LEWIS_LATEST
__all__ = ['SimulatedLakeshore340']
| StarcoderdataPython |
3241701 | # Example using PIO to turn on an LED via an explicit exec.
#
# Demonstrates:
# - using set_init and set_base
# - using StateMachine.exec
import time
from machine import Pin
import rp2
# Define an empty program that uses a single set pin.
@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW)
def prog():
pass
# Construct t... | StarcoderdataPython |
1677677 | <reponame>wzhengui/pylibs
#!/usr/bin/env python3
#generate bctides.in's tide harmonics
from pylib import *
#---------------------------------------------------------------------
#input
#---------------------------------------------------------------------
tnames=['O1','K1','Q1','P1','M2','S2','K2','N2']
StartT=[2010,1... | StarcoderdataPython |
45370 | <gh_stars>0
# StorageGRID Data Management Console (DMC)
# Copyright (c) 2018, NetApp, Inc.
# Licensed under the terms of the Modified BSD License (also known as New or Revised or 3-Clause BSD)
import re
from app import logger
from app import get_s3_client
from utils import *
from flask import jsonify
import botocore... | StarcoderdataPython |
3360194 | VALID_CARDS = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']
class Card:
def __init__(self, value):
if value not in VALID_CARDS:
raise Exception(f'{value} is not a valid card.')
self.value = value
| StarcoderdataPython |
127060 | <filename>codeforces/cdf390_2b.py
N = 4
board = [input() for _ in range(4)]
for i in range(N):
for j in range(N):
cand = []
if j + 2 < N:
cand.append([board[i][j+k] for k in range(3)])
if i + 2 < N:
cand.append([board[i+k][j] for k in range(3)])
if i + 2 < N a... | StarcoderdataPython |
1695003 | <filename>tests/test_a_dummy_for_coverage.py
import signal
import sys
from pytest_cov.embed import cleanup
# https://pytest-cov.readthedocs.io/en/latest/mp.html#abusing-process-terminate
# https://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python
def handle_termination_signal(signum, frame):
... | StarcoderdataPython |
88668 | # -*- coding: utf-8 -*-
from omoide.migration_engine.operations \
.relocate.relocate import act
| StarcoderdataPython |
171710 | <reponame>JackywithaWhiteDog/gcp-auth-practice
from google_auth_oauthlib import flow
from google.cloud import bigquery
from google.oauth2 import service_account
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
QUERY_STRING = """
SELECT
EXTRACT(YEAR FROM date) year,
EXTRACT(MONTH FROM date) month,
... | StarcoderdataPython |
1650318 | import os
from shardingpy.parsing.parser.context.selectitem import AggregationSelectItem
from shardingpy.parsing.parser.sql.dql.select import SelectStatement
from shardingpy.parsing.parser.token import *
from tests.parsing.sql import SQLCaseType, get_supported_sql
from .parsers import ALL_PARSER_RESULT_SET
def get_p... | StarcoderdataPython |
1673629 | <reponame>hadifar/hazm
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import codecs
import os
import tempfile
from nltk.parse import DependencyGraph
from nltk.parse.api import ParserI
from nltk.parse... | StarcoderdataPython |
1751680 | from django.core.management.base import BaseCommand
import facebook
from common.models import Configuration
from meupet.models import Pet
class Command(BaseCommand):
"""
This command is not pretty at all, using the database for
these configurations is not the the best approach, but it
makes easier t... | StarcoderdataPython |
18873 | <reponame>ogero/Deluge-Manager-XBMC
import locale
from xml.sax import saxutils
defaultEncoding = locale.getdefaultlocale()[-1]
class Generator(saxutils.XMLGenerator):
"""Friendly generator for XML code"""
def __init__(self, out=None, encoding="utf-8"):
"""Initialise the generator
Just overr... | StarcoderdataPython |
3351442 | {% include 'misc/header.py' %}
"""Pytest fixtures and plugins for the UI application."""
from __future__ import absolute_import, print_function
import pytest
from invenio_app.factory import create_app as create_ui_api
@pytest.fixture(scope='module')
def create_app():
"""Create test app."""
return create_ui_... | StarcoderdataPython |
3345718 | <gh_stars>1-10
def sendall(socket, msg, objs=b""):
totalsent = 0
MSGLEN = len(msg)
while totalsent < MSGLEN:
sent = socket.send(msg[totalsent:].encode('utf-8'))
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
if objs... | StarcoderdataPython |
3392464 | <filename>database/database.py
import sqlite3
import json
class DatabaseInitializeError(BaseException):
""" Raised when the database can't be initialized properly """
pass
class SQLRollback(BaseException):
""" Raise this exception to rollback an SQLCursor operation """
pass
class SQLCursor:
""" C... | StarcoderdataPython |
3245519 | """
N-gram counting, discounting, interpolation, and backoff
Authors
* <NAME> 2020
"""
import itertools
# The following functions are essentially copying the NLTK ngram counting
# pipeline with minor differences. Written from scratch, but with enough
# inspiration that I feel I want to mention the inspiration sourc... | StarcoderdataPython |
3250172 | # Copyright 2020 University of New South Wales, University of Sydney, Ingham Institute
# 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
# Unle... | StarcoderdataPython |
3329456 | import autofixture
from django.test import TestCase
from reports.models import ReportItem, Report
class ReportItemTest(TestCase):
def setUp(self):
self.report = Report.objects.create(interval=1)
def test_not_seen_before(self):
report_item = autofixture.create_one(
ReportItem,
... | StarcoderdataPython |
3385528 | import copy
from glob import glob
import cv2
import os
import sys
import yaml
import matplotlib as mpl
import numpy as np
from skimage.io import imread
import matplotlib.pyplot as plt
from ellipses import LSqEllipse # The code is pulled from https://github.com/bdhammel/least-squares-ellipse-fitting
import time
from ma... | StarcoderdataPython |
3243524 | #!/usr/bin/env python
from pathlib import Path
from setuptools import setup, find_packages
from bookworm import app
# Invalid requirement specifier prefixes
INVALID_PREFIXES = ('http://', 'https://', 'git+',)
CWD = Path(__file__).parent
LONG_DESCRIPTION = (CWD / "README.md").read_text()
REQUIREMENTS = []
with ope... | StarcoderdataPython |
63641 | <filename>webstats/views.py<gh_stars>1-10
# Create your views here.
from __future__ import with_statement
from django.http import HttpResponse
from django.http import HttpRequest
import mimetypes
import os
import re
from stat import *
import urllib
from email.Utils import parsedate_tz, mktime_tz
from datetime... | StarcoderdataPython |
1667632 | import pickle
import datetime
from newspaper import Article
from googlesearch import search
from urllib.parse import urlparse
from dashboard.models import CropDetails, ExtraInfo
model = pickle.load(open('models/model.pkl', 'rb'))
def fetch_data(state,district):
season = get_season()
obj = CropDetails.objec... | StarcoderdataPython |
176845 | <gh_stars>0
import cherrypy
from cherrypy.process import servers
from motor_controller import start_motor_controller
class CarControlAPI:
def __init__(self, motor_controller):
self.motor_controller = motor_controller
cherrypy.engine.subscribe('stop', self.stop)
def stop(self):
self.mo... | StarcoderdataPython |
58202 | <reponame>matrix65537/lab<gh_stars>0
#!/usr/bin/env python
#coding:utf8
class Solution(object):
def permute(self, nums):
length = len(nums)
if length == 0:
return [[]]
rlists = [[nums[0]]]
for i in range(1, length):
tlists = []
for L in rlists:
... | StarcoderdataPython |
169378 | <gh_stars>0
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(2,GPIO.OUT)
GPIO.setup(3,GPIO.OUT)
GPIO.setup(4,GPIO.OUT)
GPIO.output(2, GPIO.LOW)
GPIO.output(3, GPIO.LOW)
GPIO.output(4, GPIO.LOW)
| StarcoderdataPython |
3228537 | <gh_stars>0
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/send', methods=['POST'])
def send_message():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
| StarcoderdataPython |
1779822 | import numpy as np
import matplotlib.pyplot
from pylab import *
import setOpt
import readOpt
import fit
class plotClass():
def __init__(self):
self.optFile="-"
"""
def simplePlot(self,dataFiles):
for f in dataFiles:
data=np.loadtxt(f)
x=data[:,0]
y=data[:,1]
plot(x,y)
savefig("plt.png")
show(... | StarcoderdataPython |
4823128 | import numpy as np
def plot_many_factors(photometry, low, high, shift, scale):
airmass = photometry['airmass'] / np.mean(photometry['airmass'])
x = photometry['xcenter'] / np.mean(photometry['xcenter'])
y = photometry['ycenter'] / np.mean(photometry['ycenter'])
comp_counts = photometry['comparison cou... | StarcoderdataPython |
3370236 | <gh_stars>0
from .tweets_analyzer import TweetsAnalyzer
| StarcoderdataPython |
3329814 | #Career Quiz
#KW '23
#This asks the person's name and stores it so I am resuse it when I tell them their results
print("Hello! Welcome to the Career Aptitude Test!")
name = input("Enter your name: ")
print("Hi " + name + "!")
print("I hope you have a fun time doing this quiz (:")
print("If the game breaks it's proba... | StarcoderdataPython |
103229 | import os
from collections import OrderedDict
# compatibility with python 2/3
try:
basestring
except NameError:
basestring = str
class EnvModifierError(Exception):
"""Env modifier error."""
class EnvModifierInvalidVarError(EnvModifierError):
"""Env modifier invalid var error."""
class EnvModifierInv... | StarcoderdataPython |
1605028 | # <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
This module adds the method toACE to the classes in the fudge.productData.distributions.energyAngularMC module.
"""
from... | StarcoderdataPython |
1691879 | #----------------------------------------------------------------------
# QuantumRaspberryTie.qiskit
# by KPRoche (<NAME>) (c) 2017,2018,2019,2020,2021
#
# Connect to the IBM Quantum Experience site via the QISKIT IBMQ functions
# run OPENQASM code on the simulator there
# Display the resu... | StarcoderdataPython |
3258688 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from __future__ import division
import numpy as np
import torch
import cv2
def project_pose(x, camera=None, **kwargs):
"""
Args
x: 3xN points in world coordinates
R: 3x3 Camera rotation matrix
T: 3x1 Camera trans... | StarcoderdataPython |
1622175 | <gh_stars>0
from ccontrol.types import NumberOfSteps
class DDPGConfig:
# Sampling
SKIP_FRAMES: int = 1
# Ornstein-Uhlenbeck noise generator
ADD_NOISE: bool = True
MU: float = 0.0
THETA: float = 0.13
SIGMA: float = 0.2
EPS_START = 6
EPS_END = 0
EPS_DECAY = 250 # Number of epis... | StarcoderdataPython |
4805930 | import datetime
import logging
from typing import Dict, Tuple
from ortools.sat.python import cp_model
from allocation.allocation_models import (
ALLOCATION_PRECISION,
AllocatedEvent,
AllocationData,
AllocationEvent,
AllocationOccurrence,
AllocationSpace,
)
logger = logging.getLogger(__name__)... | StarcoderdataPython |
3275735 | <reponame>gigaquads/pybiz<filename>examples/guards.py
from ravel import Application, Resource, String, Int, Id
from ravel.app.middleware import Guard, GuardMiddleware
class Exists(Guard):
"""
This guard ensures that a named action argument exists in the DAL.
"""
def __init__(self, arg: str):
... | StarcoderdataPython |
3361634 | <reponame>readthedocs-assistant/spinor-gpe
"""Base class for pseudospinor GPE propagation."""
import os
import shutil
import warnings
import numpy as np
from scipy.ndimage import fourier_shift
# from matplotlib import pyplot as plt
# import torch
from definitions import ROOT_DIR
# pylint: disable=import-error
import... | StarcoderdataPython |
1677138 | <gh_stars>10-100
import atexit
import os
from glob import glob
import ray
from kts.core.backend.address_manager import create_address_manager
from kts.core.backend.signal import create_signal_manager
from kts.settings import cfg
address_manager = None
signal_manager = None
heartbeat_handle = None
ray_session_filena... | StarcoderdataPython |
1781509 | <gh_stars>0
import pytest
import unittest
import pandas as pd
import numpy as np
from pipelines.schema import Schema
from pipelines.validators import RangeValidator, CategoryValidator, NonNegativeValidator
from fixtures.sample_schema import sample_features_metadata
sample_schema = Schema(sample_features_metadata)
on... | StarcoderdataPython |
1719327 | # -*- coding: utf-8 -*-
'''
Created on Oct 14, 2014
@author: Aaron
'''
import urllib2
from bs4 import BeautifulSoup
import re
import logging
from datetime import date
from time import localtime, strftime
import markup
import retry_decorator
team_abbrvs = ['ANA', 'ARI', 'BOS', 'BUF', 'CAR', 'CBJ', 'CGY', 'CHI', 'COL... | StarcoderdataPython |
4610 | # -*- coding: utf-8 -*-
#
from conans import python_requires
import conans.tools as tools
import os
base = python_requires("Eigen3ToPython/latest@multi-contact/dev")
class MCRTCDataConan(base.Eigen3ToPythonConan):
name = "mc_rtc_data"
version = "1.0.4"
description = "Environments/Robots description for m... | StarcoderdataPython |
3210596 | <filename>onlinejudge/aoj.py
# Python Version: 3.x
# -*- coding: utf-8 -*-
import onlinejudge.service
import onlinejudge.problem
from onlinejudge.problem import LabeledString, TestCase
import onlinejudge.dispatch
import onlinejudge.implementation.utils as utils
import onlinejudge.implementation.logging as log
import io... | StarcoderdataPython |
3235613 | <filename>unitology/tests/test_models.py
# -*- coding: utf-8 -*-
from django.test import TestCase
from django_dynamic_fixture import N
from unitology.models import UnitsFieldMixin
from unitology.variables import IMPERIAL, METRIC
from unitology.fields import WeightField, HeightField
class ModelM(UnitsFieldMixin):
... | StarcoderdataPython |
101049 | <gh_stars>0
import torch
from tqdm import tqdm
from utils import Logger, AverageMeter, accuracy
import numpy as np
def train(trainloader, model, criterion, optimizer):
# switch to train mode
model.train()
losses = AverageMeter()
top1 = AverageMeter()
top3 = AverageMeter()
top5 = AverageMeter... | StarcoderdataPython |
1790702 | import torch.nn.functional
import typing as _typing
import torch_geometric
from torch_geometric.nn.conv import GraphConv
from torch_geometric.nn.pool import TopKPooling
from torch_geometric.nn.glob import (
global_add_pool, global_max_pool, global_mean_pool
)
from ...encoders import base_encoder
from .. import base... | StarcoderdataPython |
193524 | #
# Call Option Pricing with Circular Convolution (General)
# 06_fou/call_convolution_general.py
#
# (c) Dr. <NAME>
# Derivatives Analytics with Python
#
import numpy as np
from convolution import revnp, convolution
from parameters import *
# Parmeter Adjustments
M = 3 # number of time steps
dt, df, u, d, q = get_bin... | StarcoderdataPython |
1667730 | <reponame>Kw4dr4t/maps_sqrt<gh_stars>0
import osmnx as ox
latitude = float(input('Latitude:'))
longitude = float(input('Longitude:'))
point = (latitude, longitude)
G = ox.graph_from_point(
point, dist=10000, retain_all=True, simplify=True, network_type="all"
)
u = []
v = []
key = []
data = []
for uu, vv, kkey, dd... | StarcoderdataPython |
1604559 | """
The agent provides a simple interface to policies in reinforcement
learning. It is assumed to be stateless, though stateful agents
can probably be added with a reset() method between rollouts.
"""
class Agent:
"""
An agent exposes two policies for acting in RL environments, an exploratory
and exploitat... | StarcoderdataPython |
3277045 | from statsmodels.regression.quantile_regression import QuantReg
import statsmodels.api as sm
class QuantileRegression:
"""Quantile regression wrapper
It can work on sklearn pipelines
Example
-------
>>> from sktools import QuantileRegression
>>> from sklearn.datasets import load_boston
>... | StarcoderdataPython |
4826819 | def mvs2texture(I):
"""
Converts a Multi View Stack tensor into a 3D texture
Parameters
----------
I : Tensor
a Multi View Stack tensor
Returns
-------
Tensor
a 3D texture tensor
"""
return I.permute(1, 0, 2, 3)
| StarcoderdataPython |
1629148 | <reponame>SaucyPigeon/ck3_mapdata<gh_stars>10-100
import pyradox
import pyradox.token
from pyradox.error import *
import os
import re
import warnings
""" Note that this is .yml as used in Paradox games and not canonical YAML. """
encodings = [
'utf_8_sig',
'cp1252',
]
# set of sources already read
alre... | StarcoderdataPython |
1756281 | import os
from google.cloud import bigquery
import datetime
from pprint import pprint
from google.cloud.exceptions import NotFound
from google.auth import credentials
TableSchemaDefinition = ['PassengerId:STRING', 'Pclass:INTEGER', 'Name:STRING', 'Sex:STRING', 'Age:STRING', 'SibSp:INTEGER',
'P... | StarcoderdataPython |
3313381 | import tensorflow as tf
class PiecewiseConstantDecayWithLinearWarmup(
tf.keras.optimizers.schedules.PiecewiseConstantDecay):
def __init__(self, warmup_learning_rate, warmup_steps, boundaries, values,
**kwargs):
super(PiecewiseConstantDecayWithLinearWarmup,
self).__in... | StarcoderdataPython |
1756410 | import json
import os
import sys
import subprocess
from datetime import datetime
def run_command(full_command):
proc = subprocess.Popen(full_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
try:
output = proc.communicate()
except:
pass
return b''.join(output).strip()... | StarcoderdataPython |
1609102 | import cv2
import numpy as np
import pickle
import constants
from PIL import Image, ImageTk
from tkinter import messagebox
import time
import util
cam = None
imgCrop = hist = None
pic = vstream = raw = None
def build_squares(img):
x, y, w, h = 450, 180, 13, 13
d = 10
imgCrop = None
x1, y1 = x, y
for i in range(1... | StarcoderdataPython |
94994 | <reponame>cablelabs/transparent-security<gh_stars>10-100
# Copyright (c) 2019 Cable Television Laboratories, 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/li... | StarcoderdataPython |
114707 | import os
import argparse
import numpy as np
import processors as pe
from paz.backend.camera import VideoPlayer
from paz.backend.camera import Camera
from demo_pipeline import DetectEigenFaces
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Real-time face classifier')
parser.add_argum... | StarcoderdataPython |
1729349 | <filename>Contents/Code/support/helpers.py<gh_stars>0
# coding=utf-8
import os
import traceback
import types
import unicodedata
import datetime
import urllib
import time
import re
import platform
import subprocess
from bs4 import UnicodeDammit
import chardet
from babelfish import Language
from subzero.analytics imp... | StarcoderdataPython |
1747026 | # Listing_16-1.py
# Copyright Warren & <NAME>, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# try to make a Pygame window appear
import pygame
pygame.init()
screen = pygame.display.set_mode([640, 480])
| StarcoderdataPython |
44077 | <filename>codes/d_agents/off_policy/sac/sac_agent.py
# https://spinningup.openai.com/en/latest/algorithms/sac.html
# https://github.com/pranz24/pytorch-soft-actor-critic
# https://github.com/ku2482/soft-actor-critic.pytorch/blob/master/code/agent.py
# https://github.com/cyoon1729/Policy-Gradient-Methods/blob/master/sac... | StarcoderdataPython |
3238921 | <filename>app/packages/widgets/circular_progress/__init__.py
# ///////////////////////////////////////////////////////////////
#
# BY: <NAME>
# PROJECT MADE WITH: Qt Designer and PySide6
# V: 1.0.0
#
# This project can be used freely for all uses, as long as they maintain the
# respective credits only in the Python scr... | StarcoderdataPython |
3399287 | <filename>externals/log.py
"""This module contains utility functions for logging to the server.
__authors__ = "<NAME>, <NAME>, <NAME>"
__credits__ = "Ma'ayan Lab, Icahn School of Medicine at Mount Sinai"
__contact__ = "<EMAIL>"
"""
DEBUG = True
def pprint(msg):
"""Prints message in debug mode. This function makes i... | StarcoderdataPython |
1789405 | class Token:
"""
Token i.e. a unit of some expression.
:param type:
Type of the token, provided as a :class:`~s2e2.TokenType`.
:param value:
String value of the token.
"""
def __init__(self, type, value):
"""
Constructor.
:param type:
Type ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.