id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
3479449 | # Lesson5: writing to a file
# source: code/file_write.py
with open('test.txt', 'w') as f:
f.write('Hello World!\n')
| StarcoderdataPython |
11333810 | from flask import Flask, render_template
from flask import jsonify
from flask import request
from SentimentNet import SentimentAnalyzer
SN = SentimentAnalyzer(cuda=False)
app = Flask(__name__)
@app.route("/sentiment", methods=['GET','POST'])
def sentiment():
if request.method=="GET":
sent = request.args.g... | StarcoderdataPython |
366912 | <reponame>digital-land/view-builder<filename>view_builder/organisation_loader.py<gh_stars>0
import csv
from view_builder.model.table import Organisation, Entity
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from datetime import date
def load_organisations(path):
engine = create_engine("s... | StarcoderdataPython |
11251589 | #!/usr/bin/env python3
# import lib
import socket
import struct
# communication: control <-> infection server
#
# 0 1 5 n
# +----------------------------------------------------------------------------------------+
# | | ... | StarcoderdataPython |
9790890 | # Copyright 2017 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.
from telemetry import decorators
from telemetry.internal.actions import action_runner as action_runner_module
from telemetry.testing import tab_test_case
c... | StarcoderdataPython |
1757718 | <filename>tests/test_base_transforms.py
import solt.transforms as slt
import solt.core as slc
import numpy as np
import pytest
import sys
import inspect
import torch
from .fixtures import *
def get_transforms_solt():
trfs = []
for name, obj in inspect.getmembers(sys.modules["solt.transforms"]):
if in... | StarcoderdataPython |
1859188 | <reponame>jorgenwh/npstructures<filename>profiling/counter.py
import numpy as np
import cProfile
import pstats
from npstructures import RaggedArray, Counter
import time
N=5
hashes = (np.load(f"/home/knut/Sources/kmer_mapper/h{i}.npy") for i in range(N))
ragged = RaggedArray.load("profiling/.fullragged.npz")
#agged = Ra... | StarcoderdataPython |
3498357 | """
*Natural Logarithm*
"""
from dataclasses import dataclass
import jax.numpy as jnp
from ._operator import Logarithm
__all__ = ["NaturalLogarithm"]
@dataclass
class NaturalLogarithm(
Logarithm,
):
operator = jnp.log
| StarcoderdataPython |
3204238 | <reponame>mkinsner/llvm
"""Show bitfields and check that they display correctly."""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class CppBitfieldsTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@no_debug_info_tes... | StarcoderdataPython |
1890914 | <reponame>stetsonbost/MediaSocial<filename>MediaSocial/catalog/migrations/0006_auto_20180413_1527.py
# Generated by Django 2.0.3 on 2018-04-13 22:27
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
d... | StarcoderdataPython |
1688011 | <filename>2021/day16.py
from __future__ import annotations
from dataclasses import dataclass
import functools
from aoc_tools import grouper
@dataclass
class Packet:
version: int
typ: int
val: int | list[Packet]
@classmethod
def from_file(cls, fobj):
version = fobj.read_bits(3)
t... | StarcoderdataPython |
3382165 | """
.. module:: SimpleConsensusClustering
SimpleConsensusClustering
*************
:Description: SimpleConsensusClustering
:Authors: bejar
:Version:
:Created on: 22/01/2015 10:46
"""
__author__ = 'bejar'
import numpy as np
from sklearn.base import BaseEstimator, ClusterMixin, TransformerMixin
from ... | StarcoderdataPython |
211373 | import re
import quopri
class SignupHelper:
def __init__(self, app):
self.app = app
def new_user(self, username, email, password):
wd = self.app.wd
wd.get(self.app.config['web']['baseUrl'] + "/signup_page.php")
wd.find_element_by_name("username").click()
wd.find_eleme... | StarcoderdataPython |
1661456 | class Biblioteca:
def chama_metodo_interface(self):
self.metodo_interface()
| StarcoderdataPython |
371488 | <reponame>BigShuang/Sort-Animation
#usr/bin/env python
#-*- coding:utf-8- -*-
FPS = 60 # 游戏帧率
QUICKFPS = 60
SLOWFPS = 15
WIN_WIDTH = 800 # 窗口宽度
WIN_HEIGHT = 980 # 窗口高度
BUBBLE_SPACE = 40
INIT_R = 10
DR = 4
NUMBER = 10
COLORS = {
"bg": (240, 255, 255), # 背景颜色
"bubble": (135, 206, 235),
# "select": (1... | StarcoderdataPython |
5072290 | """
A Python parser for Org mode files.
"""
__all__ = ['OrgTree', 'orgTreeFromFile'] # Seems equal to the stuff in ".tree" below
from .tree import OrgTree, orgTreeFromFile
from . import const, utils
| StarcoderdataPython |
3264627 | <filename>RecoBTag/Combined/test/writeGBRForests_cfg.py
import FWCore.ParameterSet.Config as cms
process = cms.Process("writeGBRForests")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1) # NB: needs to be set to 1 so that GBRForestWriter::analyze method gets called exactly once
)
process.so... | StarcoderdataPython |
5008607 | <gh_stars>0
import turtle
class Score:
def __init__(self, coordinates, font):
self.__count = 0
self.__coordinates = coordinates
self.__font = font
self.__pen = turtle.Turtle()
def init_score(self):
self.__pen.goto(*self.__coordinates)
self.__pen.hideturtle()
... | StarcoderdataPython |
100679 | import itertools
from unittest import skip
from django.core import urlresolvers
from rest_framework.test import APIClient, APIRequestFactory
from rest_framework.test import APITestCase, force_authenticate
from api.tests.factories import (
UserFactory, AnonymousUserFactory, IdentityFactory, ProviderFactory, Allocat... | StarcoderdataPython |
3592535 | <filename>backend/notifications/forms.py
from django import forms
from django.utils.safestring import mark_safe
class NewsletterForm(forms.Form):
email = forms.EmailField(label="Email Address")
class ContactForm(forms.Form):
name = forms.CharField(label="Name", max_length=255)
email = forms.EmailField(l... | StarcoderdataPython |
3513139 | from .lightning import Lightning
from .customer import Customer
from .onchain import Onchain
from .wallet import Wallet
from .base import webhook_verification
| StarcoderdataPython |
9604874 | import random
import os
import time
import capnp
import matplotlib.pyplot as plt
import numpy as np
from dist_zero import cgen
def test_pass_buffer_c_to_python():
program = cgen.Program(name='simple_buffer_perf_test')
globalBuf = program.AddDeclaration(cgen.Char.Star().Var('global_buffer'))
nGlobalBufBytes... | StarcoderdataPython |
6659121 | """Define tests for the QNAP QSW init."""
from unittest.mock import patch
from homeassistant.components.qnap_qsw.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from .util import CONFIG
from tests.common import MockConfigEntry
async def te... | StarcoderdataPython |
5079878 |
# i used some ideas from CodePylet https://www.youtube.com/watch?v=osDofIdja6s&t=1038s
# i also borrowed pretty much all of this from kids can code - thanks!
# on acceleration https://www.khanacademy.org/science/physics/one-dimensional-motion/kinematic-formulas/v/average-velocity-for-constant-acceleration
# on vector... | StarcoderdataPython |
9791849 | <filename>preprocess.py
import numpy
import cv2
RAW_SHAPE = (160, 320, 3)
def preprocess(image):
assert(image.shape == RAW_SHAPE)
image = crop(image)
image = resize(image)
image = standardize(image)
return numpy.array(image, dtype='float32')
def crop(image):
return image[50:-30,:,:]
def r... | StarcoderdataPython |
1655384 | from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from loginmodule.models import Login
@csrf_exempt
def login(request):
print ("buhuuu")
for key in request.POST:
print(key)
value = request.POST[key]
print(value)
use... | StarcoderdataPython |
5198272 | """
Small library for providing unique identifier to similar exceptions
1) we check just filename and function name
2) we don't check line numbers because they often change e.g. by unrelated changes
3) we check exception type but not message as the message can often differ for similar problems
the code is public-doma... | StarcoderdataPython |
142418 | <gh_stars>1-10
from django.shortcuts import redirect
def unauthenticated_user_only(view_func):
def wrapper(request):
if request.user.is_authenticated:
return redirect('index')
return view_func(request)
return wrapper
def authenticated_user_only(view_func):
def wrapper(request... | StarcoderdataPython |
1762892 | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import google.protobuf.empty_pb2 as google_dot_protobuf_dot_empty__pb2
import pysolveengine.svc_jobs_pb2 as svc__jobs__pb2
class JobStub(object):
"""A service for creating new jobs with the solveEngine
"""
def __init__(self, cha... | StarcoderdataPython |
99777 | from tkinter import *
import time
import random
root = Tk()
root.title("bb")
root.geometry("450x570")
root.resizable(0, 0)
root.wm_attributes("-topmost", 1)
canvas = Canvas(root, width=600, height=600, bd=0, highlightthickness=0, highlightbackground="white", bg="Black")
canvas.pack(padx=10, pady=10)
score ... | StarcoderdataPython |
6415639 | <gh_stars>0
import os
import logging
TEST_FLAG = os.environ.get("TEST_FLAG")
environment = os.environ.get("environment")
def determine_environment (environment):
logging.info("The environment is " + environment)
if TEST_FLAG == "true" and environment != "bad":
if os.system("vagrant up unit_test") !=0:... | StarcoderdataPython |
331896 | import numpy as np
import matplotlib.pyplot as pl
import pysir
import time
from tqdm import tqdm
l = [['200,201',-500,10,1500]]
SIR = pysir.SIR(l)
psf = np.loadtxt('PSF.dat', dtype=np.float32)
SIR.set_PSF(psf[:,0].flatten(), psf[:,1].flatten())
out = np.loadtxt('model.mod', dtype=np.float32, skiprows=1)[:,0:8]
out = ... | StarcoderdataPython |
11202051 | <reponame>AsafBarZvi/MSc_project
import time
import numpy as np
class Timer:
def __init__(self,name):
self._name = name
self._tstarts = []
self._tends = []
def __enter__(self):
if len(self._tstarts) < 3000:
self._tstarts.append(time.time())
return self
... | StarcoderdataPython |
6419410 | <filename>teacher/models.py
from django.db import models
# from subject.models import Subject
from department.models import Department
# Create your models here.
class Teacher(models.Model):
name= models.CharField(max_length=200)
teacher_bio= models.TextField(max_length=5000)
# subject = models.OneToOneFi... | StarcoderdataPython |
9756712 | <filename>tests/basics/bool1.py
# tests for bool objects
# basic logic
print(not False)
print(not True)
print(False and True)
print(False or True)
# unary operators
print(+True)
print(-True)
| StarcoderdataPython |
6694339 | <gh_stars>100-1000
from specs import BaseTest
class IndexesTest(BaseTest):
def setUp(self):
super().setUp()
self.helper_indexes_testdata_prepare()
def test_get_indexes(self):
"""Should be able to get indexes list"""
status, body = self.api_get_indexes(self.current_db, self.c... | StarcoderdataPython |
8155634 | from client_of_redundant_servers.client_of_redundant_ad_ldap_servers import ClientOfRedundantAdLdapServers
from client_of_redundant_servers.client_of_redundant_servers import AllAvailableServersFailed
from collections import OrderedDict
LDAP_SERVERS = OrderedDict()
LDAP_SERVERS['srvr-dc1.myad.private.example.com'] = {... | StarcoderdataPython |
1643273 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 10 17:48:34 2020
@author: rcard
"""
#As próximas 3 linhas são para selecionar entre plot inline ou em nova janela
#Útil para rlocus
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'qt')
#get_ipython().run_line_magic('matp... | StarcoderdataPython |
3521327 | #!/usr/bin/env python
"""
@authors: <NAME>, <NAME>
Date Created: 9/24/2011
"""
from __future__ import division, print_function
from future.utils import iteritems, viewitems
from builtins import int
import os
import sys
import subprocess
import time
from copy import copy
import multiprocessing as mpr
import argparse
... | StarcoderdataPython |
3584493 | <gh_stars>1-10
#!/usr/bin/env python
from shellcall import ShellCall
# Delete all containers
ShellCall("docker rm $(docker ps -a -q)")
# Delete all images
ShellCall("docker rmi $(docker images -q)") | StarcoderdataPython |
21043 | import pyblaze.nn.data.extensions
from .noise import NoiseDataset, LabeledNoiseDataset
from .zip import ZipDataLoader
from .transform import TransformDataset
| StarcoderdataPython |
189835 | from pylps.core import *
initialise(max_time=5)
create_actions('show(_)')
create_events('handle_list(_)')
create_variables('X', 'XS')
reactive_rule(True).then(
handle_list(['a', 'b', 'c', 'd']).frm(T1, T2)
)
goal(handle_list([X]).frm(T1, T2)).requires(
show([X]).frm(T1, T2)
)
goal(handle_list([X | XS]).frm... | StarcoderdataPython |
1877223 | <reponame>ChyiYaqing/chyidlTutorial
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# array_fixed_size_CURD_implement.py
# python
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And ... | StarcoderdataPython |
9728505 | <reponame>wangvictor2012/liuwei<gh_stars>0
"""
Mockup classes used in unit tests.
"""
class FakeProcess(object):
def __init__(self):
self.regs = {}
def setreg(self, name, value):
self.regs[name] = value
def getreg(self, name):
return self.regs[name]
| StarcoderdataPython |
1792358 | from setuptools import find_packages
from setuptools import setup
long_description = """
This will be a new type of Gherkin/BDD implementation for Pytest. It is based on the Gherkin library and Pytest framework.
"""
setup(
name="pytest-gherkin",
version="0.1",
url="https://github.com/bigbirdcode",
lic... | StarcoderdataPython |
6497372 |
from .launch_params import LaunchParams, valid_param
ROLES_STUDENT = ['student', 'learner']
ROLES_INSTRUCTOR = ['instructor', 'faculty', 'staff']
class ToolBase(object):
def __init__(self, consumer_key=None, consumer_secret=None, params=None):
self.consumer_key = consumer_key
self.consumer_sec... | StarcoderdataPython |
6539641 | <reponame>shr-project/Scenic
from .common import scenicToWebotsPosition, scenicToWebotsRotation
| StarcoderdataPython |
8045015 | #!/usr/bin/env python
'''
Copyright (c) Sentieon Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of cond... | StarcoderdataPython |
1941813 | <filename>TD/q_learning/simple_q_learning.py
#http://mnemstudio.org/path-finding-q-learning-tutorial.htm
#provide two different criterion for q-learning
import numpy as np
#initialize q function
q = np.matrix(np.zeros([6,6]))
# r is the tabular representation for rewards
r = np.matrix([[-1,-1,-1,-1,0,-1],
... | StarcoderdataPython |
3444500 | <reponame>AndrewLester/2020-robot
from typing import get_type_hints
class FakeImpl:
def __init__(self, *args, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def __getattribute__(self, attr):
return FakeImpl()
def __call__(self, *args, **kwargs):
... | StarcoderdataPython |
375647 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model
admin.site.register(get_user_model(), UserAdmin)
| StarcoderdataPython |
5044258 | <filename>model/contact.py<gh_stars>0
class Contact:
def __init__(self, first_name, last_name, nick, home_phone, mobile_phone, email):
self.first_name = first_name
self.last_name = last_name
self.nick = nick
self.home_phone = home_phone
self.mobile_phone = mobile_phone
... | StarcoderdataPython |
1632082 | <reponame>deepestML/Discord-S.C.U.M<gh_stars>100-1000
import time, datetime
def calculateNonce(date="now"):
if date == "now":
date = datetime.datetime.now()
unixts = time.mktime(date.timetuple())
return str((int(unixts)*1000-1420070400000)*4194304) | StarcoderdataPython |
4886764 | import sys
import re
import textwrap
import commonmark
import pygments
import pygments.lexers
import pygments.styles
import pygments.formatters
from .styler import Styler, Style
from .escapeseq import EscapeSequence, _true_color
import logging
logger = logging.getLogger('consolemd')
endl = '\n'
def debug_tag(obj,... | StarcoderdataPython |
11297943 | import os
import asyncio
import aiohttp
from aiohttp import web
async def get_my_piblic_ip(client: aiohttp.ClientSession) -> dict:
print(client.get('https://api.ipify.org/?format=json'))
async def set_webhooks(base_url):
async with aiohttp.ClientSession() as client:
my_public_ip = await get_my_pibli... | StarcoderdataPython |
3371979 | from datetime import datetime
from loguru import logger
from config import settings
from order.dao import ordermodel
from order.schemas.schemas_order import (
orderMessage,
orderPayload,
orderModelBrokerMessage,
orderModelCreate,
messageBaseResponse,
)
from order.api.adapters.user import get_user
... | StarcoderdataPython |
3301368 | <reponame>rebeccadavidsson/covid19-sir
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import numpy as np
import pandas as pd
from covsirphy.util.error import NotInteractiveError
from covsirphy.util.plotting import line_plot
from covsirphy.cleaning.term import Term
from covsirphy.cleaning.jhu_data import JHUD... | StarcoderdataPython |
5178675 | for i in range(129):
j = (1 << i)
print(i, (j-1).bit_length(), (j).bit_length(), (j+1).bit_length())
print(i, (-j-1).bit_length(), (-j).bit_length(), (-j+1).bit_length())
| StarcoderdataPython |
199499 | <reponame>JuneMuoti/Hood-watch
from .models import User,Post
from django import forms
class ProfileForm(forms.ModelForm):
class Meta:
model = User
exclude = []
widgets = {}
class PostForm(forms.ModelForm):
class Meta:
model = Post
exclude = []
widgets = {}
class H... | StarcoderdataPython |
4843048 | from discord.ext import commands
import asyncio
import random
import os
import math
import traceback
from datetime import datetime
from discord.ext import commands
from discord.ext import tasks
import threading
ID_role_1 = 767249291730747403
ID_role_2 = 767200011749949470
ID_role_3 = 767200106557865985
ID_role_tk = 76... | StarcoderdataPython |
229961 | from torch.nn import CrossEntropyLoss
from torch.nn.functional import nll_loss, log_softmax
class LabelSmoothingCrossEntropy(CrossEntropyLoss):
def __init__(self, eps: float = 0.1, *args, **kwargs):
super().__init__(*args, **kwargs)
self.eps = eps
def forward(self, output, target):
c ... | StarcoderdataPython |
6653950 | <gh_stars>0
"""Advent of Code 2017 Day 4."""
def main(file_input='input.txt'):
passphrases = [line.strip().split()
for line in get_file_contents(file_input)]
validators = (
('no duplicates', no_duplicates),
('no anagrams', no_anagrams),
)
for description, validator i... | StarcoderdataPython |
3544733 | <reponame>tbirdso/ITKVkFFTBackend<gh_stars>0
# ==========================================================================
#
# Copyright NumFOCUS
#
# 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 L... | StarcoderdataPython |
3287303 | # !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) <NAME>, 2021
# All rights reserved
# @Author: '<NAME> <<EMAIL>>'
# @Time: '7/2/21 3:09 PM'
# 3p
from mask import Mask
from mask_prometheus import Prometheus
# project
from examples.protos.hello_pb2 import HelloResponse
app = Mask(__name__)
app.config["REFL... | StarcoderdataPython |
213672 | <reponame>sahin88/Python_Ethical_Hacking_Tools_Vulnerability_DDOS_PassSniffer
import scapy.all as scapy
import time
import termcolor
class ConnectToTarget:
def spoof(self,router_ip,target_ip,router_mac,target_mac ):
packet1=scapy.ARP(op=2, hwdst=router_mac,pdst=router_ip, psrc=target_ip)
packet2=scapy.ARP(op=2,... | StarcoderdataPython |
5115573 | <gh_stars>1-10
# pre allocate
mat = np.zeros([n, 3])
for i in range(n):
mat[i][0] = ...
mat[i][1] = ...
mat[i][2] = ...
| StarcoderdataPython |
352979 | import theano
import theano.tensor as T
from lasagne.layers import batch_norm, DenseLayer
from lasagne.nonlinearities import sigmoid, rectify, elu, tanh, identity, softmax
from lasagne.init import GlorotUniform, Constant, HeNormal
from lasagne.layers import Conv2DLayer, Pool2DLayer, MaxPool2DLayer, MaxPool1DLayer
fro... | StarcoderdataPython |
1862265 | #!/usr/bin/env python3
# -*- coding:utf8 -*-
import functools
import random
import sys
from PyQt5.QtCore import (QByteArray, QDataStream, QFile, QFileInfo,
QIODevice, QPoint, QPointF, QRectF, Qt)
from PyQt5.QtWidgets import (QApplication, QDialog,
QDialogButtonBox... | StarcoderdataPython |
3241705 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Wed May 18 07:51:28 2016
@author: ericgrimson
"""
import datetime
class Person(object):
def __init__(self, name):
"""create a person called name"""
self.name = name
self.birthday = None
self.lastName = name.split(' ')[-1]
... | StarcoderdataPython |
6630866 | def max_num_in_list(items):
tot = max(items)
return tot
print(max_num_in_list([1, 2, -8, 0]))
#
# def max_num_in_list(list):
# max = list[0]
# for a in list:
# if a > max:
# max = a
# return max
#
#
# print(max_num_in_list([1, 2, -8, 0]))
"""
Write a Python program to get the... | StarcoderdataPython |
4820366 | <filename>wagtail_localize/test/wagtail_hooks.py
from wagtail.contrib.modeladmin.options import (
ModelAdmin,
ModelAdminGroup,
modeladmin_register,
)
from wagtail_localize.modeladmin.options import TranslatableModelAdmin
from .models import NonTranslatableModel, TestModel, TestPage
class TestPageAdmin(T... | StarcoderdataPython |
1604806 | <reponame>Tejas-Nanaware/Learning-OpenCV<filename>haar cascades/own haar cascade/get files.py
import urllib.request
import cv2
import numpy as np
import os
print("Hi")
def store_raw_images():
print("getting url")
# neg_images_link = 'http://image-net.org/api/text/imagenet.synset.geturls?wnid=n00007846'
# neg_i... | StarcoderdataPython |
382623 | import os
import pytest
from pathlib import Path
import logging
from balsa import Balsa
from awsimple import __application_name__, __author__, is_mock, use_moto_mock_env_var, S3Access
from test_awsimple import test_awsimple_str, temp_dir, cache_dir
mock_env_var = os.environ.get(use_moto_mock_env_var)
if mock_env_... | StarcoderdataPython |
1858617 | import time
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # availab... | StarcoderdataPython |
170765 | <gh_stars>0
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
import commands
import time
i=0
tempo=600
x=list()
y11tx=list()
y11rx=list()
y12tx=list()
y12rx=list()
y14tx=list()
y14rx=list()
plt.ion() #Turn interactive mode on
fig,(ax11,ax12,ax14)=plt.subplots(3,sharex=True,sharey=True)
fig.... | StarcoderdataPython |
12607 | '''
Part of the dibase.rpi.gpio.test package.
GPIO pin id support classes' platform tests.
Underlying GPIO pin ids are those used by the Linux gpiolib and used
to identify a device's GPIO pins in the Linux sys filesystem GPIO
sub-tree.
Developed by <NAME> / Dibase Limited.
Copyrig... | StarcoderdataPython |
4986191 | #!/usr/bin/env python3
import string
class Solution:
def uniqueLetterString(self, s):
d1, d2 = {c: -1 for c in string.ascii_uppercase}, {c: -1 for c in string.ascii_uppercase}
ret, last = 0, 0
for i, c in enumerate(s):
last = last + (i-1) + d2[c] - 2*d1[c] + 1
prin... | StarcoderdataPython |
6692097 | <reponame>pmacosta/putil<filename>putil/tree.py
# -*- coding: utf-8 -*-
# tree.py
# Copyright (c) 2013-2016 <NAME>
# See LICENSE for details
# pylint: disable=C0111,R0913,W0105,W0212
# Standard library imports
import copy
import sys
# Putil imports
import putil.exh
###
# Exception tracing initialization code
###
"""... | StarcoderdataPython |
6680331 | <gh_stars>1-10
import json
from crawl_taobao_goods_migrate.config import CRAWL_SHOPS
from pyspider.helper.date import Date
from pyspider.helper.excel import Excel
from pyspider.libs.oss import oss
from pyspider.libs.sls import sls
class TmallOss:
"""
天猫商品在oss的数据,输出Excel
"""
def __init__(self, start_... | StarcoderdataPython |
11290850 | #!/usr/local/sci/bin/python2.7
#*****************************
#
# merge _day and _night netCDF files
#
#
#************************************************************************
'''
Author: <NAME>
Created: March 2016
Last update: 12 April 2016
Location: /project/hadobs2/hadisdh/marine/PROGS/Build
-------------------... | StarcoderdataPython |
186447 | <filename>sponsor-challenges/csit/part1 source/opcode.py<gh_stars>1-10
class opcode(object):
nul = 1
hello = 2
rhello = 130
get = 160
rget = 161
| StarcoderdataPython |
4980105 | from dependency_injector.wiring import inject, Provide
from fastapi import APIRouter, Depends
from application.rest_api.authentication.schemas import AuthenticateJwtResponse, LoginPostRequestBody
from application.users.container import UserContainer
from application.users.services import LoginUserService
router = API... | StarcoderdataPython |
6431805 | <reponame>semaphoreP/EXOSIMS
from EXOSIMS.SurveySimulation.linearJScheduler import linearJScheduler
import astropy.units as u
import numpy as np
class occulterJScheduler(linearJScheduler):
"""occulterJScheduler
This class inherits linearJScheduler and works best when paired with the
SotoStarshade Ob... | StarcoderdataPython |
4928918 | <reponame>ChuanleiGuo/AlgorithmsPlayground
class Solution(object):
def PredictTheWinner(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
mem = {}
def helper(i, j):
if (i, j) not in mem:
mem[(i, j)] = nums[i] if i == j else \
... | StarcoderdataPython |
12815373 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Nameserver'
db.create_table('nameserver', (
('created', self.gf('... | StarcoderdataPython |
9703125 | <filename>tests/test_create_features.py
# Lint as: python3
"""
test TextParsers
"""
import unittest
from src import text_parser
class TestCreateFeatures(unittest.TestCase):
def test_percent_uppercase(self):
text = "aA"
uppercase = text_parser.percent_uppercase(text)
self.assertEqual(0.5, uppercase)
... | StarcoderdataPython |
9638998 | <gh_stars>0
# Demo Python Dictionaries - Dictionary
'''
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.
'''
# Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" ... | StarcoderdataPython |
3288768 | <filename>lorem.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index2():
return render_template("index2.html")
@app.route("/more")
def more():
return render_template("more.html")
| StarcoderdataPython |
5004232 | # -*- coding: utf-8 -*-
# pylint: disable=E1101,C0103
r"""@package gmsh
Contains utilities for reading data from a GMSH-generated mesh file
@author <NAME> (<EMAIL>)
"""
import numpy
import struct
class GmshElement(object):
"""Enumeration of GMSH element types"""
TRIANGLE = 2
QUAD = 3
class GmshFileRea... | StarcoderdataPython |
5095409 | import unittest
import jinete as jit
from .abc import (
TestObjective,
)
class TestDialARideObjective(TestObjective):
def test_creation(self):
objective = jit.DialARideObjective()
self.assertEqual('Dial-a-Ride', objective.name)
def test_result(self):
objective = jit.DialARideObj... | StarcoderdataPython |
9677722 | <reponame>oniani/pyfunctional
"""
This module implements all and an
functions from functional programming.
The implementations are based on all and any
functions of the Haskell programming language.
Author : <NAME>
Date : 04/23/2019
License: MIT
"""
from sys import setrecursionlimit
from typing import Callable, S... | StarcoderdataPython |
3220609 | import logging
from enum import Enum
from datetime import date
from pydantic import Field, root_validator
from typing import List, Optional
from .base import SnakeModel
logger = logging.getLogger(__name__)
class ExportDataType(str, Enum):
raw_data = "raw_data"
occupancy = "occupancy"
social_distancing =... | StarcoderdataPython |
6532059 | # -*- coding: utf-8 -*-
import os
import shutil
import tempfile
from pur import pur, update_requirements, __version__
from click.testing import CliRunner
from pip._internal.index import InstallationCandidate, PackageFinder, Link
from pip._internal.req.req_install import Version
from . import utils
from .utils impo... | StarcoderdataPython |
3297415 | <filename>examples/gipc_benchmark.py
# -*- coding: utf-8 -*-
# Copyright 2012-2020 Dr. <NAME>. See LICENSE file for details.
"""
Example output for Python 2.7.3 on Ubuntu 10.04 on a Xeon E5630 for
# MSG length optimized for throughput (length 64000):
14:52:07,606.2 [26430]benchmark_manager# Overall benchmark resul... | StarcoderdataPython |
34622 | <reponame>osagha/turktools<gh_stars>0
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from sympy import Symbol, solve
from sympy.abc import a, b, c
from fit_beta import fit_beta_mean_uncertainty, kl_dirichlet
RESULTS_FILE = "../results/results_beta_exp.csv"
FILTER_BY = "ran... | StarcoderdataPython |
5142542 | # selection sort
def selection(sortlist):
""" checks for the largest and then replaces - ascending order only"""
for i in range(0,len(sortlist)-1):
small = sortlist[i]
pos = i
for j in range(i+1,len(sortlist)):
if sortlist[j] < small:
small = sortlist[j]
pos = j
sortlist[pos] = sortlist[i]
... | StarcoderdataPython |
11354113 | <reponame>SBRG/lifelike
"""Table schema for files.
Had to update migration file itself, rather
than a new migration file... The reason was
because changed the `id` column to Integer,
and there wasn't an easy way to set a default
value to autoincrement the primary key of an
existing column with alembic.
The `file_id` ... | StarcoderdataPython |
1805904 | import sys
import sdl2
import sdl2.ext
def run():
sdl2.ext.init()
window = sdl2.ext.Window("The Pong Game", size=(800, 600))
window.show()
factory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE)
spriterenderer = factory.create_sprite_render_system(window)
running = True
while running:
... | StarcoderdataPython |
180315 | what = input( 'что делаем?' '(+, -, *, /, %): ' )
a = int ( input( 'введи число 1: ' ) )
b = int ( input( 'введи число/проценты от числа "1" 2: ' ) )
p = 100
if what == '-':
c = a - b
print( str(a) + "-" + str(b) + "=" + str(c) )
elif what == '+':
c = a + b
print( str(a) + "+" + str(b) + "=" + str(c) )
... | StarcoderdataPython |
1767593 | #!/usr/bin/env python2
# Copyright (c) 2001 by The Regents of the University of California.
# All rights reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose, without fee, and without written agreement is
# hereby granted, provided that the above copyrigh... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.