index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
993,000 | da8e7d5ad85f8736e4aadd118314b3ec39e2090b | import pytest
from gumo.core.domain.entity_key import KeyPair
from gumo.core.domain.entity_key import NoneKey
from gumo.core.domain.entity_key import EntityKey
from gumo.core.domain.entity_key import EntityKeyFactory
from gumo.core.domain.entity_key import IncompleteKey
class TestKeyPair:
def test_invalid_name(s... |
993,001 | a92627e32e367ce8104f04f87ea328e2d1e26278 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 02 18:57:40 2016
@author: marco
"""
from manual_tests.models.linear_models import MIMO2x2, StabilizationMIMO2x2
from yaocptool.methods import IndirectMethod
# model = VanDerPol()
# problem = VanDerPolStabilization(model)
model = MIMO2x2()
problem = StabilizationMIMO2x2(... |
993,002 | 0ee04b3aedc5f4689aab7779af13851105ede703 | # from django.shortcuts import render
from django.views.generic import ListView
from habratest.models import Post
class Posts(ListView):
"""
Список всех доступных статей
"""
# Нижеуказанные параметры можно также передать
# данному отображению через метод as_view()
# url(r'^$', Posts.as_view(... |
993,003 | eb87513c1159dd5638efcdc08f9a5d6659911c33 | # Generated by Django 3.0.4 on 2020-08-12 16:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clients', '0003_clients_email'),
]
operations = [
migrations.AlterField(
model_name='clients',
name='email',
... |
993,004 | 270bc56ac4ffa2eeea3ddb0edc65850c55c901fb | import os.path
import urllib, os
from ConfigParser import ConfigParser
from XPLMPlugin import *
from XPLMProcessing import *
from XPLMDataAccess import *
from XPLMDefs import *
from XPLMMenus import *
from XPLMDisplay import *
from XPLMGraphics import *
from XPLMPlanes import *
from XPWidgetDefs import *
from XPWidgets... |
993,005 | e51d600a0243a1d1bc9ffdf61c08a996f0056b55 | import cv2
import zbar
from PIL import Image
import numpy as np
import socket
import urllib
bytes = bytes()
def get_frame(stream):
global bytes
bytes += stream.read(1024)
a = bytes.find(b'\xff\xd8')
b = bytes.find(b'\xff\xd9')
if a != -1 and b != -1:
jpg = bytes[a:b+2]
bytes = bytes[b+2:]
img = cv2.imdecod... |
993,006 | be6c48b8b15d0bcac33aabbfa809355a77e59163 | lista = []
maiores = []
soma = 0
media = 0.0
for i in range(10):
num = int(input('Digite um número: '))
lista.append(num)
soma = soma + num
num_elementos = len(lista)
media = soma / num_elementos
for i in range(10):
if lista[i] > media:
maiores.append(lista[i])
print('A média dos números é: '... |
993,007 | 87ca91fb425906a2ee533072dfee26f584a0dbd8 | # 럭키 스트레이트
def luckyStraight():
s = input()
mid = len(s) // 2
left = list(s[:mid])
right = list(s[mid:])
leftSum, rightSum = 0, 0
for i in range(len(left)):
leftSum += int(left[i])
rightSum += int(right[i])
if leftSum == rightSum:
print("LUCKY")
else:
... |
993,008 | c6d5c57bd57bf34d564de12803a0679509dec81e | from flask import Flask, render_template, request, make_response
from flask_sqlalchemy import SQLAlchemy
from config import app_config
#app = Flask(__name__)
#app.config.from_object(app_config[env_name])
#JWT_SECRET_KEY = hhgaghhgsdhdhdd
def create_app(env_name):
"""
Create app
"""
# app... |
993,009 | 15b809ad99fd0adc20227ebea1abcf53575b0d92 | def find_it(seq):
dic = {}
for x in seq:
if dic.__contains__(x):
dic[x] += 1
else:
dic[x] = 1
for key, value in dic.items():
if value % 2 != 0:
return key
|
993,010 | 231d384ab3680eadddd62f5896c87b13a34b5cf8 | # OAuth app keys
DROPBOX_KEY = 'changeme'
DROPBOX_SECRET = 'changeme'
DROPBOX_AUTH_CSRF_TOKEN = 'dropbox-auth-csrf-token'
|
993,011 | 3f7a8bb7030829545b382a17f5d393510703c32c | print("Maior número da Tupla")
def maiorTupla (tupla):
maior = max(tupla)
return maior
tupla = (1, 2, 3, 4, 5, 6, 7, 80, 9, 10)
print(maiorTupla(tupla)) |
993,012 | 0ca991e780b1cc8686fe586af81e948a9cffe229 | # SheetManager Exceptions
class GoogleConnectionException(Exception):
pass
class InitSheetManagerException(Exception):
pass
class AuthSheetManagerException(Exception):
pass
class CreateSheetException(Exception):
pass
class LoadSheetException(Exception):
pass
# Holdings Exceptions
class Hol... |
993,013 | 5c7766b0fd1f77cb0ab89c54e08e283f895660d8 | #!/usr/bin/python2.7
def transform(x):
return int(str(x)[::-1]) + x
def is_palindrome(x):
x_str = str(x)
return x_str == x_str[::-1]
def is_lychrel(x):
pal = transform(x)
for i in xrange(0, 50):
if (is_palindrome(pal)):
return False
else:
pal = transform(pal)
return True
count = 0
for i in xrange(1... |
993,014 | 30c363919055bded5bff501d259751b35652e81b | from django.db import models
# Data model for Authors
class Author(models.Model):
first_name = models.TextField()
last_name = models.TextField()
def __str__(self):
return self.last_name + ", " + self.first_name
# Data model for Books
class Book(models.Model):
name = models.TextField()
isb... |
993,015 | 61ea95c81e8aeb1c275d1564a5b6b08ee518f1dd | #!/usr/bin/env python
# coding=utf-8
# Copyright 2021-Present The THUAlign Authors
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import collections
def parse_args():
parser = argparse.ArgumentParser(description="Create vocabulary")
... |
993,016 | 75c2d37bd9456de71b6933c6ba67b9eb3f189446 | import pandas as pd
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# This removes ASCII characters, and writes them to a new, edited file.
with open('/Users/jif/Repos/Automation/Files/sample.txt') as fp:
edit_file = open('/Users/jif/Repos/Automation/Files/sample_v2.txt', "w")
for line in fp:
ed... |
993,017 | 8c31379b0fa8a98502068cd17209bb51459d2388 | from hash40 import Hash40
class NameHash40:
def __init__(self, name, hash40):
self.name = name
self.hash40 = hash40
HashList = []
ArticleList = []
namesFile = open('scriptNames.txt', 'r')
#Game
HashList.append(NameHash40("game_".strip(), Hash40.CreateFromString("game_".lower().strip())))... |
993,018 | 3d3a01ac76d206dbbfef3f0ab73b1aecfed2b407 | """
Rebuilds database: deletes old database.db and creates tables.
"""
import os
import sqlite3
os.remove('database.db')
CONNECTION = sqlite3.connect('database.db')
CONNECTION.row_factory = sqlite3.Row
CURSOR = CONNECTION.cursor()
CURSOR.execute(
"""
CREATE TABLE groups
(name text)
"""
)
CURSOR.exe... |
993,019 | 79398ad5ef2ef8863f3cd9a5bc23ebe97b9a2c01 |
# 测试输入空字符串的情况,int 时会报错
port = input("input name :")
print("1:")
print(port)
if port:
print("非空字符串")
else:
print("空字符串")
port = int(port)
print("2:")
print((port))
if port:
print("非零")
else:
print("零")
|
993,020 | 7da4235f6df904a58f01ecaf7fa4d23274347a31 | """DB_Ubereats URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... |
993,021 | 4252a2ae2c09ebe8af535335b74506bef8a3e581 | """
sentry.utils.files
~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import zlib
from sentry import features, options
from sentry.models import MAX_FILE_SIZE
def compress_file(fp... |
993,022 | 0ebd3346aa5f066d77c11bd86b79abb22b551f36 | import pyvisa
from .driver import Driver
class Keithley6221Driver(Driver):
def __init__(self, resource):
super().__init__(resource)
try:
# Try to setup the device for serial operation
resource.baud_rate = 19200
resource.data_bits = 8
resource.parity... |
993,023 | 1ed53c9fcca3b817ae66de83535fe2c0e1fdfda0 | import numpy as np
from math import pow
import Eff
TankR = 10026.35e-3
Height = 10026.35e-3
PPM = [1, 1, 1, 1, 1, 1]
Iso = ['U238', 'Th232', 'U235', 'U238_l', 'Th232_l', 'U235_l']
IsoDecay = [['Pa234', 'Pb214', 'Bi214', 'Bi210',
'Tl210'], #U238
['Ac228', 'Pb212', 'Bi212', 'Tl208'],
... |
993,024 | e8ee4ff881ac0c9d24ac7600eaabcd5af6c35e46 | from math import factorial
import numpy as np
from xspline.typing import PolyParams, NDArray
from xspline.xfunction import BundleXFunction, XFunction
def poly_val(params: PolyParams, x: NDArray) -> NDArray:
"""Polynomial value function.
Parameters
----------
params
Polynomial coefficients.
... |
993,025 | 7c5df548f0e1254aa1d14309a120d74af9ede05a | from hashlist import Hashlist
class Hash:
def __init__(self):
self.taken = 0
self.list = Hashlist(4)
def __setitem__(self,index,newItem):
if self.taken/4 > len(self.list)/3:
self.list = Hashlist(len(self.list)*2, self.list)
old = self.list.items[self.list.toIndex(index)]
self.list[index... |
993,026 | 760db1dcd073d63dab71e3c0d965eb3a4b231edd | import sys
import logging
logger = logging.getLogger(__file__)
def reload_pb_tools():
"""Remove all mop modules from the Python session.
Use this command to reload the `mop` package after
a change was made.
"""
search = ["pb"]
mop_modules = []
for module in sys.modules:
for term... |
993,027 | 86f57b1731307ea8802a436a88d73e70fc0fb32a | import unittest
from main.SEIR_model import SEIR
import configparser
import os
class TestMultipleFactors(unittest.TestCase):
conf = configparser.ConfigParser()
curpath = os.path.dirname(os.path.realpath(__file__))
cfgpath = os.path.join(curpath, "config.ini")
conf.read(cfgpath, encoding="utf-8")
... |
993,028 | 4c4f7cb701b090d10227f7a51de9954f9934d79f | ### Routines for demonstrating 1D function learning programs.
from RLtoolkit.G.g import *
from RLtoolkit.Quickgraph.graph import *
from math import *
from .fa import *
from .tilecoder import *
window = None
black = gColorBlack(True)
flip = gColorFlip(True)
gray = gColorLightGray(True)
white = gColorWhite(True)
xresol... |
993,029 | 0cfb1ce36fafaeb2e10b3ce773f6e86afe407b31 | from .densenet import densenet121, densenet161, densenet169, densenet201
from .inception import inception_v3
from .mnasnet import mnasnet0_5, mnasnet0_75, mnasnet1_0, mnasnet1_3
from .mobilenet import mobilenet_v2_
from .resnets import resnet18, resnet34, resnet50, resnet101, resnet152
from .resnext import resnext50_32... |
993,030 | 0a140cfb0e4b977c5cefe3cb7f6836c7f98f0979 | import pymongo
from pymongo.collection import Collection
class Connect_mongo:
def __init__(self):
self.client = pymongo.MongoClient(host='192.168.100.106', port=27017)
self.db_data = self.client['douguo']
def insert_item(self, item):
db_collectiopn = Collection(self.db_data, 'douguo'... |
993,031 | c905b82d93d37dbb23eb80bdedd15120d31b9dd2 | # Generated by Django 3.1.1 on 2020-09-28 14:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0017_remove_course_newfield'),
]
operations = [
migrations.AlterField(
model_name='course',
name='image',... |
993,032 | 1afbd83e7855afbab33aed4467902b9dbc83abf0 | #!/usr/bin/python
import os
from os import listdir
from os.path import isfile, join
import numpy as np
import cv2
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
vocab = [] # This is a list of every SIFT descriptor.
raw_corpu... |
993,033 | b070c6dc7f5bd53b5f8a4051a003d48ef8a01297 | #!/usr/bin/python
import sys, urllib2, re
proteins = sys.stdin.read().strip().split('\n')
for prot in proteins:
f = urllib2.urlopen('http://www.uniprot.org/uniprot/' + prot + '.fasta')
cur = ''.join(f.read().split('\n')[1:])
ind = []
for m in re.finditer('(?=(N[^P][ST][^P]))', cur):
ind.append(m.start() + ... |
993,034 | 0ffee1a5537bc7f8fcd393fce35ae788dc142db2 |
from django.contrib import admin
from django.urls import path
from django.urls import include
urlpatterns = [
path('livraria/',include('AppLivraria.urls')),
path('admin/', admin.site.urls),
]
|
993,035 | 7441f38af587040c052e55eb3feec2dec06856f3 | goods = [
(1, {'name': "компьютер", 'price': 20000, 'count': 5, 'units': "шт."}),
(2, {'name': "принтер", 'price': 6000, 'count': 2, 'units': "шт."}),
(3, {'name': "сканер", 'price': 2000, 'count': 7, 'units': "шт."})
]
max_num = 3
fields = ["name", 'price', 'count', 'units']
print('Hello there')
while T... |
993,036 | 668b74d33c3c14f4400e95c2cd53e79c8c311e76 | # Generated by Django 2.1.4 on 2018-12-29 17:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BaseScript',
fields=[
... |
993,037 | e542aaa732b630a0310728f399c7957f663a6c43 | from RobotRaconteur.Client import * #import RR client library
import cv2
import sys
#Function to take the data structure returned from the Webcam service
#and convert it to an OpenCV array
def WebcamImageToMat(image):
frame2=image.data.reshape([image.height, image.width, 3], order='C')
return frame2
#Main... |
993,038 | d4f4af1ac216dffe8a0cdf4b42a44beb29539562 | #!/usr/bin/python3
import sys
from wltr8 import get_file_addr
#Get all transactions from address argv1, store file info in argv2
get_file_addr(sys.argv[1], sys.argv[2])
|
993,039 | 5c2838391d3e1aa8d062bd2cea0d31d92ba9026b | import cv2
def main():
low = (48, 86, 6)
high = (64, 255, 255)
image = cv2.imread('test.bmp')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, low, high)
res = cv2.bitwise_and(image, image, mask=mask)
cv2.imwrite("Result.png", res)
if __name__ == "__main__":
main... |
993,040 | 0f08ed6060461c56a8fe925d11ad167d610b2889 | # Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
## @PowhegControl PowhegConfig_HZj
# Powheg configuration for HZj subprocess
#
# Authors: James Robinson <james.robinson@cern.ch>
#! /usr/bin/env python
from ..PowhegConfig_base import PowhegConfig_base
## Default Powheg configuration for H... |
993,041 | 016680dec61165ac5dd2b37b7558f0109c5b10b5 | CURRENT_WEATHER_DATA="https://api.openweathermap.org/data/2.5/weather?"
ONE_CALL_API="https://api.openweathermap.org/data/2.5/onecall?exclude=current,minutely,hourly,alerts&"
DAY_LIMIT=7 |
993,042 | 7f3d77e592d421bee5397f9fe9ade7ad4f6296bf | import codecs
# 打开文件
f = codecs.open("text.txt", 'w', 'utf-8')
# 文件中写入内容
f.write("Hello World,Python! 中国加油!")
# 关闭流
f.close()
|
993,043 | 17ba6650e6075835f62d0bdbdadb71929a4e09c8 | # # Advanced Machine Learning Techniques
# ## Agenda
#
# 1. Reading in the Kaggle data and adding features
# 2. Using a **`Pipeline`** for proper cross-validation
# 3. Combining **`GridSearchCV`** with **`Pipeline`**
# 4. Efficiently searching for tuning parameters using **`RandomizedSearchCV`**
# 5. Adding features ... |
993,044 | 7157dfc0340c462b9eccbd308b2aeae8b5fa81ef | class School:
def __init__(self, name = None, roster = {}):
self._name = name
self._roster = roster
def get_roster(self):
return self._roster
def set_roster(self, roster):
self._roster = roster
roster = property(get_roster, set_roster)
def ... |
993,045 | 2b3ccee329bbe2b858ecffa05a4c28564755fb3f | sbox = [62, 117, 195, 179, 20, 210, 41, 66, 116, 178, 152, 143, 75, 105, 254, 1, 158, 95, 101, 175, 191, 166, 36, 24, 50, 39, 190, 120, 52, 242, 182, 185, 61, 225, 140, 38, 150, 80, 19, 109, 246, 252, 40, 13, 65, 236, 124, 186, 214, 86, 235, 100, 97, 49, 197, 154, 176, 199, 253, 69, 88, 112, 139, 77, 184, 45, 133, 104,... |
993,046 | bee105e79bf1e244cda2600e169f90d766789a36 | import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from matplotlib import gridspec
# import sklearn
# print('The scikit-... |
993,047 | 6d0e6203994419ca104557740b33c76da2ad5262 | from django.shortcuts import render, redirect
from django.views.generic import CreateView, ListView, UpdateView, TemplateView
from django.contrib.auth import login
from .forms import TeacherSignUpForm, StudentSignUpForm
from .models import User
class SignUpView(TemplateView):
template_name = 'accounts/signup.ht... |
993,048 | 13420f754b7eb295d413f31954e14940b09ff821 | import pymysql
class A:
def __init__(self):
self.conn = pymysql.connect(host="localhost",
user="root",
password="mysqlfgh.00",
db="QcChat",
port=3306,
... |
993,049 | e0286758c609a37a45046ccb5b4644eb11092199 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
count = 0
url = input("Enter Browser URL:")
client = webdriver.Chrome()
while count < 100:
print("Currently ran this ", count)
client.get(url)
count += 1
|
993,050 | ebafcc3d271a05376e1f2baa0ffb8c208df11624 | # Copyright (c) 2021, Hyunwoong Ko. 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 l... |
993,051 | 2e887ce52411de470759f594d72e9426e41706ae | import arcpy
import os
from arcpy import management as DM
from time import time
from string import zfill
from datetime import date
arcpy.env.workspace = "C:/WorkSpace/Phase5/Objects/test.gdb"
outf = open("c:/workspace/phase5/Objects/modellog.txt", "a")
outf.writelines("\n" + str(date.today()) + " --Test-Small File-\n")... |
993,052 | e527202ed9691b63df49c9f78d50f2b2485d35c4 | import unittest
import sys
sys.path.append('src')
from arduinoSerialMonitorParser import ArduinoParser
from datetime import datetime
import numpy as np
class TestParser(unittest.TestCase):
def testProcessGoodLines(self):
self.parser.lines = self.simpleFileLines
self.parser.processLines()
d... |
993,053 | a1f6bbe02711d7874534cdb6a06f4f583ceebdaf | from django.contrib.contenttypes.models import ContentType
from django_utils.render_helpers import render_or_default
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
import django.shortcuts as shortcuts
from django.template import RequestCo... |
993,054 | 6da2e31324e1952036ad289e3fb2c727c2b731f0 | import random
import requests
from lxml import etree
import redis
import time
# Redis
pool = redis.ConnectionPool(host="localhost", port=6379, decode_responses=True, db=4)
r = redis.Redis(connection_pool=pool)
headers = {
"Host": "www.letpub.com.cn",
"Connection": "keep-alive",
"Content-Length": "183",
... |
993,055 | a9391a60ccf1dc1cf1a605125ab84fdd5d3c35c5 | import re
'''
Calculate the sentiment of each dictionary
'''
def calculate_pos_neg(sum_sentiment, pos, neg, threshold, is_emo):
if is_emo:
if sum_sentiment > threshold:
pos += 2
elif sum_sentiment < -threshold:
neg += 2
else:
if sum_sentiment > threshold:
... |
993,056 | 07520d2903c4e6cb9bc55c4c33c3d6af1ba5998b | /Users/principal/anaconda3/lib/python3.6/posixpath.py |
993,057 | 3e09baa334d1977182aea5bcd0e8c6bffeae8be4 | from calendar import *
weekdays = ["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"]
date = list(map(int, input().split()))
i = weekday(date[2], date[0], date[1])
print(weekdays[i])
|
993,058 | 4c267385b4b505dfe83cd66fa956202bc5e97b0d | # -*- coding: utf-8 -*-
"""
Created on Fri May 13 19:52:20 2016
@author: Julien
"""
import pygame
import variables
from classes import Item, Inventory, Message, Illuminator
class Chest(Item):
def __init__(self,x, y, contents_list):
self.name = 'Chest'
self.value = 0
self.image = variables... |
993,059 | 805336a7bee956253f130f5f97a0e0aab768ec90 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras import layers, Sequential
cifar10 = tf.keras.datasets.cifar10
(xc_train, yc_train), (xc_test, yc_test) = cifar10.load_data()
mnist = tf.keras.datasets.mnist
(train_x, train_y), (test_x, test_y) = mnist.load_data()
# 数据预处理... |
993,060 | 9137b0b3fbeafda20f719dda29351747175dd304 | import sys
import random
from constellationData import *
from dataModel import *
from models import *
from utils import *
from solution import *
def getNextMoves(current, possibles, points, model):
start = time()
moves = [c for c in possibles if len(c.stars) <= points and c.canActivate(current.provides, current.co... |
993,061 | ea297a7d2982a1fa57558a1d4f1b5f5b85ec6174 | from envio.models import Centro, Estudio, Plan, Persona, Matricula, Entrega, Departamento
centros = [
Centro(100, 'Facultad de Ciencias','Z'),
Centro(101, 'Facultad de Economía y Empresa', 'Z'),
Centro(102, 'Facultad de Derecho', 'Z'),
Centro(109, 'Facultad de Economía y Empresa', 'Z'),
Centro(11... |
993,062 | 891c416311e9d801eb79bf17ce51f1fc1e2fe9a8 | import tw2.core as twc
import tw2.sqla as tws
import sqlalchemy as sa
import transaction
import tw2.sqla.utils as twsu
import testapi
from nose.tools import eq_
class BaseObject(object):
""" Contains all tests to be run over Elixir and sqlalchemy-declarative """
def setUp(self):
raise NotImplementedE... |
993,063 | cb09049b4c36476077bad63da1cf78afc93cc401 | from ns.utils import stampedstore
class VirtualClockServer:
""" Models a virtual clock server. For theory and implementation see:
L. Zhang, Virtual clock: A new traffic control algorithm for packet switching networks,
in ACM SIGCOMM Computer Communication Review, 1990, vol. 20, pp. 19.
Pa... |
993,064 | 6936dcc69833b4324b71e112a5e4d31e2bc0a822 | import numpy as np
import tqdm
import time
import os
import pandas as pd
import tensorflow as tf
from flearn.utils.model_utils import gen_batch
from .fedbase import BaseFedarated
class Adam:
def __init__(self, lr=0.01, betas=(0.9, 0.999), eps=1e-08):
self.lr = lr
self.beta1 = betas[0]
sel... |
993,065 | 455d8ad2789235c8170a4325bee3c50e3df1da91 | # build url from ConductR base url and given path
def url(path, args):
base_url = 'http://{}:{}'.format(args.ip, args.port)
return '{}/{}'.format(base_url, path)
|
993,066 | d3c5775c3ad427e6fa76cc2430b37450f9e4a16b | from rest_framework import serializers
from .models import Power, Temp, Switches
class PowerSerializer(serializers.ModelSerializer):
class Meta:
model = Power
fields = ('id', 'VoltsRMS','CurrentRMS','ApparentPower','TruePower' ,'ReactivePower', 'Pf', 'date_created')
class TempSerializer(seriali... |
993,067 | 22f4bd6c74184247b4ae2f78ab1c9a89875b1bc2 | from django.http import JsonResponse
from django.http import Http404
from django.views.decorators.http import require_http_methods
from django.core.cache import cache
from ..models import Redirect
@require_http_methods(["GET"])
def redirect(request, key):
data = get_from_cache(key)
if data:
return Js... |
993,068 | b07737bf65ba4526915108e2aa674a0dfd6fb75f | import traceback
from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, MetaData, ForeignKey, DateTime, Index, Boolean, func, Table, \
SmallInteger
from sqlalchemy import text
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.ext.declarative import declarative_base
from sq... |
993,069 | f8055748b03b18039e413447183be145268c915c | import cv2
import matplotlib.pyplot as plt
import time
import numpy as np
def getss(list):
avg=sum(list)/len(list)
ss=0
for l in list:
ss+=(l-avg)*(l-avg)/len(list)
return ss
def getdiff(img):
avglist=[]
try:
Sidelength=30
img=cv2.resize(img,(Sidelength,Sidelength)... |
993,070 | 92c2458c30efc626c1b94a4dd76452d8e6db19ff | """
- Enter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie, and 'q' to quit:
- Add movies
- See movies
- Find a movie
- Stop running the program
Tasks:
[X]: Decide where to store movies
[X]: What is the format of a movie?
[X]: Show the user the main interface and get their input
[X]: Allow users to a... |
993,071 | b2c78d538588511e14bd1bf05c0601923fc00916 | from urllib.parse import urljoin
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from gitenberg.metadata.pandata import Pandata
from gitensite.apps.bookinfo.models import Author, Book, Cover
import requests
def addBookFromYaml(yaml):
if isinstance(yaml, Panda... |
993,072 | 7ab222d5ee57e05fad85e4d8f971aace249266d7 | from django.contrib import admin
from django.contrib.auth.models import Permission
from django.utils.safestring import mark_safe
from Index.models import Product,Product_type,Review,Order_products,Address,Promotion
from Profile.models import My_User,Financial_detail,Payment,Order
# Register your models here.
class Ord... |
993,073 | 6d8d4e4cb252124d91f0bbd570f84c003f2736ce | import numpy as np
np.random.seed(1664)
from os import listdir
import sys
import pandas as pd
from keras.preprocessing.image import img_to_array, load_img
DATASET_PATH = 'dataset/MTFL/'
HAAR_FOLDER = '/home/username/opencv/opencv-master/data/haarcascades/'
HAAR_FILE = 'haarcascade_frontalface_default.xml'
def loadT... |
993,074 | bd5b1b0dc772f637e26d02816aa20c0dbf3ea507 | class NltkSentenceSplitter(object):
def __init__(self):
from nltk import sent_tokenize
self._sent_tokenize = sent_tokenize
def __call__(self, text):
return self._sent_tokenize(text)
class BlingfireSentenceSplitter(object):
def __init__(self):
from blingfire import text_to_... |
993,075 | bf068802a4fabbf5b67c5b0dfa13c514f5f9538d | import string
import random
def gen_url():
url = ''
for i in range(4):
url+= random.choice(string.ascii_letters)
return url |
993,076 | 9b4d492458102b5a80d20bdb5b722143678188ef | from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from blog.models import Post, Comment
from django.utils import timezone
from blog.forms import PostForm, CommentForm
from django.contrib.auth.models import User
from django.contrib import auth
from... |
993,077 | 6dfc8e4edf5a3169205953a9a2c45ce379880a1c | A = int(input())
B = int(input())
C = [i for i in range(1, 4) if i != A and i != B]
print(*C) |
993,078 | 771737853fa5cade35531cb7d2824359343b62d8 | # License: BSD
# Author: Sasank Chilamkurthy
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import matplotlib.pyplot as plt
im... |
993,079 | 624fbbfe2c95746be39011acb9fe2ea4b71d8165 | import seed
from utils import *
from models import *
from preprocessing import Preprocessing
X, y, files = load_data(patches=True)
X = X - 0.5
pre = Preprocessing(standardize=False, samplewise=False)
X_train, X_valid, y_train, y_valid = pre.split_data(
X, y, test_size=0.1, shuffle=True)
conf = Config(epochs=10... |
993,080 | 33f7a793f5b2c3b585cd9d64cb6d3694522949b8 |
"""lab05_elif.py
This program reads a temperature in fahrenheit from
the keyboard, converts it to centigrade and prints the results.
Then it prints a description of the conditions outside. Note,
in class we discussed why this code is considered somewhat sloppy.
"""
temp = input('Enter a temperature: ')
ft... |
993,081 | 338488503ffe8727e39ef50f1ac62cd7b6a94e53 | class Employee():
def __init__(self,first,last,salary):
self.first=first
self.last=last
self.salary=salary
def give_raise(self,incre=5000):
self.salary=self.salary+incre
import unittest
class TestEmployee(unittest.TestCase):
def setUp(self):
self.my_emp=Employee("jak... |
993,082 | 5c191e0c87a43d09cbcd7f26e19a94e63013da1f | import link
link_name = "GitHub Syllabus Repository"
user_text = "GitHub Syllabus Repository"
url = "https://github.com/MarkHoeber/tools-tech-syllabus"
link.xref_links.update({link_name: (user_text, url)}) |
993,083 | 83cc83ade56aab8f51e06d16fe47161a107c3fd0 | #!/usr/bin/python
### BRAND NEW VERSION. CONTAINS MATERIAL FROM LEONARDO SALA AND MARCO-ANDREA BUCHMANN
import sys; sys.path.append('/usr/lib/root')
from sys import argv,exit
from os import popen
import re
import ROOT
from math import sqrt,ceil
from array import array
class bcolors:
HEADER = '\033[95m'
OKBLU... |
993,084 | ed919d39090273360de96c5723c5e5e80fb33916 | from constants import *
from input import Input
from layout import Layout
from paddle import Paddle
from ball import Ball
from brick import *
from colorama import Back, Style
import os
import time
class Main:
'''
Explanation: This class is used as a driver class to play the game
'''
def __init__(s... |
993,085 | 7c9f51e19846e0170cb4c95489b8af9dd30a7555 | import sys
import numpy as np
sys.path.append("..")
import tensorflow as tf
import tensorflow.contrib.slim as slim
from Vgg19 import Vgg19
batch_norm = tf.layers.batch_normalization
vgg_file_path = '/home/cgim/桌面/tensorflow_train/GAN/vgg19.npy'
class SRGAN:
def __init__(self,is_training,vgg_weight):
self... |
993,086 | 0842329c37bb72d611f5ccda6a4d6b8752fe1422 | import unittest
from GenesLists import *
TEMPDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'temp/')
class GenesListsTests(unittest.TestCase):
def setUp(self):
"""
make a temp folder with two files, set all assert expectations
"""
if not os.path.exists(TEMPDIR):
... |
993,087 | d60cbd41aa7627041d353ee84037cef874486518 | """
decoder.py: When passed a list, simply returns objects as-is unless they are
integers between 1 and 26, in which case it converts that number to the
corresponding letter. The integer-to-letter correspondence is 1=A, 2=B, 3=C...
"""
from string import ascii_uppercase
def alphabator(s=None):
for o in s:
... |
993,088 | 2f9a37013df4d11e6bde889d8a30612455313b8d | def cap_name(nom):
return nom.capitalize()
def lower_word(wordy):
return wordy.lower()
def want_to_play():
answer = input("Do you want to play MadLibs? (y/n): ")
answer = answer.lower()
if answer == "y":
print("Yay!")
return make_madlib()
elif answer == "n":
return pr... |
993,089 | 82cefbb5d74e288d87a03f87cda4dd2ac284b08d | import psycopg2 as pg
choice = int(input("Enter Your choice:\n"
"1. Find\n"
"2. insert\n"
"3. delete\n"
"4. Quit\n"))
def Conneciton():
connection = ""
# use postgres
try:
connection = pg.connect(user="postgres",
... |
993,090 | a2e0a444edc14cb6ce9a0ed69ca1d90405038926 | from openpyxl.formula.tokenizer import Tokenizer, Token
from xlsx2html.utils.cell import parse_cell_location
class HyperlinkType:
__slots__ = ["location", "target", "title"]
def __init__(self, location=None, target=None, title=None):
self.location = location
self.target = target
self... |
993,091 | 9d8bf2ee9f8262113ac45088d5b53c30e06bd875 | import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
# import numpy as np
import pandas as pd
# import matlab.engine
# import io
import numpy as np
# import midi
#from scipy.io import wavfile
import scipy
#import matplotlib.pyplot as plt
from featur... |
993,092 | 53988e30d309017f08d8be6641b5fb05188ad9e8 | """Integration test for plotting data with non-gregorian calendar."""
import unittest
import warnings
import matplotlib
matplotlib.use("agg")
import cftime
import matplotlib.pyplot as plt
import numpy as np
import pytest
import nc_time_axis
class Test(unittest.TestCase):
def setUp(self):
# Make sure w... |
993,093 | 3024d5a6841260ca849aa29f29c560397861beb5 | from flask import request
from flask_restx import Resource
from ..util.dto import TransactionListDataDto
from ..service.transaction_list_data_service import save_transaction_list_data, \
get_transaction_list_data, get_all_transaction_lists_with_pagination, \
get_all_transaction_list_data, update_transaction_li... |
993,094 | d6b6c2d417ebcc92e4402a0fe028ec98c02e1d9b | #!/usr/bin/python
import commands
def exec_ssh_cmd(target, cmd, user="root"):
"""
"""
ssh_cmd_prefix = "ssh -o StrictHostKeyChecking=no -T root"
return exec_cmd("%s@%s 'sudo -u %s sh -c \"%s\"'" % (ssh_cmd_prefix, target, user, cmd))
def exec_cmd(cmd):
"""
"""
result = commands.getstatusoutput(cmd)
print re... |
993,095 | 36ed7b864733ea9fc67f666ea219f50540f8ce7e | import os,sys,shutil
import importlib
import warnings
import datetime
import polychromosims.paramproc
import polychromosims.globalvars as globalvars
def init(sysargv=sys.argv):
"""
Initialize the polychromosims wrapper. This function should be called
before importing polychromosims.sim, because it loads t... |
993,096 | b7c507f2b309af13013415e7c6e02cab93faddb3 | from flask import Blueprint, jsonify, request
from pystock.app.services.report_service import get_report
from pystock.app.config import API_KEY
report_controller = Blueprint('report_controller', __name__)
@report_controller.route('/getReport')
def report():
auth = request.headers.get("X-Api-Key")
if auth !=... |
993,097 | 663e6c164586d93c5c8e93390f28c0ff3bb9bad3 | from typing import Optional
import bpy
def get_preferences(context: bpy.types.Context) -> Optional[bpy.types.AddonPreferences]:
addon_name = ".".join(__name__.split(".")[:-3])
addon = context.preferences.addons.get(addon_name)
if addon:
return addon.preferences
print(f"WARNING: Failed to read... |
993,098 | 33afcc1c7273018dad3ad6832e0370f38df877a2 | ## Newton's Law of Cooling.
temperature = 212
count = 0
while temperature > 150:
count += 1
temperature -= (temperature - 70) * 0.079
print("The coffee will cool to below")
print("150 degrees in", count, "minutes.")
|
993,099 | e460a5bcf1bff809249198dcb82e2218d34fc874 | # Generated by Django 2.2 on 2020-03-28 11:21
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('labApp', '0002_auto_20200328_1629'),
]
operations = [
migrations.AlterField(
model_name='activityperiod',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.