text stringlengths 8 6.05M |
|---|
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# 本题是算法课上的习题,与Leetcode无关。
# 给定一个以字符串形式表示的入栈序列,请求出一共有多少种可能的出栈顺序?如何输出所有可能的出栈序列?
# 比如入栈序列为:1 2 3 ,则出栈序列一共有五种,分别如下:1 2 3、1 3 2、2 1 3、2 3 1、3 2 1
from time import time
# Catalan!!!!!
# https://github.com/vo01github/Math/tree/master/%E7%BB%84%E5%90%88%E6%95%B0%E5%AD%A6/%E5%8D%... |
import torch.nn as nn
class EncoderDecoderTF(nn.Module):
""" Original Transformer architecture that uses both the encoder and decoder side"""
def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):
super().__init__()
self.encoder = encoder
self.decoder = decoder
s... |
import sys, os, time, datetime
import wx
from tc_lib import sub, send
from pprint import pprint
import wx.lib.mixins.listctrl as listmix
e=sys.exit
class MessageList(wx.ListCtrl,): #listmix.ListCtrlAutoWidthMixin,
def __init__(self, win, parent, ID=wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, st... |
"""class MyException(Exception): # Некоректное входное значение
def __init__(self, text):
super().__init__(text)
try:
print("My")
except MyException as arr:
print(err)"""
def my_iter(obj):
for i in obj:
yield i
l1 = [1,2,3,4,5,6,7,]
iterator_object = my_iter(l1)
print(next(iterato... |
from datetime import datetime
from requests.exceptions import ConnectionError
from django.test import TestCase
from fetcher.tools import SatcatParser
class SatcatParserTestCase(TestCase):
"""
Test the behavior of the SatcatParser tool
"""
def test_canImportSatcatparser(self):
"""
... |
import sys
import tensorflow as tf
import tensorflow.keras as kr
import Configuration as cfg
import DataOperator as do
import RNNLMNetwork as rn
def generate_sentence(char_to_index, index_to_char, char_count, model, input_char, generate_num):
sentence = input_char.lower()
for _ in range(gene... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 7 21:43:45 2020
@author: garethlomax
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img = mpimg.imread('bgnd2.jpg')
#route should be this form
route = np.array([[11,1], [10,5], [6, 6]])
two_starts = Tru... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = raw_input("请输入: ");
print "你输入的内容是: ",str
str2 = input("请输入: ");
print "你输入的内容是: ",str2;
|
import sys, string, math
p,r = map(int,input().split())
k = 0
for l in range(p,r+1) :
for j in range(2,l) :
if l%j == 0 :
break
else :
k += 1
print(k)
|
#-*-coding: utf-8-*-
from django.shortcuts import render, render_to_response
# Create your views here.
def index(req):
return render_to_response("webapp/index.html") |
from .web import *
from .flask import *
|
from coreMechanics import Dungeon
from time import sleep
import pickle
method = "whole"
test = Dungeon(120, 120, method=method)
print test
f = open("saves/pregeneratedDungeon.dun", 'w')
pickle.dump(test, f)
f.close() |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 20:11:06 2020
@author: user
"""
import numpy as np
import argparse
import AnoGANmodel
parser = argparse.ArgumentParser()
data = np.load('traindata2.npz')
parser.add_argument('--mode', type=str, default='train', help='train, test')
args = parser.parse_args(... |
import turtle
turtle1 = turtle.Pen()
turtle1.forward(100)
turtle1.left(90)
turtle1.forward(100)
turtle1.left(90)
turtle1.forward(100)
turtle.left(90)
turtle1.forward(100)
|
import numpy as np
import matplotlib.pyplot as plt
from sklearn.feature_selection import mutual_info_regression, mutual_info_classif
from mine_estimator import mine, DistributionSimulator
def gen_x(data_size):
return np.random.normal(1.,1.,[data_size[0],data_size[1]])
def gen_y(x, data_size):
y = 2*x[:, 0] +... |
grade1 = float(input("Digite a 1a nota: "))
grade2 = float(input("Digite a 2a nota: "))
grade3 = float(input("Digite a 3a nota: "))
grade4 = float(input("Digite a 4a nota: "))
average = (grade1+grade2+grade3+grade4)/4
print(f"A média das notas é: {average}")
|
from SignalGenerationPackage.SignalMainWindow import SignalMainWindow
from SignalGenerationPackage.DynamicPointsDensitySignal.Ui_DynamicPointsDensitySignalWindow import Ui_DynamicPointsDensitySignalWindow
from SignalGenerationPackage.DynamicPointsDensitySignal.DynamicPointsDensityUIParameters import DynamicPointsDensit... |
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
thisli... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
get_ipython().run_line_magic('matplotlib', 'inline')
# In[4]:
df=pd.read_csv("https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.c... |
import xlrd
class excel_utils():
def get_data(self,file_name, sheet_index):
# create an empty list to store rows
values = []
# open the specified Excel spreadsheet as workbook
book = xlrd.open_workbook(file_name)
# get the first sheet
sheet = book.sheet_by_index(sh... |
from .BooleanType import BooleanType
from .SequenceType import SequenceType
from .UTF8String import UTF8String
from .IntegerType import IntegerType
from .EnumeratedType import EnumeratedType
from .ChoiceType import ChoiceType
from .SequenceOfType import SequenceOfType
from .BitStringType import BitStringType
from .Octe... |
import cPickle as pickle
import vivisect
def saveWorkspaceChanges(vw, filename):
elist = vw.exportWorkspaceChanges()
if len(elist):
f = file(filename, 'ab')
pickle.dump(elist, f, protocol=2)
f.close()
def saveWorkspace(vw, filename):
f = file(filename, "wb")
vwevents = vw.expo... |
import pytest
import requests
from requests.exceptions import RequestException
from tests.test_vars import *
def service_available():
try:
requests.get(BASE_URL)
return True
except RequestException:
return False
@pytest.mark.skipif(service_available() is False, reason='Service unav... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum
from typing import Any, ClassVar
from pants.build_graph.address import Address
# -----------... |
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
m = {}
index1 = 0
index2 = 0
for i in xrange(0,len(num)):
if num[i] in m:
index1 = i + 1
index2 = m[num[i]] + 1
m[target - num[i]] = i
if index1 > inde... |
import torch
import torch.nn as nn
from torchsummary import summary
import math
class BasicBlock(nn.Module):
def __init__(self, n_features, bias):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(n_features, momentum=0.001) # when trying EMA with many epochs, try using BN with moment... |
import android
import webbrowser
droid = android.Android()
code = droid.scanBarcode()
url = code[1]['extras']['SCAN_RESULT']
droid.makeToast("The url scanned is " + url)
droid.notify('Scan result',url)
droid.dialogCreateAlert('Scan Result', url)
droid.dialogSetPositiveButtonText('Open in browser')
droid.dialogSetNegat... |
from typing import Tuple
import numpy as np
from qtpy.QtCore import QModelIndex, Qt
from napari._qt.containers import QtLayerList
from napari.components import LayerList
from napari.layers import Image
def test_set_layer_invisible_makes_item_unchecked(qtbot):
view, image = make_qt_layer_list_with_layer(qtbot)
... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import re
from enum import Enum
from typing import Match, Optional, Tuple, cast
from pants.backend.python.target_types import PexCompletePlatformsField, PythonResolveField
from pants.back... |
raw_activation_key = input()
while True:
tokens = input()
if tokens == "Generate":
print(f"Your activation key is: {raw_activation_key}")
break
tokens = tokens.split(">>>")
command = tokens[0]
if command == "Contains":
substring = tokens[1]
if substring in raw_activ... |
# -*- coding: utf-8 -*-
# Converts a T-cell density map (as produced by Ilastik) to a detection map and, optionally, to a list of
# coordinates for the centers of the detections.
__author__ = "Vlad Popovici <popovici@bioxlab.org>"
__version__ = 0.1
import skimage.io as skio
import skimage.morphology as skm
import ... |
from __future__ import print_function
import tensorflow as tf
import numpy as np
# Save to file
# remember to define the same dtype and shape when restore
def net_save():
W = tf.Variable([[1, 2, 3], [3, 4, 5]], dtype=tf.float32, name='weights')
b = tf.Variable([[1, 2, 3]], dtype=tf.float32, name='biases')
... |
# coding: utf-8
# Standard Python libraries
from io import IOBase
from pathlib import Path
from typing import Optional, Union
import numpy as np
# https://github.com/usnistgov/atomman
import atomman as am
import atomman.unitconvert as uc
# https://github.com/usnistgov/DataModelDict
from DataModelDict import DataMod... |
# https://youtu.be/9JUAPgtkKpI?t=1065
import numpy as np
import os
os.system('cls')
print('LEARNING NUM_PY\n')
a = np.array([[1, 2], [4, 5], [7, 8]])
print(' a = np.array([[1, 2], [4, 5], [7, 8]])\n')
print('version =>', np.__version__)
print(f'a => \n{a}')
print(f"shape => {a.shape}")
print(f'dtype => {a.dty... |
#Defining a class
# Class names are uppercase
#Allows us to create our own data types
#Every class has to have the "__init__" method. Its alled the constructor. It must accept at least one thing, it has to be 'self'
class Person:
def __init__(self): #always self
print ("class instantiated")
def do_some... |
#Разработать программное средство с использованием ООП для
#представления успеваемости студентов по дисциплине:
#1)
#Промежуточная аттестация максимум 20 баллов, разбитые
#по количеству работ (практики, контрольная и тестирование в 1
#половине семестра);
#2)
#Работа в семестре 20 баллов (практики, контрольная и... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" Contain KafkaTransactionContext & KafkaTransactionalManager
Module for make Kafka Transaction
"""
from typing import Callable, Dict
from tonga.services.coordinator.transaction.base import (BaseTransaction,
... |
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import urllib.request
URL = 'https://www.koreabaseball.com/Record/Player/HitterBasic/Basic1.aspx'
driver = webdriver.Chrome('H:\chromedriver.exe')
driver.get(url=URL)
driver.implicitly_wait(3)
y... |
import xml.etree.ElementTree as ET
import os
import glob
def cover(xmlpath, thresh = 20):
error = []
error_type = []
for path, d, filelist in os.walk(xmlpath):
for xmlname in filelist:
if xmlname.endswith('xml'):
oldname = os.path.join(path, xmlname)
pri... |
def pascal(number) :
if number == 0 :return [1]
else :
line = [1]
previousLine = pascal(number - 1)
for i in range(len(previousLine) - 1):
line.append(previousLine[i] + previousLine[i+1])
line += [1]
return line
number = 3
print(pascal(number)) |
from tkinter import *
from hf10sound_panel2 import *
import pygame.mixer
app=Tk()
app.title("head first mix")
mixer=pygame.mixer
mixer.init()#创建一个mixer对象,并且初始化pygame的声音系统
panel=SoundPanel(app,mixer,"wrong.wav")
panel.pack()
panel=SoundPanel(app,mixer,"correct.wav")
panel.pack()
def shutdown():
... |
# Day 17: Conway Cubes
# <ryc> 2021
class ConwayCube:
def __set_active(self, coord):
x, y, z = coord
if z not in self.__active_cubes:
self.__active_cubes[z] = dict()
if y not in self.__active_cubes[z]:
self.__active_cubes[z][y] = set()
if x not in self.__act... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-06-10 12:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('k8sproject', '0007_auto_20180610_2017'),
]
operations = [
migrations.AlterF... |
class Dog():
def __init__(self,name,age):
self.name=name
self.age=age
def sit(self):
print(self.name.title()+" is a now sitting.")
def roll_over(self):
print(self.name.title()+" rolling over!")
my_dog=Dog("willie",6)
print("My dog's name is "+my_dog.name.title()+".")... |
# -*- coding:utf8 -*-
#1 request 的使用
#
# import requests
#
# response = requests.get('https://www.appannie.com/apps/ios/app/idle-heroes/reviews/?order_by=date&order_type=desc&date=2019-04-29~2019-05-29&translate_selected=false&granularity=weekly&stack&percent=false&series=rating_star_1,rating_star_2,rating_star_3,rati... |
import os
import psycopg2
DATABASE_URL = os.popen('heroku config:get DATABASE_URL -a app_name').read()[:-1]
# connect to database
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cursor = conn.cursor()
# create a table
create_table_query = '''
CREATE TABLE test_table(
id serial PRIMARY KEY,
... |
# -*- coding: utf-8 -*-
#
import numpy
import sys
if sys.platform == 'darwin':
# likely there.
gmsh_executable = '/Applications/Gmsh.app/Contents/MacOS/gmsh'
else:
gmsh_executable = 'gmsh'
def rotation_matrix(u, theta):
'''Return matrix that implements the rotation around the vector :math:`u`
b... |
from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, TextAreaField
from wtforms.validators import InputRequired
from flask_wtf.file import FileField, FileRequired, FileAllowed
from werkzeug.utils import secure_filename
class Propertyform(FlaskForm):
title = StringField('Property Title', va... |
s = list(raw_input())
k = int(raw_input())
newList = []
n = len(s)
for i in range(k):
if i<=n-1:
newList.append(s[i])
print newList[::-1]+s[k:]
|
from django.db.models import Sum, F
from django.db import transaction
from rest_framework import serializers
import jdatetime
from car.models import CarStock, CarSold
from utils.exceptions import CustomException
class CarListSerializer(serializers.Serializer):
name = serializers.ReadOnlyField()
total = seria... |
seq1 = "0actcg"
seq2 = "acagtag"
gap = -1
mismatch = 0
match = 1
def BuildTable():
global gap
global seq1
global seq2
table = []
for i in range(len(seq1)):
column = []
for j in range(len(seq2)+1):
if j == 0:
column.append(i * gap)
elif i == 0:... |
#!/usr/bin/env python
# wujian@2018
import os
import pprint
import argparse
import random
from libs.trainer import PermutationTrainer
from libs.utils import dump_json, get_logger
from libs.dataset import make_pitloader
from nnet import Nnet
from conf import trainer_conf, nnet_conf, feats_conf, train_data, dev_data
... |
# import numpy as np
# grid = np.chararray((rows, cols))
# order is important since these are parallel arrays
turn_cycle = [-1, 0, 1]
cart_chars = ['<','^','>','v']
track_chars = ['-','|','-','|']
backward_curve = ['^', '<', 'v', '>']
forward_curve = ['v','>','^','<']
dirs = [(0,-1),(-1,0),(0,1),(1,0)]
def simulate_c... |
import os, pandas as pd, numpy as np
from sklearn.cluster import KMeans
from matplotlib import pyplot as plt
from scipy.spatial.distance import cdist
from scipy.cluster.hierarchy import fcluster
from sklearn.ensemble import AdaBoostClassifier
from sklearn.model_selection import train_test_split
from sklearn import met... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 16/4/24 下午2:28
# @Author : ZHZ
# @Description : 将predict行记录增加至1000条
import pandas as pd
num_days = 7
final_date = 444/num_days
if_all_predict = open("/Users/zhuohaizhen/PycharmProjects/Tianchi_Python/Data/if_all_predict.csv",'r')
if_all_predict_1000 = open(... |
# 패키지 사용자가 echo.py 모듈을 쓸 때 import로
# from pygame.sound import *
# 를 하기 위해서는 원래
# __all__ = ['echo', 'effect' ...]
# 를 해줘야하는데
# from . import echo
# 가 있으면 없어도 작동함
__all__ = ['effect', 'echo'] # import * 했을 때
from . import echo
|
#!/usr/bin/env python
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
#!/usr/bin/env python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# Date: 2017.12.19
# Author: Tony Paulino
# Description:
# Modified by: Tony Paulino
# Version: 0.1
import os
import sys
import time
import glob
import re
TEMPLATE_HTML = """<HTML>
<HEAD>
<META HTTP-EQUIV... |
from gtts import gTTS
import os
mytext ='This is a to remind you about your health problems'
language = 'en'
myobj = gTTS(text=mytext, lang=language, slow=False)
myobj.save("med.mp3")
os.system("mpg321 new.mp3")
|
from collections import defaultdict
def solution1(players, stop):
marbles = [0]
current = 0
steps = 0
score = defaultdict(int)
while steps <= stop:
for player in range(1, players + 1):
steps += 1
if steps % 23 == 0:
r = (current - 7) % len(marbles)
... |
# Helper routines for residual vectors output by the DREAM solver.
import h5py
import matplotlib.pyplot as plt
import numpy as np
import warnings
from .petscmat import _mplcursors_frmt1d
#################
# Check for mplcursors
HASMPLCURSORS = False
try:
import mplcursors
HASMPLCURSORS = True
except:
wa... |
from django.contrib import messages
from django.shortcuts import render, redirect, get_object_or_404
from .forms import WargaRegistrationForm
from account.forms import RegisterForm, LoginForm, EditAccountForm
from account.decorators import anonymous_required, warga_required
from django.db import transaction
from django... |
import pika
import time
from DAO.connection import Connection
import os
import multiprocessing
import json
import logging
import ast
from extract_prosodic.main import extract
import threading
import functools
from files_ms_client import download, upload
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcN... |
#!/usr/bin/python
# add.py
# by: Mike Pozulp
# adds npb benchmark job run(s) to the pgsql db
# Usage: add.py pbsJobOutput benchMarkOutput
import os
import sys
import io
import string
import psycopg2
MIN_FILE_SIZE = 1000 # used to easily skip output of
# incomplete benchmark runs
def printUsage():
... |
from socket import *
import zlib
class Client():
def __init__(self, server='localhost', port=12201, maxChunkSize=8154):
self.graylog2_server = server
self.graylog2_port = port
self.maxChunkSize = maxChunkSize
def log(self, message):
UDPSock = socket(AF_INET,SOCK_DGRAM)
zmessage = zlib.compress(message)
... |
import numpy as np
from keras.callbacks import Callback
from keras.optimizers import SGD, Adam
from keras.models import Sequential
from keras.layers import Dense
from scipy.stats import logistic
from .BaseModel import BaseModel
from ..utils import YpredCallback
class NN_SoftmaxSoftmax(BaseModel):
"""2 Layer logis... |
# -*- coding: utf-8 -*-
"""Created by: Sacaia"""
import discord
from discord.ext import tasks, commands
import discord.ext
import asyncio
import dados
import gerenciadorDeDados
import random
import os
import re
import math
##############ACTIVITY##############
activity = discord.Activity()
activity.name = ".help | Es... |
import io
from django.core import management
# from fabric.api import run
# from fabric.context_managers import settings
def create_session_on_server(username): # revisit
out = io.StringIO()
management.call_command("create_session", f"--username={username}", stdout=out)
return out.getvalue()
def reset... |
__author__ = 'wuxj06'
import user_management_pb2
import user_management_pb2_grpc
import register_login_pb2
import register_login_pb2_grpc
import comp_management_pb2
import comp_management_pb2_grpc
import company_cert_pb2
import company_cert_pb2_grpc
import grpc
import random
import hmac
import time
import unittest
impo... |
# # -*- coding:utf-8 -*-
#
# from django.test import TestCase
# from guest_app.models import Guest,Event
# from datetime import datetime
# from django.contrib.auth.models import User
# # Create your tests here.
# class TestModels(TestCase):
#
# def setUp(self):
# Event.objects.create(name="测试发布会", status=Tr... |
from datetime import datetime
from orm import DateTime
from pydantic import BaseModel
from ..models.questions import QuestionChoices
class QuestionBase(BaseModel):
created_at: datetime = None
# created_at: DateTime = datetime.now()
class QuestionCreate(QuestionBase):
question: QuestionChoices
class ... |
# -*- encoding: utf-8 -*-
"""
http://bytefish.de/blog/first_steps_with_sqlalchemy/
An image consist of a UUID and its associated number of likes. Each image can
be associated with many tags, a tag can be associated with many images. That's
a many-to-many relationship, so we need a mapping table. Finally each image
ca... |
import time
import dash_bootstrap_components as dbc
from dash import Input, Output, html
loading_spinner = html.Div(
[
dbc.Button("Load", id="loading-button", n_clicks=0),
dbc.Spinner(html.Div(id="loading-output")),
]
)
@app.callback(
Output("loading-output", "children"), [Input("loading... |
a = []
for _ in range(9):
a.append(int(input()))
m = max(a)
n = a.index(m)+1
print(m)
print(n)
|
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
... |
# -*- coding: utf-8 -*-
"""The app module, containing the app factory function."""
from flask import Flask
from webcv import public
from webcv.extensions import db, migrate, heroku # cache,
from webcv.settings import Config
def create_app(config_object=Config):
"""Application factory.
:param config_object:... |
# -*- coding: utf-8 -*-
# MLC (Machine Learning Control): A genetic algorithm library to solve chaotic problems
# Copyright (C) 2015-2017, Thomas Duriez (thomas.duriez@gmail.com)
# Copyright (C) 2015, Adrian Durán (adrianmdu@gmail.com)
# Copyright (C) 2015-2017, Ezequiel Torres Feyuk (ezequiel.torresfeyuk@gmail.com)
# ... |
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui, uic
import PixivUtil
import threading
import cache
import PixivNotifier
from bs4 import BeautifulSoup
import requests
DlgUI, QtBaseClass = uic.loadUiType("IllustDialog.ui")
bookmarkUrl = 'https://www.pixiv.net/bookmark_add.php?type=illust&illust_i... |
#!/usr/bin/env python
import os
import re
import collections
import argparse
"""
File name : file_searching.py
script that implements the following scenario:
You have a big directory tree with many files and directories in it.
Some of those files have the extension '.inform'.
Some of the files with... |
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from mptt.admin import DraggableMPTTAdmin
from .models import Shop, Link, Address, Phone, Page, Menu, MenuItem
class MenuItemsInline(GenericTabularInline):
model = MenuItem
extra = 1
class LinkInline(admin.T... |
from os import path
from setuptools import setup, find_packages
with open('requirements.txt') as reqs_file:
requirements = reqs_file.read().splitlines()
with open('test-requirements.txt') as reqs_file:
test_requirements = reqs_file.read().splitlines()
# Get the long description from the relevant file
long_de... |
from logging import error, info
import requests
from furl import furl
from retry import retry
from utilities import constants
class Http:
def __init__(self, session_builder):
self.session = session_builder()
@retry(requests.exceptions.ConnectionError or requests.exceptions.Timeout, delay=constants... |
import numpy as np
from numpy import fft
import matplotlib.pyplot as plt
from scipy.signal import argrelextrema
import librosa
from librosa import display
filename = 'Samples/Anga.wav' ## Test Signal
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
#!/usr/bin/python3
import sys
import json
import subprocess
from urllib.request import urlopen
num_tags = 20
url ='https://hub.docker.com/v2/repositories/factominc/factomd/tags/?page_size=%s' % num_tags
docker_path = '/usr/bin/docker'
def prompt(tag_list):
print("Please choose an image to install:")
for i, ta... |
from distutils.core import setup
setup(name='pysem',
version='1.0',
description='Simplesem interpreter',
author='Davide Angelocola',
author_email='davide.angelocola@gmail.com',
url='http://bitbucket.org/dfa/pysem',
package_dir = { '': 'src' },
packages=['pysem'],
)
|
"""
Module to handle specifically comminication actions with RabbitMQ
"""
# System Imports
import json
import os
# Framework / Library Imports
import pika
# Application Imports
# Local Imports
import config
from exceptions import ConnectionError
def get_connection():
"""
Returns a connection object for Rab... |
import names
from gtts import gTTS
import tempfile
import os
def spellApco(word):
alphabet = {
'A': "Adam",
'B': "Boy",
'C': "Charles",
'D': "David",
'E': "Edward",
'F': "Frank",
'G': "George",
'H': "Henry",
'I': "Ida",
... |
# -*- coding: utf-8 -*-
import logging
from django_cron import CronJobBase, Schedule
from .base import FetcherJob
logger = logging.getLogger(__name__)
class HearthstoneJob(CronJobBase, FetcherJob):
RUN_EVERY_MINS = 59
RETRY_AFTER_FAILURE_MINS = 9
schedule = Schedule(run_every_mins=RUN_EVERY_MINS,
... |
from django.shortcuts import redirect
from django.contrib import messages
# decorator used to ensure user in in session
def required_login(views_func):
def _wrapped_views_func(request, *args, **kwargs):
if 'user_id' not in request.session:
messages.error(request, "Please register an account or... |
# coding:utf-8
import urllib.request, json
from bs4 import BeautifulSoup
import pandas as pd
url = 'http://zhaopin.baidu.com/api/quanzhiasync?query=%E4%BA%A7%E5%93%81%E7%BB%8F%E7%90%86+%E6%8B%9B%E8%81%98&sort_type=1&city_sug=%E4%B8%8A%E6%B5%B7&detailmode=close&rn=20&pn=0'
m1 = []
m2 = []
content = {}
req = urllib.re... |
# Author:ambiguoustexture
# Date: 2020-02-13
from collections import Counter
from morphological_analysis import morphology_map
file_parsed = "./neko.txt.mecab"
words = morphology_map(file_parsed)
words_without_punctuation = []
for word in words:
if word['pos'] != '記号':
words_without_punctuation.append(wor... |
import unittest
from katas.kyu_7.the_office_1_outed import outed
class OutedTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(outed({
'tim': 0, 'jim': 2, 'randy': 0, 'sandy': 7, 'andy': 0, 'katie': 5,
'laura': 1, 'saajid': 2, 'alex': 3, 'john': 2, 'mr': 0}, 'la... |
import sale
import product
import mrp |
from django.utils.translation import gettext_lazy as _
from django.db.models import (
CASCADE,
Model,
DateTimeField,
CharField,
ForeignKey
)
from users.models import User
class Tag(Model):
modified_at = DateTimeField(
_('Modified at'),
auto_now=True
)
name = CharField(... |
#!/bin/env python3
import logging
from sys import platform, getfilesystemencoding
from os import uname
from collections import namedtuple
from jproperties import Properties
from splunk_hec_handler import SplunkHecHandler
# setup logger utility for this script
logging.basicConfig(filename='transmute.log', filemode='w',... |
#!/usr/bin/python3
#
# Project: pyresteasy
# File: pyresteasy.py
#
# Copyright 2015 Matthew Mitchell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without l... |
maior = int(input())
for i in range(1,100):
n = int(input())
if maior < n:
maior = n
print(maior)
|
import numpy as np
def initTemp(STATUS, T, x):
# return values for initial temperature field
if not isinstance(x, np.ndarray):
raise Exception("x must be numpy.ndarray")
if not isinstance(T, np.ndarray):
raise Exception("T must be numpy.ndarray")
if len(T) != len(x):
raise E... |
import tornado
import json
class BaseHandler(tornado.web.RequestHandler):
def set_default_headers(self):
self.set_header("Content-type", "application/json")
def get(self):
pass
def post(self):
pass
def put(self):
pass
def delete(self):
pass
... |
#!/usr/bin/env python3
''' Author : Student '''
MYNOTE = "print this string"
print(MYNOTE)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.