text stringlengths 38 1.54M |
|---|
#! /usr/bin/python3
for i in range(10):
if i == 0:
print("Current number " + str(i) + " Previous number " + str(i) + " sum "+ str(i+i))
else:
print("Current number " + str(i) + " Previous number " + str(i-1) + " sum "+ str(i+(i-1)))
|
fo=open("hello.txt","r")
print("NAME OF FILE: ",fo.name)
line=fo.readline()
print("READ LINE: %s" %(line))
p=fo.tell()
print("POSITION OF POINTER IS: %d"%p)
print("----------------------------------------")
fo.seek(0,0)
g=fo.tell()
print("POSITION OF POINTER IS: ",g)
|
import pyparsing as _p
def parse(liberty_string):
#_p.ParserElement.enablePackrat() <- dont, kills memory - and slower...
identifier=_p.Word(_p.alphanums+'._') # a name for..
EOL = _p.LineEnd().suppress() # end of line
ws = ' \t'
_p.ParserElement.setDefaultWhitespaceChars(ws)
linebreak = _p.Sup... |
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return 0
# 2 is the only even prime number
if n == 2:
return 0
# all other even numbers are not primes
if not n & 1:
re... |
from __future__ import absolute_import, unicode_literals
from .base import *
from .secrets import DEBUG
try:
from .local import *
except ImportError:
pass
|
from collections import Counter
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
L = list()
c1 = Counter(nums1)
c2 = Counter(nums2)
print(c1,c2)
for k in... |
def compute(pankcakes):
parts = 1
for idx in range(1, len(pankcakes)):
if pankcakes[idx] != pankcakes[idx-1]:
parts += 1
if pankcakes[-1] == '+':
parts -= 1
return parts
cases = input()
for idx in range(int(cases)):
pankcakes = input()
print("Case #{}: {}... |
import nltk
from nltk import word_tokenize
from nltk.corpus import brown
import os, os.path
import math, time
def noOfFilesCnt():
return totalCnt
def frequencyOfWord(word,listOfWords):
count = 0
for i in listOfWords:
if word == i:
count = count + 1
return count
#To sort the tfidf words
def sorter(tfidf):... |
import github
import json
import os
token = os.environ['INPUT_TOKEN']
repoName = os.environ['GITHUB_REPOSITORY']
projectCardId = os.environ['INPUT_PROJECTCARDID']
displayUserJson = json.loads(os.environ['INPUT_DISPLAYUSERJSON'])
displayUrlJson = json.loads(os.environ['INPUT_DISPLAYURLJSON'])
# Connect to GitHub
g = ... |
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtSql import *
import time
class returnBookDialog(QDialog):
return_book_successful_signal=pyqtSignal()
def __init__(self, StudentId, parent=None):
super(returnBookDialog, self).__init__(parent)
... |
import picamera
from openflexure_stage import OpenFlexureStage
import numpy as np
from camera_stuff import get_numpy_image, find_template
import time
import h5py
from contextlib import closing
import data_file
def measure_txy(n, start_time, camera, templ8): #everything used in a definition should be put in as an argum... |
# def scope_test(counter=0):
# print('helos')
# if(counter == 10):
# return
# else:
# print(counter)
# scope_test(counter+1)
# def indsider(x):
# print(x)
# # indsider()
# scope_test()
# def recursion(coin, amount, coinAccumulator):
# # if 100 / 25 - amount divides evenly
# if(amount / coin >... |
import numpy as np
import numpy.random as npr
import scipy as sc
from scipy import linalg
from mimo.abstraction import Distribution
class MatrixNormalWithPrecision(Distribution):
def __init__(self, M=None, V=None, K=None):
self.M = M
self._V = V
self._K = K
self._V_chol = None
... |
from rest_framework.permissions import BasePermission
from ..models import Campaign
class IsOwner(BasePermission):
"""Custom permission class to allow only campaign owners to edit them."""
def has_object_permission(self, request, view, obj):
"""Return True if permission is granted to the campaign own... |
from django.conf.urls import include, url
from django.contrib import admin
from tweets.views import Index, Profile, PostTweet, HashTagCloud, Search
admin.autodiscover()
urlpatterns = [
url(r'^$', Index.as_view()),
url(r'^user/(\w+)/$', Profile.as_view()),
url(r'^admin/', admin.site.urls),
url(r'^user/(\w+)/post/$', P... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 16 02:37:34 2019
@author: dbhmath
"""
import time
import click
import sys
import pandas as pd
import json
from selenium import webdriver
def unanota(calificaciones, driver, i, CX, delay=2.5):
cod = -1
ncorte = {'C1': 1, 'C2': 2, 'C3': 3}
try:
... |
import scipy as sp
import numpy as np
from skimage.segmentation import clear_border
from skimage.feature import peak_local_max
from skimage.measure import regionprops
import scipy.ndimage as spim
import scipy.spatial as sptl
from porespy.tools import get_border, extract_subsection, extend_slice
from porespy.filters imp... |
""" ``django-structlog`` is a structured logging integration for ``Django`` project using ``structlog``.
"""
default_app_config = "django_structlog.apps.DjangoStructLogConfig"
name = "django_structlog"
VERSION = (1, 5, 0)
__version__ = ".".join(str(v) for v in VERSION)
|
from __future__ import division
import const
import numpy
import math
prior_prob = []
prob = []
count = []
count2 = []
'''
This method is used to shuffle the training label and training image
'''
def randomize(randomList, data):
ans = []
for i in range(len(randomList)):
ans.append(data[randomList[i]... |
#!/usr/bin/env python
import numpy as np
import os, sys, logging, math
import matplotlib.pylab as plt
from PIL import Image, ImageFilter, ImageOps
class Histogaram:
image = None
# constructor
def __init__(self, input):
# open and process the image
try:
self.image = Image.ope... |
#a Imports
from gjslib.math import vectors, matrix
#a c_set_of_lines
class c_set_of_lines(object):
def __init__(self):
self.lines = []
pass
def add_line(self, pt, drn):
drn = list(drn)
drn = vectors.vector_normalize(drn)
self.lines.append( (pt,drn) )
pass
def... |
import socket,struct,pickle,logging,time
from Peer import Peer
KEEP_ALIVE = struct.pack('!B',0)
POSITION = struct.pack('!B',1)
GET_PEERS = struct.pack('!B',2)
GET_STREAM = struct.pack('!B',3)
STOP = struct.pack('!B',4)
CLOSE = struct.pack('!B',5)
ERROR = struct.pack('!B',6)
HAVE = struct.pack('!B',7)
CONNECTION_TIME... |
# Generated by Django 3.2.8 on 2021-10-21 07:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("zerver", "0425_realm_move_messages_between_streams_limit_seconds"),
]
operations = [
migrations.AddField(
model_name="realmuserde... |
# -*- coding: utf-8 -*-
import scrapy
class LianjiaSpider(scrapy.Spider):
# todo 这边暂时只处理普通租房,不处理公寓的信息。
name = 'lianjia'
allowed_domains = ['lianjia.com']
# start_urls = ['https://sz.lianjia.com/zufang/']
start_urls = []
# 广州市内含有的 https://www.lianjia.com/city/ 参考这儿。
# locationCode = ['dg',... |
'''
https://leetcode.com/problems/friend-circles/description/
There are N students in a class. Some of them are friends,
while some are not. Their friendship is transitive in nature.
For example, if A is a direct friend of B, and B is a direct friend of C,
then A is an indirect friend of C. And we defined a friend... |
datasetList = [
'QCD_Pt_15to30_TuneCUETP8M1_13TeV_pythia8',
'QCD_Pt_30to50_TuneCUETP8M1_13TeV_pythia8',
'QCD_Pt_50to80_TuneCUETP8M1_13TeV_pythia8',
'QCD_Pt_80to120_TuneCUETP8M1_13TeV_pythia8',
'QCD_Pt_120to170_TuneCUETP8M1_13TeV_pythia8',
'QCD_Pt_170to300_TuneCUETP8M1_13TeV_pythia8',
'QCD_Pt_300to470_TuneCUETP8M1_13TeV... |
"""
This is to plot the TS from the EDGAR six experiments
data inputs are forty years of monthly TS
first step is to process the monthly TS into monthly mean
second step is to process annual mean of monthly mean
"""
import site
import os
import numpy as np
import netCDF4 as nc4
from scipy import stats
imp... |
from agent.reactiveagent import ReactiveAgent, Stance
from game import start_game
from sys import argv
from agent.player import Player
has_player = False
def main():
global has_player
if not (len(argv) == 2 or len(argv) == 3):
raise ValueError("Must pass one or two command line arguments - number o... |
def solve(n):
if n == 0:
return "INSOMNIA"
m = n
obs = set(str(m))
while len(obs) < 10:
m += n
obs = obs.union(str(m))
return m
fin = open("A-large.in", "r")
fout = open("A-large.out", "w")
for t in xrange(1, int(fin.readline()) + 1):
sln = solve(int(fin... |
"""
run_auto_validation_tests.py
Will search all the sub-directories for scripts of the form starting with
validate_
and then run the scripts.
"""
import os, time, sys
import anuga
args = anuga.get_args()
#print args
# List any sub directory to exclude from validation.
# Current working directory ('.') shou... |
import unittest
from unittest import mock
def mocked_requests_post(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
if args[0] ... |
# --------------------------------------------------------------------------------
# Import
# --------------------------------------------------------------------------------
import torch
import time
import os
import tqdm
from utils.metrics import*
import torch.nn.functional as F
from base.trainer_base impor... |
import os
import time
from textwrap import fill
class Tutor:
def __init__(self):
self.bundle = None
self.led = None
self.button = None
self.row = 70
@staticmethod
def clear():
clear_cmd = 'clear'
if os.name == 'nt':
clear_cmd = 'cls'
o... |
'''
You are given two NONEMPTY linked lists representing two non-negative integers.
The digits are stored in REVERSE ORDER and each of their nodes contain a single
digit. Add the two numbers and return it as a linked list.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6-> 4)
Output: 7 -> 0 -> 8
'''
class node:
def __init_... |
class Solution:
def reorganizeString(self, st):
self.data = {}
for i in st:
if i not in self.data:
self.data[i] = 1
else:
self.data[i] += 1
m = max(self.data)
mv = self.data[m]
self.data[m] = 0
total = 0
for k, v in self.data.items():
total += v
print(total, mv) |
"""
class Employee:
def enterEmployeeDetails(self):
self.name = "Mark"
def displayEmployeeDetails(self):
print(self.name)
employee = Employee()
employee.displayEmployeeDetails()
# 'Employee' object has no attribute 'name'
# name not set when object created
# hence use "init" method
... |
import requests, json
apikey = "7cb9becaea566cc27d69991c345fa129"
base = "http://api.openweathermap.org/data/2.5/weather?"
city = "Austin"
compbase = f"{base}appid={apikey}&q={city}"
resp = requests.get(compbase)
x = resp.json()
if x["cod"] != "404":
y = x["main"]
w = x["wind"]
z = x["weather"]
currtem... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 9 15:32:05 2018
@author: rjovelin
"""
# use this script to check md5 and new headers on reheadered bams
# precondition: samtools need to be loaded
# module load samtools/1.5
import os
import sys
import subprocess
import argparse
import yaml
# use this function to mat... |
#http://eddmann.com/posts/depth-first-search-and-breadth-first-search-in-python/
#Adjacency list: build by storing each node in a dictionary along with a set containing their adjacent nodes
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
... |
import Levenshtein
def editsim(a: str, b: str, ignore_order=False) -> int:
"""
returns a score from 0 - 100 indicating the similarity score based on the edit distance between two strings.
NOTE: if clause at the beginning is specific for this notebook's experiments.
"""
try:
if a == "" or b... |
#!/usr/bin/env python2
import boto3
import botocore
import collections
import hashlib
import re
import signal
import sys
import threading
import urllib
import urlparse
class MessageHeader(collections.namedtuple('MessageHeader_', ['status_code', 'status_info'])):
def __str__(self):
return '{} {}'.format(sel... |
class Solution:
def successfulPairs(self, s: List[int], p: List[int], t: int) -> List[int]:
ans = []
p.sort()
n = len(p)
for ss in s:
tt = t // ss if t % ss == 0 else t // ss + 1
idx = bisect.bisect_left(p,tt)
ans.append(n - idx)
return ans... |
# stack is a vector of pancakes
def pancake(stack, counter):
# print stack
if len(stack) == 0:
return counter
if stack[-1] == "+":
return pancake(stack[:-1], counter)
else:
if stack[0] == "+":
numberOfPlus = 0
for e in stack:
if e == "+":
numberOfPlus += 1
else:
break
stack[:numberO... |
# coding:utf-8
from __future__ import unicode_literals
from django.db import models
from company.models import Organization, Staff
import os
# Create your models here.
class Pro(models.Model):
"""
Description: 项目
"""
org = models.ForeignKey(Organization, verbose_name='公司')
pro_name = models.CharF... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module: day21.py
Author: zlamberty
Created: 2016-12-02
Description:
day 21 puzzles for the advent of code (adventofcode.com/2016/day/21)
Usage:
<usage>
"""
import itertools
import os
import re
import eri.logging as logging
# -----------------------------... |
myNumbers = [23,234,345,4356234,243,43,56,2]
#Your code go here:
def increment_by_one(the_number):
# new_list = []
# new_list.append(the_numbers * 3)
# print(new_list)
# new_list.append(the_numbers) * 3
return the_number * 3
# return new_list
new_list = map(increment_by_one, myNumbers)
result... |
from mentor.questionaire.tests import UserLogin, AdminLogin
from mentor.questionaire.forms import QuestionaireForm, DownloadResponseForm
from datetime import date, timedelta
from mentor.users.models import User
from mentor.questionaire.models import Questionaire
class QuestionaireFormTest(UserLogin):
def test_at... |
'''
TEMPLATE for creating your own Agent to compete in
'Dungeons and Data Structures' at the Coder One AI Sports Challenge 2020.
For more info and resources, check out: https://bit.ly/aisportschallenge
BIO:
<Tell us about your Agent here>
'''
# import any external packages by un-commenting them
# if you'd like to tes... |
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from neomodel import db
from TestModel.models import person
# 数据库操作
def testdb(request):
#p1 = Person(id=7).save()
'''
p2 = Person.nodes.get(id=2)
p4 = Person.nodes.get(id=4)
print p2, p4
p2.knowing_p.connect = p4
if p2.knowing_p... |
import unittest
from adaptor.dleq import *
class TestsDLEQ(unittest.TestCase):
def test_dleq(self):
x = 10
y = 14
Y = y * G
X = x * G
R = x * Y
proof = dleq_prove(x, X, Y, R)
self.assertTrue(dleq_verify(X, Y, R, proof))
|
import sys
sys.stdin = open("D3_3809_input.txt", "r")
# 1. runtime error
# T = int(input())
# for test_case in range(T):
# N = int(input())
# data = []
# if N < 20:
# data = list(map(int, input().split()))
# else:
# ans = [list(map(int, input().split())) for _ in range(N // 20)]
# ... |
def total_cost(calls):
dict = {}
for call in calls:
date, _, length = call.split(" ")
dict[date] = dict.get(date,0) + ceil(int(length)/60)
return ...
# 第一种做法反思
# 使用Counter是非常优雅的写法
# 除此之外,普通的字典dict也可以达到相同的作用
# 原理:dict类型赋值的几种情况
# 情况1:key已经存在,则以下两种方式都可行
# dict[key] = 1
# dict[key] += 1
# 情况2:key不存... |
import numpy as np
from collections import defaultdict
from sklearn.metrics import classification_report, accuracy_score
from tqdm import tqdm
"""
NLPtutorial2020のDockerfile, requirement.txt, Makefileを使用
make docker-run FILE_NAME=./tutorial07/tutorial07.py
"""
class NN():
def __init__(self, λ=0.1, node=2, layer=1)... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 10:33:33 2020
@author: Administrator
"""
import os
import pandas as pd
path = r'D:\2020年工作\2020年维护指标年底收官\退服详单'
os.chdir(path)
df_not_choose = pd.read_excel('物理站址与铁塔站址对应关系信息表 (2020.10.14改)待确认.xlsx', sheet_name='曲靖')
df_not_choose = df_not_choose[df_not_choose['是否选择铁... |
# Goldbach's Conjecture
# @Author: Gavin Moore
# 3/4/2021
# v1.0
# Description: Given between 1 and 100 integers even integers between 4 and 32,000, determine the number of ways
# they can be represented as sums of two prime numbers. Output the number of representations, and each representation.
# Problem obtained fro... |
class Solution:
def find(self, parent, i):
if parent[i] != -1:
parent[i] = self.find(parent, parent[i])
return i
def union(self, parent, rank, i, j):
p1 = self.find(parent, i)
p2 = self.find(parent, j)
if p1 == p2:
return
if rank[p1] > ran... |
import pandas as pd
import csv
class User:
def __init__(self, index, file):
with open(file, 'rb') as csvfile:
info = csv.reader(csvfile)
self.name = info.iloc[index]['Name']
self.sex = info.iloc[index]['Sex']
self.age = info.iloc[index]['Age']
self.height = info... |
import requests
import json
import datetime
url = 'https://financialmodelingprep.com/api/v3/nasdaq_constituent?apikey=c1d5db3bf65299abe6068e556f5bed6e'
resp = requests.get(url=url)
list_stocks = resp.json() # Check the JSON Response Content documentation below
print('Done, count:', len(list_stocks))
with open('list... |
"""
****************************************************************************************************
:copyright (c) 2019-2021 URBANopt, Alliance for Sustainable Energy, LLC, and other contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
... |
#bill calculator
meal_amount=float(input("Enter meal amount($):"))
discount_meal_amount=meal_amount*0.50
service_charge=discount_meal_amount*0.10
gst=(discount_meal_amount+service_charge)*0.07
total=gst+service_charge+discount_meal_amount
print(" ")
print("Receipt")
print("cost of meal : $%.2f"%meal_amount)
print("50% ... |
param = 10
strdata = '전역변수'
def func1():
strdata = '지역변수'
print(strdata)
def func2(param):
param = 1
def func3():
global param
param = 50
func1()
print(strdata)
print(param)
func2(param)
print(param)
func3()
print(param)
print()
def reverse(x,y,z):
return z,y,x
ret = reverse (1,2,3)
print(... |
from flask import g, jsonify, request
from .db import get_db
from flask_restful import Resource
import bcrypt
def user_exist(username):
db = get_db()
user = db.Users.find_one({"Username":username})
print ("user:{}".format(user))
if user:
return True
else:
return False
def check_adm... |
from tutorial.settings.base import *
DEBUG = False
ALLOWED_HOSTS = ['api', 'wsgi', 'asgi']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': '!dlatl00',
'HOST': 'database',
'PORT':... |
"""
Metview Python use case
UC-07-pandas. The Analyst compute simple differences between observations and analysis
and use pandas to perform further computations
BUFR version - BUFR is not tabular or gridded, but we can use Metview Python
framework to extract a particular parameter to a tabular format (geopoints)
--... |
from collections import OrderedDict
import uuid
import time
from urllib.parse import quote, urlencode
import requests
import json
from .utils import hmacb64, parse_config
class AliyunSMS():
def __init__(self, config_file=None, access_key_id='', access_key_secret='', region_id='', host='http://dysmsapi.aliyuncs.co... |
class Solution:
def minPartitions(self, n: str) -> int:
nums = [int(i) for i in n]
return max(nums)
|
import logging
# Get an instance of a logger
logger = logging.getLogger('config')
import json
from os.path import join, dirname, isfile
DEFAULT_CONFIG = join(dirname(__file__), 'daphne.conf')
class ConfigurationLoader():
def __init__(self):
self.config = None
def load(self):
if(sel... |
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import style
style.use('seaborn-paper')
antenna_length = np.array([1, 0.8, 0.7, 0.6, 0.5, 0.4])
C_shunt = np.array([])
g = np.array([])/2
#with small pad
C_shunt_sp = np.array([])
g_sp = np.array([])/2 |
#coding=utf-8
'''
use if-idf algorithm to find key words in articles
also can be used in short sentence however the proformance is not so good.
'''
import sys
import jieba
from collections import Counter
jieba.user_dict = "./dictionary/user_dict.txt"
stop_words = set(['。', ',', ',', '.','“','”','、','\n',' ',' ... |
"""adding games/genres to db
Revision ID: 1db083b8d003
Revises: bb5ef27893de
Create Date: 2017-09-04 13:04:14.683378
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1db083b8d003'
down_revision = 'bb5ef27893de'
branch_labels = None
depends_on = None
def upgra... |
#!/usr/bin/env python3
import cv2
import dlib
import numpy as np
import pyautogui
import time
import webbrowser
time_old = time.time()
def shape_to_np(shape, dtype="int"):
coords = np.zeros((68, 2), dtype=dtype)
for i in range(0, 68):
coords[i] = (shape.part(i).x, shape.part(i).y)
return coords
def eye_on_mask(m... |
import numpy as np
from vtk_rw import read_vtk
vtk_file = '/nobackup/ilz3/myelinconnect/new_groupavg/profiles/smooth_1.5/%s/%s_lowres_new_avgsurf_groupdata.vtk'
pro_file = '/nobackup/ilz3/myelinconnect/new_groupavg/profiles/smooth_1.5/%s_lowres_new_avgsurf_groupdata.npy'
pro_mean_file = '/nobackup/ilz3/myelinconnect/n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 23 13:08:59 2020
@author: nenad
"""
def mergeLists(l1, l2):
# one list is empty
if l1 is None:
return l2
if l2 is None:
return l1
n1 = l1
n2 = l2
newHead = None
... |
'''
Problem statement:
https://www.hackerrank.com/challenges/itertools-permutations
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import permutations
import sys
sys.stdin.readline
line = sys.stdin.readline().strip().split()
w = line[0]
p = int(line[1])
a = lis... |
from django.contrib.auth.models import User
from denuncias.models import Denuncia
from tipo_denuncia.models import TipoDenuncia
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
class DenunciaTests(APITestCase):
def setUp(self):
user = User.objects.create(username='te... |
import sys
from math import gcd
from random import getrandbits
from random import randbytes
from random import randint
from unittest import TestCase
from Crypto.Cipher import AES
from Crypto.Cipher import ARC4
from Crypto.Util import Counter
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
fro... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
# Create a Profile table that links to User Table.
user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True)
bio = models.TextField()
location = models.CharField(... |
import logging
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import MethodDataSerializer
class ProcessorView(APIView):
content_type = 'application/json'
def post(self, request, format=None):
serializer = MethodDataSerializer(data=request.data... |
from PyQt5 import QtWidgets, QtCore
import pyqtgraph as pg
import sys
from pylsl import StreamInlet, resolve_stream
import argparse
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
self.channel_list = [
"AFF1h",
"AFF5h",
"F7",
... |
#CLASE
class tamano_ramo:
#ATRIBUTOS
tamanos = ["s", "l"]
#METODOS:
def __init__ (self, tamano):
self.tamano = tamano
print("se ha añadido un tamano de ramo")
# AREA DE PRUEBAS UNITARIAS
if __name__ == "__main__":
tamano_ramo("L")
tamano_ramo("s") |
from source.T5_LinearStructure.P3_List.L1_Node import Node
class CircularLinkedList:
def __init__(self):
""" Конструктор - створює новий порожній список.
"""
self.mPrev = None # Вузол, що передує поточному елементу списку
self.mCurr = None # Поточний вузол списку
def empty(... |
#Python04_12_StrEx01_신동혁
s01='NiceDay'
print(s01)
s02='''
NiceDay
NiceDay
NiceDay
'''
print(s02) |
# echo server 서비스 계속 유지
import socket
import sys
HOST = ''
PORT = 8888
serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
serversock.bind((HOST, PORT))
print('에코 서버 서비스 시작')
serversock.listen(5)
while 1:
conn, addr = serversock.accept()
print(... |
#! /usr/bin/env python3
# Q. 整数a1,a2,...anが与えられ、その中からいくつか選び、和をkにすることができるか
# => a1から順に和の計算要素に加えるか決める深さ優先検索の問題
n = 4
a = [1, 2, 4, 7]
k = 15
def dfs(i: int, s: int):
# 最深にたどり着いたら、和がkに等しいか判定
if i == n:
return s == k
# a[i]は使わない場合
if dfs(i + 1, s):
return True
# a[i]を使う場合
if dfs(... |
#!/usr/bin/env python
import unittest, random
from common import *
from pprint import *
from itertools import product
ibd.Mr_Plus_Infinity.restype = c_long
ibd.Mr_Minus_Infinity.restype = c_long
mr_plus_infinity = ibd.Mr_Plus_Infinity()
mr_minus_infinity = ibd.Mr_Minus_Infinity()
ibd.Hti_New.restype = ctypes.c_void_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Cloudera, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LIC... |
import math
from functools import reduce
import operator
class Solution:
'''Runtime: 28 ms, faster than 60.30% of Python3 online submissions for Subtract the Product and Sum of Digits of an Integer.
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Subtract the Product and Sum of Digit... |
#!/usr/bin/python
import os
import sys
from pyquery import PyQuery
data_dir = sys.argv[1]
if data_dir == '--help':
print 'Useage: python parse_html.py <data_dir>'
exit(0)
for data_file in os.listdir(data_dir):
with open (data_dir + '/' + data_file, 'r') as myfile:
html=myfile.read().replace(... |
import math
class Solution:
def mySqrt(self, x: int) -> int:
left, right = 0, x
while left <= right:
mid = math.floor(left + (right - left) / 2)
sqt = mid * mid
if sqt > x:
right = mid - 1
elif sqt < x:
left = mid + 1
... |
from django import forms
from .models import Categoria
class CategoriaForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for form in self.visible_fields():
form.field.widget.attrs['style'] = 'font-size: 14px'
form.field.widget.att... |
import numpy as np
import os
import torch
import time
import logging
import torch.nn as nn
from torch import optim
from lib.data_process.loader import MyDataset
from torch.utils.data import DataLoader
from lib.model.factory import model_factory
from lib.loss import FocalLoss, BceLoss, ResidualLoss
from lib.config imp... |
# from pypi
import numpy
import matplotlib.pyplot as pyplot
import seaborn
from sklearn.metrics import log_loss
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import make_hastie_10_2
from sklearn.model_selection import train_test_split
fro... |
from PIL import Image
import numpy as np
def imageResize(infile, outfile, size):
"""
:param infile: input img
:param outfile: output img
:param size: max size for the img
:return: return the resized im
"""
try:
im = Image.open(infile)
im.thumbnail(size,Image.ANTIALIAS)
... |
from flask import request
from apps.flow.business.deploy import DeployBusiness, DeployRecordBusiness, DeployLogBusiness
from apps.flow.extentions import validation, parse_json_form, parse_list_args2
from library.api.render import json_detail_render, json_list_render2
from library.api.tBlueprint import tblueprint
bpna... |
import tensorflow.keras
import numpy as np
from keras_preprocessing.sequence import pad_sequences
from tensorflow.keras.layers import Dense, Dropout, Conv1D, Activation, Flatten
from tensorflow.keras.models import Sequential
from src.sound.SoundTransformer import SoundTransformer
from src.classifiers.KerasClassifier i... |
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Cliente, Proyecto
class ClienteSerializer(serializers.ModelSerializer):
class Meta:
model = Cliente
fields = ('idCliente', 'nombre', 'rubro', 'direccion', 'contacto')
class ProyectoSerializer(s... |
import pstats
import cProfile
import numpy as np
import data.ncExtract as NCE
from data.timeArray import *
import unittest
# path='/home/tuomas/workspace/cmop/projects/turb_tests/cre_open_channel/real_bath/fluxTest/combined'
path = '/home/workspace/ccalmr53/karnat/projects/turb_tests/fluxtest/fluxTest/combined/'
# a... |
# Generated by Django 2.2.2 on 2019-07-01 19:52
from django.db import migrations
import django.db.models.deletion
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
('home', '0017_feedbackform_2_field_feedbackform_2_page_feedbackform_3_field_feedbackform_3_page'),
]
... |
'''Train CIFAR10 with PyTorch.'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import numpy as np
import os, random
import argparse
import time
from PIL import Image
# i... |
N = 2000
def check(N, x, y):
return 0 <= x < N and 0 <= y < N
s = [0] * (N * N + 1)
for k in range(1, 56):
s[k] = (100003 - 200003 * k + 300007 * k * k * k) % 1000000 - 500000
for k in range(56, 4000001):
s[k] = (s[k - 24] + s[k - 55] + 1000000) % 1000000 - 500000
for n in (10, 100):
print(n, s[n])
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.