id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
1895060 | <reponame>deepkick/PyRockSim<filename>py4science-master/src/chapter4/module_1.py
# ファイル名: module_1.py """
print("module_1 is imported.")
wgt = 60.5 # 初期体重 [kg]
def teacher(x):
if x > 60:
print("体重オーバーです")
else:
print("適正体重です")
| StarcoderdataPython |
278042 | <filename>chapter_8/D/resolve.py
def resolve():
'''
code here
'''
import collections
N = int(input())
A_list = [[int(item) for item in input().split()] for _ in range(N)]
A_list.sort(key=lambda x:x[0])
if __name__ == "__main__":
resolve()
| StarcoderdataPython |
1827770 | <reponame>optimor/reverse-proxy
from django import forms
from .models import ProxySite
class SelectSiteForm(forms.Form):
proxy_site = forms.ModelChoiceField(queryset=ProxySite.objects.all())
class Meta:
fields = ["proxy_site"]
class ProxySiteForm(forms.ModelForm):
class Meta:
model = P... | StarcoderdataPython |
119325 | <filename>trainer/__init__.py<gh_stars>1-10
from .train import train
from .preview import preview
from logging import NullHandler, getLogger
getLogger(__name__).addHandler(NullHandler())
| StarcoderdataPython |
6595946 | import os, time, shutil, datetime
from stat import S_ISDIR, S_ISREG
from sphinx.application import Sphinx
from sphinx.util.docutils import docutils_namespace, patch_docutils
from . import config
# class FileSnapshot:
# '''An object that represents a snapshot in time of a File'''
# def __init__(self, lastModifi... | StarcoderdataPython |
3239758 | from typing import Any, Dict
from boto3 import Session
from app import Remediation
from app.remediation_base import RemediationBase
@Remediation
class AwsDdbEncryptTable(RemediationBase):
"""Remediation that creates a KMS key and uses it to encrypt DDB table"""
@classmethod
def _id(cls) -> str:
... | StarcoderdataPython |
80898 | <reponame>noaa-ocs-hydrography/brute
from nbs.bruty.world_raster_database import *
def slow_process():
# slow_tif = r"C:\Data\\H13222_MB_50cm_MLLW_1of1_interp_1.csar.tif"
# slow_tif = r"\\nos.noaa\ocs\HSD\Projects\NBS\NBS_Data\PBG_Gulf_UTM14N_MLLW\NOAA_NCEI_OCS\BAGs\Manual\H13222_MB_50cm_MLLW_1of1_interp_1.csa... | StarcoderdataPython |
4967846 | import sys
import fandango as fd
assert sys.argv[1:], 'Start date required (e.g. 2017-08-01)'
tables = {
'att_array_devdouble_ro':'adr',
'att_array_devlong_ro':'alr',
'att_array_devshort_ro':'ahr',
'att_array_devstring_ro':'asr',
'att_array_devstate_ro':'atr',
'att_scalar_devdouble_ro':'sdr'... | StarcoderdataPython |
3329443 | <filename>auto_schema/host.py
import re
import sys
import time
from .bash import run
# NOTE: Hosts here are the same sense of instance.
# Meaning an actual host can have multiple of them
# Do not shutdown or general actions using this class on a
# multiinstance host
class Host(object):
def __init__(self, host, s... | StarcoderdataPython |
1892064 | <filename>model.py
from typing import Dict
from PySide2.QtCore import Signal, Slot, QObject, QTimer
import cv2, h5py, math
import numpy as np
import matplotlib.pyplot as plt
# YOLOv4 & DeepSORT code is taken from :
# https://github.com/theAIGuysCode/yolov4-deepsort
# deep sort imports
from deep_sort import preproces... | StarcoderdataPython |
4882133 | <filename>tests/test_storage_interface.py
import pytest
from chaosplt_scheduling.storage.interface import BaseSchedulingService
def test_cannot_instanciate_scheduling_interface():
try:
BaseSchedulingService()
except TypeError as e:
return
else:
pytest.fail("BaseSchedulingService sh... | StarcoderdataPython |
4912094 | <reponame>Meemaw/Eulers-Project<gh_stars>0
coins = [1,2,5,10,20,50,100,200]
#Testing inner function memoization
def memoizator(f):
tabela = dict()
def inner(a,b):
h = (a, tuple(b))
if h in tabela:
return tabela[h]
else:
tabela[h] = f(a,b)
return tabela[h]
return inner
@memoizator
def vseMoznosti(... | StarcoderdataPython |
5107135 | <reponame>Santhu15rsk/C110-TA
import plotly.figure_factory as ff
import plotly.graph_objects as go
import statistics
import random
import pandas as pd
import csv
df = pd.read_csv("data.csv")
data = df["temp"].tolist()
def random_set_of_mean(counter):
dataset = []
for i in range(0, counter):
random_ind... | StarcoderdataPython |
193970 | <filename>EnvMS/tests.py
# -*- coding: utf-8 -*-
# 测试环境管理API
# Created: 2016-7-27
# Copyright: (c) 2016<<EMAIL>>
from django.test import TestCase
| StarcoderdataPython |
3314186 | <reponame>GCerar/pysnesens
"""Python API for interaction with SNE-SENS-V1.1.0 sensor board.
Contains:
- (IC1) TMP75:
- (IC3) LPS331AP:
- (IC4) SHT21:
- (IC5) SI1143:
- (IC6) TCS3772:
- (IC7) ADMP521:
"""
from .sht21 import SHT21
from .lps331ap import LPS331AP
| StarcoderdataPython |
166597 | <gh_stars>0
from scowclient import ScowClient
import json
def listProcs():
sclient = ScowClient()
jsonObj = sclient.get('processDefinitions')
prettyPrintJson(jsonObj['processDefinitions'][0:4])
def prettyPrintJson(obj):
print json.dumps(obj, sort_keys=True, indent=4)
def main():
listProcs()
if... | StarcoderdataPython |
12820952 | <filename>bgjobs/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-25 16:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependenc... | StarcoderdataPython |
6617866 | <reponame>hadware/pyannote-audio
import numpy as np
import torch
from pyannote.audio.utils.permutation import permutate
def test_permutate_torch():
num_frames, num_speakers = 10, 3
actual_permutations = [
(0, 1, 2),
(0, 2, 1),
(1, 0, 2),
(1, 2, 0),
(2, 0, 1),
... | StarcoderdataPython |
4849346 | <reponame>Ventu012/P1_Facial_Keypoints
import torch
import torch.nn as nn
import torch.nn.functional as F
# can use the below import should you choose to initialize the weights of your Net
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## T... | StarcoderdataPython |
4822959 | import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import numpy as np
def track(df: pd.DataFrame,
curves: list = None,
lims: list = None,
clims: list = None,
dtick: bool = False,
scale: str ='linear',
curvetitle: str ='Track',
... | StarcoderdataPython |
286027 | <reponame>samir-nasibli/sdc
import os
import unittest
from sdc.tests.tests_perf.test_perf_utils import *
class TestBase(unittest.TestCase):
iter_number = 5
results_class = TestResults
@classmethod
def create_test_results(cls):
drivers = []
if is_true(os.environ.get('SDC_TEST_PERF_EXC... | StarcoderdataPython |
12804188 | import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
from config import *
def Querry(sql):
db = MySQLdb.connect(user=USERDATABASE, passwd=<PASSWORD>ABASE, host="localhost", db=DATABASE)
cursor, sql = db.cursor(), str(sql)
cursor.execute(sql)
db.commit()
data = cursor.fetchall()
db.close(... | StarcoderdataPython |
4825894 | <filename>raven/__init__.py
"""
raven
~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import os
import os.path
__all__ = ('VERSION', 'Client', 'get_version')
VERSION = '6.1.0.dev0'
def _get_gi... | StarcoderdataPython |
3356734 | <reponame>jacobic/redmapper
#!/usr/bin/env python
import os
import sys
import subprocess
import multiprocessing
import argparse
parser = argparse.ArgumentParser(description='Run multiple redmapper pixels on the same node')
parser.add_argument('-c', '--command', action='store', type=str, required=True, help='Command ... | StarcoderdataPython |
3262952 | from prometheus_client.registry import CollectorRegistry
from app.prom.metrics.general.io_stall import IOStall, NAME, READ, WRITE, STALL, QUEUED_READ, QUEUED_WRITE
def test_should_collect():
test_data_1 = {NAME: 'test_1', READ: 300, WRITE: 100, STALL: 500, QUEUED_READ: 100, QUEUED_WRITE: 100}
test_data_2 = {... | StarcoderdataPython |
1600528 | from reliapy._messages import *
from scipy.stats import norm
import numpy as np
from reliapy.math import spectral_decomposition, cholesky_decomposition
class Random:
"""
``Random`` simple random sampling.
**Input:**
* **distribution_obj** (`object`)
Object of ``JointDistribution``.
**Att... | StarcoderdataPython |
5070477 | <reponame>Christovis/wys-ars<filename>src/astrild/rays/voids/tunnels/gadget.py
import os.path
import numpy as np
from astrild.rays.voids.tunnels.miscellaneous import (
throwError,
throwWarning,
charToString,
)
GadgetFileType = {1: "Gadget1", 2: "Gadget2", 3: "HDF5", -1: "Unknown"}
class GadgetParticles:... | StarcoderdataPython |
9673899 | #!/usr/bin/env python3
import json
def vc_value_str(config, ratio_dict):
if "worker_sku_cnt" not in config or "sku_mapping" not in config:
print(
"Warning: no default value would be added to VC table. Need to manually specify"
)
return "", "", [], ""
worker_sku_cnt, sku_ma... | StarcoderdataPython |
5005715 | <filename>scripts/matchingbio.py
#!/usr/bin/env python3
import sys
def argparser():
from argparse import ArgumentParser
ap = ArgumentParser()
ap.add_argument('file1')
ap.add_argument('file2')
return ap
def process_streams(f1, f2, options):
matched, total = 0, 0
sent1, sent2 = [], []
... | StarcoderdataPython |
6619742 | <gh_stars>1-10
# =========================================================================
# Copyright 2020 <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/... | StarcoderdataPython |
3296560 | <gh_stars>0
# !/usr/bin/python3
# -*- coding:utf-8 -*-
# @File: __init__.py.py
# @Author: BradyHu
# @Email: <EMAIL>
# @Time: 2022/2/8 上午9:17
from .base import * | StarcoderdataPython |
3260539 | <reponame>jimmeak/graveyard
from django import forms
from django.core.validators import MinLengthValidator
from ddcz.notifications import Audience
class News(forms.Form):
text = forms.CharField(
label="",
widget=forms.Textarea(
attrs={"class": "comment__textarea", "cols": 80, "rows": ... | StarcoderdataPython |
185519 | class BeeSQLError(Exception):
pass
| StarcoderdataPython |
6532374 | <reponame>CoderLeague/research_aiohttp
import io
import json
import mimetypes
import os
import warnings
from abc import ABC, abstractmethod
from multidict import CIMultiDict
from . import hdrs
from .helpers import (PY_36, content_disposition_header, guess_filename,
parse_mimetype, sentinel)
from... | StarcoderdataPython |
11367837 | <filename>Model1/image_loader.py
# 数据处理
import os
import torch
from torch.utils import data
from PIL import Image
import numpy as np
from torchvision import transforms
#不管传进来的什么图,直接先切成100*100然后随机旋转
img_transform = transforms.Compose([
transforms.RandomCrop(100),
transforms.RandomHorizontalFlip(),
... | StarcoderdataPython |
4906266 | # -*- coding: utf-8 -*-
"""
lantz.drivers.ni.daqmx
~~~~~~~~~~~~~~~~~~~~~~
Implements bindings to the DAQmx (windows) National Instruments libraries.
Sources::
- DAQmx Reference manual
- DAQmx Base Reference manual
- pylibnidaqmx
http://pylibnidaqmx.googlecode.com
... | StarcoderdataPython |
325689 | # Copyright 2018 <NAME>
#
# Licensed under the 3-clause BSD license. See the LICENSE file.
class InvalidPackageNameError(Exception):
"""Invalid package name or non-existing package."""
def __init__(self, frontend, pkg_name):
self.frontend = frontend
self.pkg_name = pkg_name
def __str... | StarcoderdataPython |
8000698 | <reponame>arithmetic1728/ssl_grpc_example<filename>service_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import service_pb2 as service__pb2
class ServerStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
... | StarcoderdataPython |
4821020 | # Entrada de dados
Celsius = float(input('\033[34mInforme a temperatura em celsius(ºC) :'))
# Processamento
Fahrenheit = ((9 * Celsius) / 5) + 32
Kelvin = ((Celsius * 5) / 5)
# Saída de dados
print('A Temperatura em fahrenheit é {:.1f} ºF'.format(Fahrenheit))
print('A Temperatura em kelvin é {:.1f} ºK'.format(Kelvin))
| StarcoderdataPython |
11296268 | CONSTRAINT_DICT_IN = \
{
"contextName": "appName",
"operator": "IN",
"values": [
"test",
"test2"
]
}
CONSTRAINT_DICT_NOTIN = \
{
"contextName": "appName",
"operator": "NOT_IN",
"values": [
"test",
"test... | StarcoderdataPython |
4900030 | <gh_stars>0
from django.apps import AppConfig
import stripe
from .conf import settings
class DjangoStripeConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'django_stripe'
def ready(self):
stripe.api_key = settings.STRIPE_SECRET_KEY
stripe_app_data = settings.... | StarcoderdataPython |
3377776 | from pathlib import Path
from typing import List, Optional, Union, NamedTuple, Iterable
import importlib
import importlib.util
import warnings
import pytz
from .common import PathIsh, get_tmpdir, appdirs, default_output_dir
from .common import Res, Source
class Config(NamedTuple):
# TODO remove default from sou... | StarcoderdataPython |
11249048 | import json
def output(videos, courseName):
"""
Write results of analysis to json file.
:param videos:
:param courseName:
:return:
"""
fileName = courseName + '_video_statistics.json'
with open(fileName, "w") as out:
courses = set()
for video in videos:
cou... | StarcoderdataPython |
12862439 | <gh_stars>1-10
# Generated by Django 3.0.8 on 2020-07-28 12:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0004_product_product_image'),
]
operations = [
migrations.AddField(
model_name='product',
nam... | StarcoderdataPython |
193198 | <gh_stars>1-10
# Impacket - Collection of Python classes for working with network protocols.
#
# SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more... | StarcoderdataPython |
293446 | # -*- coding: utf-8 -*-
from collections import Counter
from pathlib import Path
def total_answers( forms ):
total_yes = 0
group_answers = set( )
for form in forms:
if form:
group_answers = group_answers.union( form )
else:
total_yes += len( group_answers )
... | StarcoderdataPython |
183987 | from django.apps import AppConfig
class IndigoConfig(AppConfig):
name = "indigo"
| StarcoderdataPython |
5158803 | <gh_stars>1-10
#!/usr/bin/python3
from control import PidController
class SonicController():
kP = 0.2
kI = 0
kD = 0.01
done = False
def __init__(self, target):
self.target = target
self.pid = PidController(self.kP, self.kI, self.kD, flipSign=True)
def calculate(self, dista... | StarcoderdataPython |
1675794 | """Unit test package for install_webdrivers."""
| StarcoderdataPython |
11296737 | # Escreva um programa que leia um valor em metros
# e o exiba convertido em centímetros e milímetros.
meters = int(input('Digite a medida em metros: '))
print('Em kilometros: {}km'.format(meters / 100))
print('Em metros: {}m'.format(meters))
print('Em centímetros: {}cm'.format(meters * 100))
print('Em milímetros: {}mm... | StarcoderdataPython |
3372819 | <filename>four_sum.py
class Solution(object):
@staticmethod
def kSum(nums, k, start, target):
result = list()
# if nums[start] * k > target or nums[-1] * k < target:
# return result
if k == 2:
left, right = start, len(nums) - 1
while left < right:
... | StarcoderdataPython |
3207419 | <gh_stars>0
# services/web/server/main/views.py
try:
from pyspark import SparkContext, SparkConf,SQLContext
from pyspark.sql.functions import to_date,lit,desc,col
from pyspark.sql import Row
from operator import add
from server.main.utils import get_requireddataframe_fromcsv
import sys
except:... | StarcoderdataPython |
9665642 | <gh_stars>0
# Generated by Django 3.0.5 on 2020-04-14 13:33
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20200406_1646'),
]
operations = [
migrations.AlterField(... | StarcoderdataPython |
250005 | from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import sys
from time import time
from os import makedirs, path
from psychrnn.backend.regularizations import Regularizer
from psychrnn.backend.loss_functions import LossFunction
from psychrnn.backend.initi... | StarcoderdataPython |
8110823 | <reponame>sebasrp/yaticker
import socket
import textwrap
from tempfile import NamedTemporaryFile
import requests
from matplotlib.image import imread
from PIL import Image, ImageDraw, ImageFont
def is_connected(url="http://www.google.com/", timeout=3):
try:
requests.head(url, timeout=timeout)
retu... | StarcoderdataPython |
12807587 | <reponame>mgrsantox/nmmis<filename>nmmis/contrib/municipal/migrations/0004_auto_20200723_1714.py
# Generated by Django 3.0.8 on 2020-07-23 11:29
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('municipal', '0003_auto_20... | StarcoderdataPython |
11228392 | <gh_stars>0
from tests import *
from naxxatrapy.naxxatrapy import average_velocity
class TestAverageVelocity(unittest.TestCase):
def test_average_velocity(self):
self.assertEqual(average_velocity(), ...)
| StarcoderdataPython |
1770251 | """
This implements a model of mesolimbic dopamine cell activity during monkey
conditioning as found in `Montague, Dayan, and Sejnowski (1996) in PsyNeuLink
<http://www.jneurosci.org/content/jneuro/16/5/1936.full.pdf>`_
"""
import argparse
import numpy as np
import psyneulink as pnl
all_figures = ['5a', '5b', '5c']
... | StarcoderdataPython |
3501101 | <filename>setup.py
from setuptools import setup
from setuptools.command.install import install
from setuptools.command.develop import develop
import subprocess
from os.path import join
description = 'A toolkit to work with the Oriented Bounding Boxes annotation ' \
'schema for datasets.'
def build_wit... | StarcoderdataPython |
4919572 | # Generated by Django 3.2.2 on 2021-05-11 20:28
import datetime
from django.db import migrations
from django.utils.timezone import utc
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
("jobs", "0006_auto_20210511_2322"),
]
operations = [
... | StarcoderdataPython |
1739968 | <filename>rdisq/request/receiver.py<gh_stars>1-10
from typing import *
from rdisq.consts import RECEIVER_SERVICE_NAME
from rdisq.configuration import get_rdisq_config
from rdisq.payload import SessionResult
from rdisq.request.message import RdisqMessage
from rdisq.request.dispatcher import RequestDispatcher
from rdisq... | StarcoderdataPython |
5177671 | from zope import component
from zope import interface
import importlib
from hashlib import md5
import mellon
from scrapy.linkextractors import LinkExtractor
import scrapy.spiders
try:
from urllib import parse
except ImportError:
import urlparse as parse # Py2
from sparc.configuration import container
from mell... | StarcoderdataPython |
3571093 | <reponame>LudditeLabs/autodoc-tool<gh_stars>0
# Copyright 2018 Luddite Labs 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 requ... | StarcoderdataPython |
254439 | # Copyright 2020 Microsoft Corporation
#
# 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... | StarcoderdataPython |
6625162 | <reponame>rqssouza/opencv-gui-parameter-tuner<gh_stars>1-10
#!/bin/env python3
import cv2 as cv
import numpy as np
import argparse
import tuner.tuner as tuner
def mag(gradient_x, gradient_y):
gradient_mag = np.sqrt(np.square(gradient_x) + np.square(gradient_y))
return np.uint8(255 * (gradient_mag / np.max(gr... | StarcoderdataPython |
6652621 | <reponame>rogerio-ignacio-developer/formulas-github
#!/usr/bin/python3
import os
from formula import formula_horusec
from formula import formula_superlinter
from formula import formula_dependabot
def run(project_path, workflows, new_branch, new_branch_name):
try:
current_pwd = os.environ.get("CURRENT_PWD"... | StarcoderdataPython |
8057873 | <reponame>msklarek/CodeWars-Python-Solutions
def digital_root(n):
a = str(n)
suma = 0
while len(a) > 1:
arr = []
for i in range(len(a)):
arr.append(a[i])
suma = 0
for j in range(len(arr)):
suma = suma + int(arr[j])
a = str(suma)
return ... | StarcoderdataPython |
103186 | import numpy as np
import pandas as pd
from typing import List
from .phantom_class import Phantom
class Beam:
"""A class used to create an X-ray beam and detector.
Attributes
----------
r : np.array
5*3 array, locates the xyz coordinates of the apex and verticies of a
pyramid shaped X... | StarcoderdataPython |
269685 | #Copyright ReportLab Europe Ltd. 2000-2016
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/enums.py
__version__='3.3.0'
__doc__="""
Container for constants. Hardly used!
"""
TA_LEFT = 0
TA_CENTER = 1
TA_RIGHT = 2
TA_JUSTIFY = 4 | StarcoderdataPython |
5069586 | import requests
from bs4 import BeautifulSoup
from menus.menu import Menu
class Edison(Menu):
def __init__(self):
super().__init__()
self.url = 'http://restaurangedison.se/lunch'
self.dow = {
0: 'monday',
1: 'tuesday',
2: 'wednesday',
3: 'th... | StarcoderdataPython |
305677 | from .Test import add
from .QuitWarning import warning
from .Email import email
| StarcoderdataPython |
8035767 | import numpy as np
from matplotlib import pyplot as plt, colors, cm
from sklearn import decomposition, manifold
def plot_with_pca(X, assigned_cluster_numbers, point_labels, features_count, coeff_labels):
pca = decomposition.PCA(n_components=2)
principal_components = pca.fit_transform(X)
scatter_points(ass... | StarcoderdataPython |
231769 | <reponame>ctc316/algorithm-python<gh_stars>0
class Solution:
"""
@param s: A string
@return: the length of last word
"""
def lengthOfLastWord(self, s):
return len(s.strip().split(" ")[-1]) | StarcoderdataPython |
11201453 | from tkinter import *
import sqlite3
from tkinter import messagebox
root = Tk()
root.title("Fantasy Cricket")
root.geometry("680x490")
root.resizable(width=FALSE, height=FALSE)
root.configure(background='#FFFFFF')
# -----------Show Root win in center--------------
def center(win):
win.update_idletasks... | StarcoderdataPython |
5042706 | # This initializes the problem class for SWE
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D
from parameters import Nx, Ny, Lx, Ly
from parameters import rho, grav, dt, dx, dy, ft
from parameters import K
from parameters import plot_viz, num_st... | StarcoderdataPython |
8089771 | <reponame>fananchong/go-xclient<filename>pyclient/main.py
#! python3
import wx
import config
import user
import login_window
import log
if __name__ == "__main__":
args, cfg = config.load_config()
usr = user.User(args, cfg).init()
log.init(cfg["logfile"])
app = wx.App(False)
login_window.new(usr, a... | StarcoderdataPython |
5183265 | import functools
import os
import sys
import threading
import pkg_resources
from .executor import Context, Tasks, TaskError
from .paths import in_dir, paths_for_shell
tasks = Tasks()
@tasks.register('dependencies', 'additional_assets', 'bundles', 'collect_static_files',
'take_screenshots', 'compile... | StarcoderdataPython |
3550696 | <reponame>octoenergy/oliver-twist
from dataclasses import dataclass
from enum import Enum
from json import JSONEncoder
from typing import List
class MyEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
@dataclass
class ReportStatus(str, Enum):
PASSED = "passed"
SKIPPED = "skipped"
... | StarcoderdataPython |
1759103 | <filename>AI/csv_data.py
# This script provides a way for the different models to access the training and testing data
# Created by: <NAME>(KCL)
import pandas as pd
import torch
import math
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.preprocessing import MinMaxScaler
class Dat... | StarcoderdataPython |
4933445 | <reponame>hknerdgn/theanets<gh_stars>1-10
'''This package groups together a bunch of theano code for neural nets.'''
from .dataset import Dataset
from .main import Experiment
from .feedforward import Network, Autoencoder, Regressor, Classifier
from . import flags
from . import layers
from . import recurrent
from . i... | StarcoderdataPython |
9717723 | from decimal import Decimal
import requests
from cryptoportfolio.interfaces.base import Address
class F2PoolWallet(Address):
decimal_places = 18
symbol = None
f2pool_currecnices_mapping = {
'bitcoin': "BTC",
'litecoin': "LTC",
'etc': "ETC",
'eth': "ETH",
'zec': "... | StarcoderdataPython |
8103819 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Power by <NAME> 2020-10-24 13:53:35
import os
import cv2
import torch
import numpy as np
from pathlib import Path
from utils import batch_PSNR, batch_SSIM
from skimage import img_as_float32, img_as_ubyte
from networks.derain_net import DerainNet
os.environ['CUDA_DEVICE_O... | StarcoderdataPython |
5156612 | import FWCore.ParameterSet.Config as cms
from RecoVertex.Configuration.RecoVertex_cff import unsortedOfflinePrimaryVertices, trackWithVertexRefSelector, trackRefsForJets, sortedPrimaryVertices, offlinePrimaryVertices, offlinePrimaryVerticesWithBS,vertexrecoTask
from RecoVertex.PrimaryVertexProducer.TkClusParameters_cf... | StarcoderdataPython |
4815950 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.3.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# +
# https://github.com/... | StarcoderdataPython |
11221614 | # https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
low, high = 0, len(nums)-1
first = self.fi... | StarcoderdataPython |
1844567 | <reponame>zj-zhang/inDelphi-model
"""
Run each component of inDephi to understand its inputs/outputs
"""
# zzjfrank, 2020-10-11
from inDelphi import init_model, predict
# the example sequence in inDelphi webserver
left = 'GCAGTCAGTGCAGTAGAGGATGTGTCGCTCTCCCGTACGGCGTGAAAATGACTAGCAAAG'
right = 'TTGGGGCCTTTTTGGAAGACCTAG... | StarcoderdataPython |
11379481 | <gh_stars>0
"""
Write a Python program to read first n lines of a file.
"""
from itertools import islice
def read_line_numbers(file_name, line_no):
with open(file_name) as file:
for line in islice(file, line_no):
print(line)
read_line_numbers("main.txt", 2) | StarcoderdataPython |
20473 | import tensorflow as tf
import numpy as np
def euclidean_dist(x, y):
return np.linalg.norm(x - y)
def limit_gpu():
gpus = tf.config.list_physical_devices('GPU')
if gpus:
try:
tf.config.set_logical_device_configuration(
gpus[0],
[tf.config.Logic... | StarcoderdataPython |
1866443 | <filename>ledger/basket/admin.py<gh_stars>10-100
from oscar.apps.basket.admin import * # noqa
| StarcoderdataPython |
5117787 | """Test script to send control messages to a MQTT topic."""
import datetime
import json
import logging
import logging.config
import os
import time
from picamera_mqtt.mqtt_clients import AsyncioClient, message_string_encoding
from picamera_mqtt.protocol import (
connect_topic, control_topic, deployment_topic, imag... | StarcoderdataPython |
3413069 | <gh_stars>0
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import re
from copy import deepcopy
from operator import itemgetter
from math import sqrt
import ROOT
from PyAnalysisTools.base import _logger, InvalidInputError
import PyAnalysisTools.Plotti... | StarcoderdataPython |
303760 | # coding: utf-8
from ._base import BaseForm
from collipa.libs.tforms import validators
from collipa.libs.tforms.fields import TextField, TextAreaField, PasswordField
from collipa.libs.tforms.validators import ValidationError
from collipa.models import User, Message
from collipa import config
from pony import orm
cl... | StarcoderdataPython |
8066768 | from django.contrib import admin
from .models import News
admin.site.register(News) | StarcoderdataPython |
4830863 | <filename>lagury/client/algorithms/run_task.py
import sys
import json
import importlib
from lagury.client.models import Task
if __name__ == '__main__':
data = json.loads(sys.argv[1])
input_dirs = data['input_dirs']
output_dir = data['output_dir']
parameters = data['parameters']
class_path = par... | StarcoderdataPython |
11341407 | <reponame>HiroseTomoyuki/sge3<gh_stars>1-10
import random
import sge.grammar as grammar
def crossover(p1, p2):
xover_p_value = 0.5
gen_size = len(p1['genotype'])
mask = [random.random() for i in range(gen_size)]
genotype = []
for index, prob in enumerate(mask):
if prob < xover_p_value:
... | StarcoderdataPython |
4826683 | <filename>tests/test_field.py
from hcipy import *
import numpy as np
import copy
def test_field_dot():
grid = make_pupil_grid(2)
a = np.random.randn(3, grid.size)
A = np.random.randn(3, 3, grid.size)
a = Field(a, grid)
A = Field(A, grid)
b = field_dot(A, a)
bb = np.array([A[...,i].dot(a[...,i]) for i in rang... | StarcoderdataPython |
222098 | # coding: utf-8
#
# Copyright (c) 2020-2021 Hopenly srl.
#
# This file is part of Ilyde.
#
# 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
#
#... | StarcoderdataPython |
4883272 | from unittest import TestCase
from func_prog.pipe import (
func_pipe, pipe_class,
chain_pipe, map_pipe,
filter_pipe, reduce_pipe
)
def add_1(value):
return value + 1
def add_tuple_1(values):
return tuple([v + 1 for v in values])
def sum_all(x, y, z):
return x + y + z
class TestFuncPipe(... | StarcoderdataPython |
1820403 | # -*- coding: utf-8 -*-
import os
import sys
import time
import urllib2
import threading
from datetime import datetime
from unittest import TestCase
cwd = os.path.dirname(os.path.abspath(__file__))
sys.path.append(cwd)
if os.name == "nt":
cwd = cwd.decode("cp1251").encode("utf8")
from trassir_script_framework i... | StarcoderdataPython |
4868525 | <reponame>usgs/geomag-algorithms<gh_stars>10-100
#! /usr/bin/env python
from os import path
import sys
# ensure geomag is on the path before importing
try:
import geomagio # noqa (ignores this line for lint purposes.)
except ImportError:
script_dir = path.dirname(path.abspath(__file__))
sys.path.append(p... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.