index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
3,500 | 4f7b689c06383673b510092932b051c644306b84 | # -*- coding:utf-8 -*-
from odoo import api, fields, _, models
Type_employee = [('j', 'Journalier'), ('m', 'Mensuel')]
class HrCnpsSettings(models.Model):
_name = "hr.cnps.setting"
_description = "settings of CNPS"
name = fields.Char("Libellé", required=True)
active = fields.Boolean("Ac... |
3,501 | f0f4573808253ca4bff808104afa9f350d305a9c | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... |
3,502 | 610610e7e49fc98927a4894efe62686e26e0cb83 | from pythonforandroid.recipe import CompiledComponentsPythonRecipe
from multiprocessing import cpu_count
from os.path import join
class NumpyRecipe(CompiledComponentsPythonRecipe):
version = '1.18.1'
url = 'https://pypi.python.org/packages/source/n/numpy/numpy-{version}.zip'
site_packages_name = 'numpy'
... |
3,503 | 600b49c7884f8b6e3960549702a52deb20089f5a | import time
import os
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from app.wechat_subscription.object_page.home_page import HomePage
from conf.decorator import teststep, teststeps
from conf.base_page import BasePage
from selenium.webdriver... |
3,504 | b0bc55ab05d49605e2f42ea036f8405727c468d2 | import pandas
from sklearn.externals import joblib
import TrainTestProcesser
from sklearn.ensemble import RandomForestClassifier
from Select_OF_File import get_subdir
import matplotlib.pyplot as mp
import sklearn.model_selection as ms
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classificati... |
3,505 | 8f971ee3b98691a887ee0632afd613bbf4f19aa0 | import pytest
from homeworks.homework6.oop_2 import (
DeadLineError,
Homework,
HomeworkResult,
Student,
Teacher,
)
def test_creating_objects():
teacher = Teacher("Daniil", "Shadrin")
student = Student("Roman", "Petrov")
homework = teacher.create_homework("Learn OOP", 1)
homework_r... |
3,506 | bc32518e5e37d4055f1bf5115953948a2bb24ba6 | import sys
from reportlab.graphics.barcode import code39
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from parseAccessionNumbers import parseFile
def main():
if len(sys.argv) <= 1:
print "No filepath argument passed."
return
... |
3,507 | c199b2f87b7a4ac820001dab13f24fdd287a1575 | # https://py.checkio.org/blog/design-patterns-part-1/
class ImageOpener(object):
@staticmethod
def open(filename):
raise NotImplementedError()
class PNGImageOpener(ImageOpener):
@staticmethod
def open(filename):
print('PNG: open with Paint')
class JPEGImageOpener(ImageOpener):
@... |
3,508 | c54a046ebde1be94ec87061b4fba9e22bf0f4d0a | from e19_pizza import *
print("\n----------导入模块中的所有函数----------")
# 由于导入了每个函数,可通过名称来调用每个函数,无需使用句点表示法
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 注意:
# 使用并非自己编写的大型模块时,最好不要采用这种导入方法,如果模块中
# 有函数的名称与你的项目中使用的名称相同,可能导致意想不到的结果。
# Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导
# 入所有... |
3,509 | 3f86227afd60be560ac3d4ce2bee1f6cf74a744d | from flask_admin.contrib.sqla import ModelView
from flask_admin import Admin
from flask import abort
import flask_login
import logging
from .models import User, sendUserMail, db as userdb
from .box_models import Box, Image, db as boxdb
from .box_queue import BoxQueue
logger = logging.getLogger('labboxmain')
class Au... |
3,510 | 5f00cd446b219203c401799ba7b6205c7f1f8e9f | # -*- coding: utf-8 -*-
from numpy import *
def loadDataSet(fileName, delim = '\t'):
fr = open(fileName)
stringArr = [line.strip().split(delim) for line in fr.readlines()]
datArr = [map(float,line) for line in stringArr]
return mat(datArr)
def pca(dataMat, topNfeat = 9999999):
meanVals = mean(dat... |
3,511 | 79522db1316e4a25ab5a598ee035cf9b9a9a9411 | import torch
from torch import nn
from torch.nn import functional as F
import torchvision
import math
from torchvision.models.resnet import Bottleneck
from dataset import load_image, load_text, ALPHABET, MAX_LEN
class ResNetFeatures(nn.Module):
def __init__(self, pretrained=True):
super().__init__()
... |
3,512 | 7301a521586049ebb5e8e49b604cc96e3acc1fe9 | import os, pygame
import sys
from os import path
from random import choice
WIDTH = 1000
HEIGHT = 800
FPS = 60
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GRAY80 = (204, 204, 204)
GRAY = (26, 26, 26)
screen = pygame.disp... |
3,513 | aed6e1966d9e4ce7250ae3cacaf8854cab4b590c | from nltk.tokenize import RegexpTokenizer
token = RegexpTokenizer(r'\w+')
from nltk.corpus import stopwords
# with open('microsoft.txt','r+',encoding="utf-8") as file:
# text = file.read()
# text = '''
# Huawei Technologies founder and CEO Ren Zhengfei said on Thursday the Chinese company is willing to license its... |
3,514 | 6c98be473bf4cd458ea8a801f8b1197c9d8a07b3 | import serial
import time
import struct
# Assign Arduino's serial port address
# Windows example
# usbport = 'COM3'
# Linux example
# usbport = '/dev/ttyUSB0'
# MacOSX example
# usbport = '/dev/tty.usbserial-FTALLOK2'
# basically just see what ports are open - >>> ls /dev/tty*
# Set up s... |
3,515 | 93b12d1e936331c81522790f3f45faa3383d249e | #!/usr/bin/env python
# ------------------------------------------------------------------------------------------------------%
# Created by "Thieu Nguyen" at 19:47, 08/04/2020 %
# ... |
3,516 | 01153a695b4744465b706acb4c417217c5e3cefd | from django.db import models
import os
from uuid import uuid4
class Card_profile(models.Model):
def path_and_rename(self, filename):
upload_to = 'uploads'
ext = filename.split('.')[-1]
filename = '{}.{}'.format(uuid4().hex, ext)
return os.path.join(upload_to, filename)
MALE ... |
3,517 | 56b8b9884b8500ff70f59058484c4a351b709311 | import sys
def ReadFile(array, fileName):
with open(fileName, 'r') as f:
if f.readline().rstrip() != 'MS':
print("prosze podac macierz sasiedztwa")
for i in f:
el = list(map(int, i.rstrip().split()))
if len(el) > 1:
array.append(el)
def Prim(mat... |
3,518 | ae5dfa7fa6a0d7349d6ae29aeac819903facb48f | import sys
import os
import unittest
from wireless.trex_wireless_manager import APMode
from wireless.trex_wireless_manager_private import *
class APInfoTest(unittest.TestCase):
"""Tests methods for the APInfo class."""
def test_init_correct(self):
"""Test the __init__ method when parameters are corr... |
3,519 | 2060f57cfd910a308d60ad35ebbbf9ffd5678b9c |
# coding: utf-8
import pandas as pd
import os
import numpy as np
import json as json
import mysql.connector as sqlcnt
import datetime as dt
import requests
from mysql.connector.constants import SQLMode
import os
import glob
import re
import warnings
warnings.filterwarnings("ignore")
from pathlib import Path
# In[... |
3,520 | fb0dcb641dfb379751264dc0b18007f5d058d379 | import numpy as np
import matplotlib.pyplot as plt
def cos_Taylor2(x, n):
s = 0
a = 1
for i in range(0, n+1):
s = s+a
a = -a*x**2 / ((2*i+1)*(2*i+2))
return s, abs(a)
vcos = np.vectorize(cos_Taylor2)
def cos_two_terms(x):
s = 0
a = 1
s = s+a
a = -a*x**2 / ((2*0+1)*(2*... |
3,521 | 0e7d4b73cedf961677e6b9ea5303cdb3a5afa788 | #!/usr/bin/env python3
import fileinput
mem = [int(n.strip()) for n in next(fileinput.input()).split()]
size = len(mem)
states = set()
states.add('.'.join(str(n) for n in mem))
part2 = None
steps = 0
while True:
i = mem.index(max(mem))
x = mem[i]
mem[i] = 0
while x > 0:
i += 1
mem[i ... |
3,522 | a4f4137b9310ebc68515b9cae841051eda1f0360 | import random
consonants = [
'b', 'c', 'd', 'f', 'g',
'h', 'j', 'k', 'l', 'm',
'n', 'p', 'q', 'r', 's',
't', 'v', 'w', 'x', 'y',
'z'
]
vowels = [
'a', 'e',' i', 'o', 'u'
]
def make_word(user_input):
word = ""
for letter in user_input:
letter = letter.lower()
if letter... |
3,523 | 2e2de50a7d366ca1a98d29b33ed157a1e8445ada | # (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this... |
3,524 | 48311ee17a3f2eca8db32d7672f540fa45a7a900 | #!/usr/bin/env python
from LCClass import LightCurve
import matplotlib.pyplot as plt
import niutils
def main():
lc1821 = LightCurve("PSR_B1821-24/PSR_B1821-24_combined.evt")
lc0218 = LightCurve("PSR_J0218+4232/PSR_J0218+4232_combined.evt")
fig, ax = plt.subplots(2, 1, figsize=(8, 8))
ax[0], _ = lc18... |
3,525 | 426a8fb6d1adf5d4577d299083ce047c919dda67 | '''
EXERCICIO: Faça um programa que leia quantidade de pessoas que serão convidadas para uma festa.
O programa irá perguntar o nome de todas as pessoas e colcar num lista de convidados.
Após isso deve imprimir todos os nomes da lista
'''
'''
qtd = int(input("Quantas pessoas vão ser convidadas?"))
lista_pe... |
3,526 | e59404149c739a40316ca16ab767cbc48aa9b685 | # -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
import datetime
class GoldpriceSpider(scrapy.Spider):
name = 'goldprice'
allowed_domains = ['g-banker.com']
start_urls = ['https://g-banker.com/']
def __init__(self):
self.browser = webdriver.PhantomJS()
self.price =... |
3,527 | ba78a1e29736c4f109a0efc6f5b9993994661058 | '''
Created on June 24, 2019
@author: Andrew Habib
'''
import json
import jsonref
import sys
from jsonsubschema.api import isSubschema
def main():
assert len(
sys.argv) == 3, "jsonsubschema cli takes exactly two arguments lhs_schema and rhs_schema"
s1_file = sys.argv[1]
s2_file = sys.argv[2]
... |
3,528 | 4f116f3eec9198a56a047ab42ed8e018ebb794bb | def Hello_worlder(x):
a=[]
for i in range(x):
a.append('Hello world')
for i in a:
print(i)
Hello_worlder(10)
|
3,529 | f33190df35a6b0b91c4dd2d6a58291451d06e29a | # -*- coding: utf-8 -*-
import scrapy
import json, time, sys, random, re, pyssdb
from scrapy.utils.project import get_project_settings
from spider.items import GoodsSalesItem
goods_list = []
'''获取店铺内产品信息'''
class PddMallGoodsSpider(scrapy.Spider):
name = 'pdd_mall_goods'
mall_id_hash = 'pdd_mall_id_ha... |
3,530 | d84a7e16471c604283c81412653e037ecdb19102 | import os
bind = '0.0.0.0:8000'
workers = os.environ['GET_KEYS_ACCOUNTS_WORKERS']
|
3,531 | 076b852010ddcea69a294f9f2a653bb2fa2f2676 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 1 10:18:11 2017
@author: Duong
"""
import pandas as pd
import matplotlib.pyplot as plt
import psycopg2
from pandas.core.frame import DataFrame
# DBS verbinden
database = psycopg2.connect(database="TeamYellow_election", user="student", password="pas... |
3,532 | 005ea8a1e75447b2b1c030a645bde5d0cdc8fb53 | t3 = float(input('Digite um numero: '))
print('o dobro deste numero é', t3 * 2)
print('O triplo deste numero é', t3 * 3)
print('E a raiz quadrada deste numero é', t3**(1/2)) |
3,533 | fc0c8deb3a5a57934c9e707911c352af55100c3c | print(sum([int(d) for d in str(pow(2,1000))]))
|
3,534 | f566c42674728f1874d89b15102627c3b404c9a0 | #!/usr/bin/env python3
import sys
import cksm
from pathlib import Path
VIRTUAL_TO_ROM = 0x800ff000
def patch_rom(rom_path, payload_path, c_code_path, entry_code_path, out_path):
rom = list(Path(rom_path).read_bytes())
payload = list(Path(payload_path).read_bytes())
c_code = list(Path(c_code_path).read_b... |
3,535 | 82f8bfd95fea3025bed2b4583c20526b0bd5484f | from flask import Flask, abort, url_for, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('login.html')
# #redirect demo
# @app.route('/login', methods=['POST', 'GET'])
# def login():
# if request.method == 'POST' and request.form['username'] == 'admin':
# ... |
3,536 | 028c2193e180ccdbfdcc51e5d061904ea1d6164e | #!/usr/bin/python
import errno
import fuse
import stat
import time
#from multiprocessing import Queue
from functools import wraps
from processfs.svcmanager import Manager
import processfs.svcmanager as svcmanager
fuse.fuse_python_api = (0, 2)
_vfiles = ['stdin', 'stdout', 'stderr', 'cmdline', 'control', 'status']
... |
3,537 | 430b5ca7212983743cadc36a2ada987bb721174a | import numpy as np
import sympy as sp
from copy import copy
from typing import Any, get_type_hints, Dict
from inspect import getclosurevars, getsource, getargs
import ast
from ast import parse, get_source_segment
from .numpy import NumPy
from .torch import torch_defs
defines = {}
defines.update(torch_defs)
def che... |
3,538 | 22b8ecfecc0e76d758f14dea865a426db56c6343 | import json
import unittest
from pathlib import Path
from deepdiff import DeepDiff
from electricitymap.contrib import config
CONFIG_DIR = Path(__file__).parent.parent.joinpath("config").resolve()
class ConfigTestcase(unittest.TestCase):
def test_generate_zone_neighbours_two_countries(self):
exchanges =... |
3,539 | ac14e88810b848dbf4ff32ea99fd274cd0285e1c | """ Codewars kata: Evaluate mathematical expression. https://www.codewars.com/kata/52a78825cdfc2cfc87000005/train/python """
#######################################################################################################################
#
# Import
#
###########################################################... |
3,540 | fdf6c28e65b50c52550a95c2d991b1eb3ec53a2f | """
@file
@brief One class which visits a syntax tree.
"""
import inspect
import ast
from textwrap import dedent
import numpy
from scipy.spatial.distance import squareform, pdist
from .node_visitor_translator import CodeNodeVisitor
def py_make_float_array(cst, op_version=None):
"""
Creates an array with a sin... |
3,541 | cef6b5ef2082dc5910806550d9a9c96357752baf | from unittest import TestCase, main as unittest_main, mock
from app import app
from bson.objectid import ObjectId
'''
dummy data to use in testing create, update, and delete routes
(U and D not yet made)
Inspiration taken from Playlister tutorial.
'''
sample_offer_id = ObjectId('5349b4ddd2781d08c09890f4')
sample_offer... |
3,542 | 67904f3a29b0288a24e702f9c3ee001ebc279748 | class ListNode:
def __init__(self, val: int, next=None):
self.val = val
self.next = next
def reverseKGroup(head: ListNode, k: int) -> ListNode:
prev, cur, rs, successor = None, head, head, None
def reverseK(node: ListNode, count: int) -> ListNode:
nonlocal successor
nonloc... |
3,543 | 1810fee40ff8a99871ecc1d024f6794a68ee54e8 | from marshmallow import fields
from server.common.database import Media
from server.common.schema.ref import ma
class MediaSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = Media
fields = ('id', 'name', 'mimetype', 'extension', 'owner', '_links')
dump_only = ('id', 'owner', '_links')
... |
3,544 | 49c3c3b8c4b097f520456736e31ac306a9f73ac7 |
class Virus:
def __init__(self, _name, _age, _malignancy):
self.name = _name
self.age = _age
self.malignancy = _malignancy
def set_name(self, _name):
self.name = _name
def set_age(self, _age):
self.age = _age
def set_malignancy(self, _malignancy):
... |
3,545 | aec5280869a780bbd93ef24b659d9959f7b81426 | import imp
from django.shortcuts import render
# ***************** API ****************
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser,FileUploadParser,MultiPartParser,FormParser
from .models import *
from django.http import Http404
from .serializers import *
from re... |
3,546 | 7b35a7f28c11be15fe2ac8d6eae4067ac5379f3e | def test(a):
"""
This function return square of number
"""
return (a**2)
print(test(2))
help(test)
test.__doc__
|
3,547 | f66f82c5c2842fc4fcae2251d4a16a9850230041 | # Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context, loader
from django.db import transaction
from django.db.models import Q
from maximus.models import Mercenary, Team, TeamMember, Tournament, TournamentTeam, TournamentMatchup, Matchup, MatchupStatis... |
3,548 | 16a95573c4fccc10bdc5e37b307d0c85714b328c | import PyInstaller.__main__
import os
import shutil
# Paths
basePath = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir))
srcPath = os.path.join(basePath, 'src')
outPath = os.path.join(basePath, 'out')
workPath = os.path.join(outPath, 'work')
# Bundle
PyInstaller.__main__.run([
'--clean',
... |
3,549 | f6cebf6ec848a06f81c4e1f584ebb83f4d9ff47c | # -*- coding: utf-8 -*-
'''
Created on Dec 22, 2014
@author: Alan Tai
'''
from handlers.handler_webapp2_extra_auth import BaseHandler
from models.models_porn_info import WebLinkRoot, WebLinkPornTemp, WebLinkPorn,\
Tag
from dictionaries.dict_key_value_pairs import KeyValuePairsGeneral
from bs4 import BeautifulSoup
... |
3,550 | b33af7aff0f3fde6499d5e24fc036d5bd74b6e47 | rom diseas import Disease
from parse import analyzing
from config import FILE_NAME
from random import randint
if __name__ == '__main__':
"""
Main module that runs the program.
"""
def working_with_user(disea):
print('Choose what you want to know about that disease:\naverage_value(will return th... |
3,551 | a19b4928c9423dae6c60f39dbc5af0673b433c8e | from flask_opencv_streamer.streamer import Streamer
import cv2
import numpy as np
MASK = np.array([
[0, 1, 0],
[1, -4, 1],
[0, 1, 0]
])
port = 3030
require_login = False
streamer = Streamer(port, require_login)
video_capture = cv2.VideoCapture('http://149.43.156.105/mjpg/video.mjpg')
whi... |
3,552 | d32496c9bce86f455b24cd9c6dc263aee1bf82af | import requests
from bs4 import BeautifulSoup
import json
import geojson
import re
import time
_apiKey = "SNgeI1tCT-oihjeZDGi6WqcM0a9QAttLhKTecPaaETQ"
def Geocode(address, apiKey):
URL = 'https://geocode.search.hereapi.com/v1/geocode'
# Параметры запроса
params = {
'q': address,
'apiKey':... |
3,553 | ab27780b19db6854855af51eea063f07d9eb7302 | import datetime
import subprocess
from time import sleep
from flask import render_template, redirect, request, url_for, flash, abort
from dirkules import app, db, scheduler, app_version
import dirkules.manager.serviceManager as servMan
import dirkules.manager.driveManager as driveMan
import dirkules.manager.cleaning as... |
3,554 | 64a590d31be98f7639034662b2a322e5572cc1ae | # coding=utf-8
# flake8:noqa
from .string_helper import (
camelize, uncamelize,
camelize_for_dict_key, camelize_for_dict_key_in_list,
uncamelize_for_dict_key, uncamelize_for_dict_key_in_list
)
from .datetime_helper import datetime_format
from .class_helper import override
from .paginate import paginate2di... |
3,555 | 30d75aafd9612ac02557b947fc4e3c2f7322a7fd | import math
getal1 = 5
getal2 = 7
getal3 = 8
getal4 = -4
getal5 = 2
print(getal1*getal2+getal3)
print(getal1*(getal2+getal3))
print(getal2+getal3/getal1)
print((getal2+getal3)/getal1)
print(getal2+getal3%getal1)
print(abs(getal4*getal1))
print(pow(getal3,getal5))
print(round(getal5/getal2,2))
print(... |
3,556 | 0aa419b0045914b066fbec457c918d83276f2583 | from matplotlib import pyplot as plt
from read_and_calculate_speed import get_info_from_mongodb
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['font.family'] = 'sans-serif'
def mat_line(speed_time_info, interface, direction, last_time):
# 调节图形大小,宽,高
fig = plt.figure(figsize=(6, 6))
# 一共一行,每行一图... |
3,557 | 9c277030ef384d60e62c2c48e38a1271a43826d6 | __author__ = 'dongdaqing'
import threading,time
class MyThread(threading.Thread):
def __init__(self, name=None):
threading.Thread.__init__(self)
self.name = name
def run(self):
print time.strftime('%Y-%m-%d %H-%M-%S',time.localtime())
print self.name
def test():
for i in r... |
3,558 | f49b80d0b8b42bafc787a36d0a8be98ab7fa53e7 | from turtle import Turtle
class Paddle(Turtle):
def __init__(self, x_position, y_position):
super().__init__()
self.shape('square')
self.shapesize(stretch_wid=5, stretch_len=1)
self.penup()
self.color("white")
self.goto(x=x_position, y=y_position)
self.speed... |
3,559 | 7bc2a02d85c3b1a2b7ed61dc7567d1097b63d658 | from setuptools import setup, find_packages
setup(
name='testspace-python',
version='',
packages=find_packages(include=['testspace', 'testspace.*']),
url='',
license="MIT license",
author="Jeffrey Schultz",
author_email='jeffs@s2technologies.com',
description="Module for interacting wit... |
3,560 | 3b7839347f24d39904d29d40e688a5dfd63534d7 | import numpy as np
import tensorflow as tf
from tfrecords_handler.moving_window.tfrecord_mean_reader import TFRecordReader
from configs.global_configs import training_data_configs
class StackingModelTester:
def __init__(self, **kwargs):
self.__use_bias = kwargs["use_bias"]
self.__use_peepholes = ... |
3,561 | 2d5993489ff3120d980d29edbb53422110a5c039 | '''
Написати програму, що визначає, яка з двох
точок знаходиться ближче до початку координат.
'''
import re
re_number = re.compile("^[-+]?\d+\.?\d*$")
def validator(pattern,promt):
text=input(promt)
while not bool(pattern.match(text)):
text = input(promt)
return text
def number_validator(promt)... |
3,562 | 4942b20a8e4f58c52b82800fb4c59db169cd8048 | #!/usr/bin/env python
# encoding=utf-8
import MySQLdb
import re
# 打开数据库连接
db = MySQLdb.connect(host='wonderfulloffline.mysql.rds.aliyuncs.com',port=3306,user='wonderfull_ai',password='868wxRHrPaTKkjvC', db='wonderfull_ai_online', charset='utf8' )
def load_stop_word():
stop_word=set()
with open("data... |
3,563 | d60690892eddda656c11470aacd1fdc9d07a721a | # CIS 117 Python Programming - Lab 10
# Bryce DesBrisay
def middle(string):
characters = list(string)
length = len(characters)
middleNum = round((length + .5) / 2)
if length % 2 == 0:
return characters[middleNum - 1] + characters[middleNum]
else:
return characters[middleNum - 1]
de... |
3,564 | 4032503bba8a1dd273015d503f52b6ea2d932d1d |
from pprint import pprint
from collections import Counter
from copy import deepcopy
class Sudoku():
def __init__(self, grid):
'''
Initializes the grid
'''
self.grid = grid
self.sub_grid = self.create_sub_grid(self.grid)
def create_sub_grid(self, ... |
3,565 | e828c2792d508ba41c5dca3f4a255eee2611c333 | Max = 100010
a = [0 for i in range(Max)]
p = []
for i in range(2,Max):
if a[i ] == 0:
p.append(i)
j = i * i
while j < Max:
a[j ] = 1
j = j + i
cnt,j = 0,1
n = int(input())
while p[j] <= n :
if p[j ] - p[j-1] == 2: cnt = cnt + 1
j = j + 1
print(cnt) |
3,566 | 5c4c893caa19e58491e641420261bb70e7202cf0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
# Describes where to search for the config file if no location is specified
DEFAULT_CONFIG_LOCATION = "config.json"
DEFAULT_CONFIG = {
"project": None,
"fixed_model_name": None,
"config": DEFAULT_CONFIG_LOCATION,
"data": None,
"emulate": None... |
3,567 | d8a09f9952856da69120fae6221636dd5bd8c93e | # python examples/mnist_rnn.py --bsz 128 --bsz-eval 256
import sys
from argparse import ArgumentParser
import pytorch_lightning as pl
import torch.nn as nn
import torch.optim as optim
from loguru import logger
from slp.config.config_parser import make_cli_parser, parse_config
from slp.data.collators import SequenceCl... |
3,568 | 27edc753ebb9d60715a2ffa25d77e69ef363d010 | import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from scipy.stats import chisquare, chi2, binom, poisson
def f_1(x, a):
return (1 / (x + 5)) * np.sin(a * x)
def f_2(x, a):
return np.sin(a * x) + 1
def f_3(x, a):
return np.sin(a * (x ** 2))
def f_4(x, a):
ret... |
3,569 | ee489c2e313a96671db79398218f8604f7ae1bf3 | # -*- coding: utf-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2017
# All rights reserved.
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source ... |
3,570 | 53127de883fb5da3214d13904664566269becba6 | # 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 writing, software
# distributed under t... |
3,571 | dc27781d0c3129d11aa98a5889aea0383b5a49d6 | from django.db import models
from django.contrib.auth.models import User
class CustomUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='custom_user')
def get_current_score(self):
acc = 0
for score in self.user_scores.all():
acc += score.p... |
3,572 | 32869a88bb59d47281249b6ebe2357328beb0359 | #!/usr/bin/env python
def question():
print("02. 「パトカー」+「タクシー」=「パタトクカシーー」")
print("「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.")
def main():
str1 = "パトカー"
str2 = "タクシー"
print(''.join([x[0] + x[1] for x in zip(str1, str2)]))
if __name__ == '__main__':
question()
main()
|
3,573 | e75bee4e014aa369131c3e200ce874a8840b5690 | from GRAFICA_BRESENHAMS import Bresenhams
def main():
x = int(input('INGRESA VALOR PARA X: \n'))
y = int(input('INGRESA VALOR PARA Y: \n'))
x1 = int(input('INGRESA VALOR PARA X1: \n'))
y1 = int(input('INGRESA VALOR PARA Y1: \n'))
Bresenhams(x,y,x1,y1)
if __name__=='__main__':
main() |
3,574 | ff99b5fd168d7987e488d7f6d0455619e988f15a | import numpy as np
import math
import activations
class FC_layer():
def __init__(self, input_size, output_size, weight_init_range, activation, debug):
self.type = "FC"
self.activation_name = activation
self.shape = (input_size, output_size)
self.activation = activations.get_activati... |
3,575 | 17cd6746e58a7f33bc239c1420d51c6810ed02d8 | from turtle import *
import time
import random
colormode(255)
class Ball(Turtle):
def __init__(self, x,y,dx,dy,r):
Turtle.__init__(self)
self.pu()
self.goto(x,y)
self.dx = dx
self.dy = dy
self.r = r
self.shape("circle")
self.shapesize(r/10)
r ... |
3,576 | c14673b56cb31efb5d79859dd0f6f3c6806e1056 | import main.Tools
class EnigmaRotor:
def __init__(self, entrata, uscita, rotore_succ=None, flag=True):
self.entrata=entrata.copy()
self.uscita=uscita.copy()
self.numeroSpostamenti=0
self.flag=flag
self.rotore_succ=rotore_succ
#Imposta il rotore sull'elemento specificat... |
3,577 | bd5f298027f82edf5451f5297d577005674de4c3 | import time
import random
import math
people = [('Seymour', 'BOS'),
('Franny', 'DAL'),
('Zooey', 'CAK'),
('Walt', 'MIA'),
('Buddy', 'ORD'),
('Les', 'OMA')]
destination = 'LGA'
flights = dict()
for line in file('schedule.txt'):
origin, dest, depart, arrive, price... |
3,578 | 6e3aa677985d7bd91bfbbd2078665206839bac63 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import paramiko
import commands
def ip_check():
"""
Parses attributes for given hosts,
then checks if hosts are up
and then calls path_check function with working hosts.
"""
hosts = []
valid_hosts = []
for item in sys.argv... |
3,579 | c385fe2af9aebc9c4a42d4db5a341fcedeec3898 | from django.shortcuts import render
# Create your views here.
from django.shortcuts import redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import Http404, HttpResponseForbidden
from django.shortcuts import render
from django.urls import reverse
from django.views.generic.edit import ... |
3,580 | 0577c274672bac333500535f21f568ade62100c7 |
# *Using Min & Max Exercise
def extremes(nums):
return (max(nums), min(nums))
|
3,581 | fe0d6cc03512d54d2d8722551e3f2a7c1bf43997 | #!/opt/Python/2.7.3/bin/python
import sys
from collections import defaultdict
import numpy as np
import re
import os
import argparse
from Bio import SeqIO
def usage():
test="name"
message='''
python CircosConf.py --input circos.config --output pipe.conf
'''
print message
def fasta_id(fastafile):
... |
3,582 | 7a4044acaa191509c96e09dcd48e5b951ef7a711 | # put your python code here
time_one = abs(int(input()))
time_two = abs(int(input()))
time_three = abs(int(input()))
time_four = abs(int(input()))
time_five = abs(int(input()))
time_six = abs(int(input()))
HOUR = 3600 # 3600 seconds in an hour
MINUTE = 60 # 60 seconds in a minute
input_one = time_one * HOUR + time... |
3,583 | 91cf1f4cf34ac9723be4863e81149c703adca27a | import sys
sys.path.append("..") # Adds higher directory to python modules path.
from utils import npm_decorator
# num_node = 3
@ npm_decorator(3)
def scenario():
"""
1. Check each peer's genesis block
2. Generate new blocks on each peer
2.1. 2 blocks on peer #1
2.2. 4 blocks on peer #2
... |
3,584 | 9e98a361ef20049cba488b86ad06eb92b3d29d11 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
self.mem = dict()
if root is None:
... |
3,585 | 1073845131afb2446ca68ee10092eeb00feef800 | # uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 2.7.5 (default, Jul 13 2018, 13:06:57)
# [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
# Embedded file name: ./authx/migrations/0001_initial.py
# Compiled at: 2018-08-23 19:33:14
# Size of source mod 2**32: 2715 bytes
from __future__ import un... |
3,586 | 8d3f8872a3d5c4351551dc2d46839763d28ebd70 | # For better usage on ddp
import torch
from pytorch_lightning.metrics import Metric
import cv2
import numpy as np
import skimage
import torch.tensor as Tensor
class SegMetric(Metric):
def __init__(self, iou_thr, prob_thr, img_size, dist_sync_on_step=False):
super().__init__(dist_sync_on_step=dist_sync_on... |
3,587 | fd45657083942dee13f9939ce2a4b71ba3f67397 | # -*- coding: utf-8 -*-
# @Time : 2022-03-09 21:51
# @Author : 袁肖瀚
# @FileName: WDCNN-DANN.py
# @Software: PyCharm
import torch
import numpy as np
import torch.nn as nn
import argparse
from model import WDCNN1
from torch.nn.init import xavier_uniform_
import torch.utils.data as Data
import matplotlib.py... |
3,588 | 97c97f18d1b93dc54538a0df7badafd961fdcb9c | from manimlib.imports import *
class A_Scroller(Scene):
CONFIG={
"camera_config":{"background_color":"#FFFFFF"}
}
def construct(self):
text_1 = Text("3493", color="#DC3832")
text_2 = Text("3646", color="#221F20").shift(2*RIGHT)
text_3 = Text("4182", color="#2566AD").shift(4*RIGHT)
text_4 = Te... |
3,589 | bb847480e7e4508fbfb5e7873c4ed390943e2fcf | #import os
import queue as q
#Считываем ввод
file = open('input.txt', 'r')
inp = ''
for i in file:
for j in i:
if (j != '\n'):
inp += j
else:
inp += ' '
inp += ' '
#print(inp)
file.close()
#Записываем все пути в двумерный массив
tmp = '' #Переменная для хранения текущего ... |
3,590 | daeb11000978d14a05ea62113dcf6e30d6a98b15 | # Enunciado: faça um programa que leia um ano qualquer e mostre se ele é BISEXTO.
ano = int(input('\nInforme o ano: '))
ano1 = ano % 4
ano2 = ano % 100
if ano1 == 0 and ano2 != 0:
print('\nO ano de {} é Bissexto !!'.format(ano))
else:
print('\nO ano de {} não foi Bissexto !!'.format(ano))
|
3,591 | 3ecc9ce82d9c902958a4da51ce7ee3c39b064b2b | import datetime
from django.views.generic import DetailView, ListView
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import get_list_or_404, render_to_response, get_object_or_404
from django.template import RequestContext
from django.co... |
3,592 | 64b4deaad548a38ba646423d33fc6a985483a042 | ########################################
__author__ = "Abdelrahman Eldesokey"
__license__ = "GNU GPLv3"
__version__ = "0.1"
__maintainer__ = "Abdelrahman Eldesokey"
__email__ = "abdo.eldesokey@gmail.com"
########################################
import torch
import torch.nn.functional as F
import torch.nn as nn
from to... |
3,593 | 9af2b94c6eef47dad0348a5437593cc8561a7deb | import numpy
numpy.random.seed(1)
M = 20
N = 100
import numpy as np
x = np.random.randn(N, 2)
w = np.random.randn(M, 2)
f = np.einsum('ik,jk->ij', w, x)
y = f + 0.1*np.random.randn(M, N)
D = 10
from bayespy.nodes import GaussianARD, Gamma, SumMultiply
X = GaussianARD(0, 1, plates=(1,N), shape=(D,))
alpha = Gamma(1e-5, ... |
3,594 | 2fbf312e1f8388008bb9ab9ba0ee4ccee1a8beae | # -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-04-12 12:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cstasker', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
3,595 | d60810ea0b19cc9163ce526e6a5a54da9c8b3f68 | ###############################################################################
# Copyright (c) 2017-2020 Koren Lev (Cisco Systems), #
# Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others #
# #
... |
3,596 | 36fce3837e0341d94ff6099a06be8cf757a1cfa9 | from pyspark import SparkContext, SparkConf
conf = SparkConf().setAppName("same_host").setMaster("local")
sc = SparkContext(conf=conf)
julyFirstLogs = sc.textFile("/Users/iamsuman/src/iamsuman/myspark/mypyspark/data/nasa_19950701.tsv")
augFirstLogs = sc.textFile("/Users/iamsuman/src/iamsuman/myspark/mypyspark/data/na... |
3,597 | 7b01e81c3e31e0a315ee01f36bf1b1f7384a9d10 | from tracking.centroidtracker import CentroidTracker
from tracking.trackableobject import TrackableObject
import tensornets as nets
import cv2
import numpy as np
import time
import dlib
import tensorflow.compat.v1 as tf
import os
# For 'disable_v2_behavior' see https://github.com/theislab/scgen/issues/14
tf.disable_v2... |
3,598 | bafb6c09ecd0017428441e109733ebcb189863ad | operation = input('operation type: ').lower()
num1 = input("First number: ")
num2 = input("First number: ")
try:
num1, num2 = float(num1), float(num2)
if operation == 'add':
result = num1 + num2
print(result)
elif operation == 'subtract':
result = num1 - num2
print(result)
... |
3,599 | 628e625be86053988cbaa3ddfe55f0538136e24d | ##################
#Drawing Generic Rest of Board/
##################
def drawBoard(canvas,data):
canvas.create_rectangle(10,10,data.width-10,data.height-10, fill = "dark green")
canvas.create_rectangle(187, 160, 200, 550, fill = "white")
canvas.create_rectangle(187, 160, 561, 173, fill = "white")
can... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.