text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
import scipy as sp
from sys import argv
from config import *
if len(argv) != 2:
print 'Usage: ' + argv[0] + ' [run file]'
exit(-1)
fd = open(argv[1], 'r')
# TODO: cleaner header handling
N = int(fd.readline()[4:-1])
beta = float(fd.readline()[7:-1])
print 'N = {:d}'.format(N)
print 'bet... |
from socket import *
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QListView, QMessageBox
from PyQt5.QtCore import QStringListModel
from ftp_login import Ui_login
from ftp_main import Ui_main
from PyQt5.QtWidgets import QFileDialog, QInputDialog
import sys
... |
#!/usr/bin/env python
# creator.py
# TODO: initialize default values from tcu_params object
# TODO: change range of frequency spin box depending on mode setting
# TODO: add content to the info section, perhaps have help files with html
# TODO: delete/ignore empty rows of table when export()
# TODO: check rounding of ... |
def hasTwoThreeDigitFactors(number):
for i in range(999,100, -1):
divisor = number / i
if number % i == 0 and len(str(divisor)) == 3:
return True
return False
def isPalindrome(number):
numString = str(number)
length = len(numString)
j = length-1
for i ... |
from Tkinter import *
class Graph:
def __init__(self):
self.nodes = {} # Nodes are stored as a dict with their ids as keys
self.endPoints = []
self.startPoints = []
self.discovered = []
self.paths = []
# Check if there's a two-way edge between two nodes
def twoWay(self, x, y):
return ((y in self.node... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Actor',
fields=[
('id', models.AutoField(verbos... |
"""
Percolate Coding Challenge!
Normalize entries from data/sample-Liz.in to JSON on data/result.out
$ cd perc_test/app
$ python formatter.py
"""
import time
import json
from functools import wraps
def timefn(fn):
"""
profiling/logging helper measuring execution speed
:param self: function
:return: st... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 13:44:04 2019
This is Code built for one purpose: well a couple purposes
1) to load the landslide DEM
2) load the non landslide DEm
3) call fft mean spec so I can begin debugging that code.
@author: matthew
"""
import time
import os
import numpy... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from typing import Iterable, Type
import pytest
from pants.backend.debian.target_types import DebianSources
from pants.build_graph.address import Address
from pants.engine.rules import Qu... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import atexit
import errno
import os
import shutil
import stat
import tempfile
import threading
import uuid
from collections import defaultdict
from con... |
l = [1, 2, 3]
l.reverse()
print(l) |
"""
4. Valid Palindrome
Question:
Given a string, determine if it is a palindrome, considering only alphanumeric characters
and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Example Questions Candidate Might Ask:
Q: What about an empty string? Is it a ... |
import psycopg2
import os
import csv
import io
from pymongo import MongoClient
def check():
print("\n\n\n\n\n\n...............................MONGO DB CONNECTIVITY ESTABLISHED!............................... ")
def initMongo():
con = MongoClient()
db = con.finalproject1
movies = db.movies
movies.... |
access_dict = {'FastEthernet0/12':10,
'FastEthernet0/14':11,
'FastEthernet0/16':17,
'FastEthernet0/17':150}
def generate_access_config(access, psecurity=False):
access_config = {}
access_template = ['switchport mode access',
'switchport access vlan',
'switchport nonegotiate',
... |
"""Precompute various Colorgorical model data for improved performance."""
import os
import numpy as np
import model
def precomputeStartingColors():
"""Precomputes the starting color sub-space.
Creates a list of all colors in a subspace of the default 8,325 CIE Lab
colors (http://dx.doi.org/10.1145/22076... |
from django.test import TestCase
from elections.utils import ElectionBuilder, get_notice_directory
from .base_tests import BaseElectionCreatorMixIn
class TestCreateIds(BaseElectionCreatorMixIn, TestCase):
def setUp(self):
super().setUp()
self.election = ElectionBuilder(
"local", "201... |
import numpy as np
from eelbrain import *
# dimension objects
from eelbrain._data_obj import UTS, Sensor
"""
Create simulated data with shape
(2 conditions * 15 subjects, 5 sensors, len(T) time points)
"""
# create the time dimension
time = UTS(-.2, .01, 100)
# random data
x = np.random.normal(0, 1,... |
#!/home/franck260/ENV/bin/python
import application
application.app.configure("production.cfg")
application.app.run() |
#!/usr/bin/env python3
#generate_references.py
#*
#* --------------------------------------------------------------------------
#* Licensed under MIT (https://git.biohpc.swmed.edu/gudmap_rbk/rna-seq/-/blob/14a1c222e53f59391d96a2a2e1fd4995474c0d15/LICENSE)
#* -------------------------------------------------------------... |
N = int(input())
def distance(A,B):
ans = ord(B) - ord(A)
if ans < 0:
ans += 26
return ans
ans = []
for _ in range(N):
AB = input()
A, B = AB.split()[0], AB.split()[1]
t = []
for i in range(len(A)):
t.append(distance(A[i], B[i]))
ans.append(t)
for k in ans:
a = ... |
import numpy as np
import tensorflow as tf
from dsn.util.tf_langevin import (
langevin_dyn,
bounded_langevin_dyn,
bounded_langevin_dyn_np,
)
from tf_util.stat_util import approx_equal
EPS = 1e-16
CONV_EPS = 1e-2
def langevin_dyn_np(f, x0, eps, num_its):
dim = x0.shape[0]
x = x0
for i in range... |
import sys
import subprocess
import rlkit.launchers.config as config
cmd = F"aws s3 sync --exact-timestamp --exclude '*' --include '12-02*' {config.AWS_S3_PATH}/ ../../s3_files/"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
print(cmd)
for line in iter(process.stdout.readline, b''):
sys.stdo... |
import string, random
def get_random_str(size=8, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def gen_playlists(repeat=10, start_id=1):
playlists = []
for i in range(repeat):
playlists.append({"id_playlist": i + start_id, "nome_playlist": get_random_st... |
counter = -1
train = []
while True:
try:
x = int(input())
except:
break
if x == 0 and len(train) != 0:
print(train[counter])
train.remove(train[counter])
counter -= 1
else:
train.append(x)
counter += 1 |
from PyQt4.Qt import *
class SortableTableItem(QTableWidgetItem):
def __lt__(self, other):
if isinstance(other, QTableWidgetItem):
myValue, myOk = self.data(Qt.EditRole).toInt()
otherValue, otherOk = other.data(Qt.EditRole).toInt()
if myOk and otherOk:
... |
from rest_framework.serializers import Serializer
from .models import Employee,EmployeeSerializer
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
class EmployeeViewSet(ModelViewSet):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer |
# Copyright 2010-2012 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
__all__ = (
'UseManager',
)
from _emerge.Package import Package
from portage import os
from portage.dep import dep_getrepo, dep_getslot, ExtendedAtomDict, remove_slot, _get_useflag_re
from portage.eapi import e... |
from flask import Flask, render_template,abort
app = Flask(__name__)
@app.route('/',methods=["GET","POST"])
def inicio():
return render_template("inicio.html")
@app.route('/hola/')
@app.route('/hola/<nombre>')
def saluda(nombre=None):
return render_template("template1.html", nombre=nombre)
@app.route('/suma/... |
import os
from pathlib import Path
'''
This page is all about static data that won't be changed through the Tests.
All the time this data should be static as-is like here
written by: jiaul_islam
'''
# ALL GLOBAL VARIABLE
BASE_DIR = Path.cwd()
READER_FILENAME = 'Request_CR.xlsx'
WRITER_FILENAME = 'Output_CR.xlsx'
CA... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 1 20:58:36 2019
@author: Sneha
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 13:26:27 2019
@author: Sneha
"""
import tkinter as tk
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import matplotlib.pyplot... |
x = int(input("Enter any number"))
y = int(input("Enter any number"))
z=1
for m in range(y):
z=z*x
print(z)
|
import datetime
import flask_sqlalchemy
db = flask_sqlalchemy.SQLAlchemy()
class Player(db.Model):
__tablename__ = 'players'
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(128))
last_name = db.Column(db.String(128))
nationality_id = db.Column(db.Integer, db.ForeignK... |
# 30.itertools.permutations()
# > split()은 기본적으로 ' '가 들어있는 거고 공백을 모두 사라지게 만듬
# split() vs split(" ") 차이는 후자는 띄어쓰기도 리스트에 포함됨
# EX) "HI 2spcae" 를 split 하면 ['HI', '2space'] vs ['HI', ' ', '2space']임
# "HI" 만 split() 하면ㅁ ['HI'] 반한됨 Split('')는 오류남
# 31.Polar Coordinates
# > Complex() 로 복소수를 만들 수 있다.
# > cmath.phase() 위상각을... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 30 17:34:28 2019
@author: amie
"""
import picdata as pic
import numpy as np
from numba import jit
import time
import math
import matplotlib.pyplot as plt
#from pca import PCA_face_example
import pickle
import cv2
class picprocess():
def _... |
#coding=utf-8
import scrapy
from scrapy.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request
from jianshu.items import JianshuItem
import urllib
class Jianshu(CrawlSpider):
name='jianshu'
start_urls=['http://www.jianshu.com/trending/monthly']
page=1
url='http... |
import tensorflow as tf
x_data = [[1, 2],
[2, 3],
[3, 1],
[4, 3],
[5, 3],
[6, 2]]
y_data = [[0],
[0],
[0],
[1],
[1],
[1]]
X=tf.placeholder(tf.float32, shape=[None, 2])
Y=tf.placeholder(tf.float32, shape=[None, 1])
W=t... |
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.Qt import Qt
class MainWindow(QWidget):
def __init__(self):
super().__init__()
def keyPressEvent(self, event):
#print(event.key()) #Print the value of the key
#print(event.text()) #Print the text of the key
... |
# Generated by Django 2.2.7 on 2019-12-19 08:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exhibition', '0004_auto_20191211_0145'),
]
operations = [
migrations.AlterField(
model_name='exhibition',
name='noto... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
# from watchlist_app.api.views import movie_list, movie_details
from watchlist_app.api.views import (ReviewList, ReviewDetail, ReviewCreate, WatchListAV,
WatchDetailAV, StreamPlatformAV,
... |
nums = map(int, raw_input().split(" "))
nums.sort()
n = nums[-1]
sumVals = n*(n+1)/2
sumList = sum(nums)
print sumVals-sumList |
import math
def remove_all_space_in_string(string):
return string.replace(' ', '')
def calculate_size_matrix(length):
sqrt_length = math.sqrt(length)
row = math.floor(sqrt_length)
column = math.ceil(sqrt_length)
if row * column < length:
row += 1
return int(row), int(column)
def ... |
import glob
from PIL import Image
import numpy as np
import os
import sys
from tqdm import tqdm
import shutil
if __name__ == '__main__':
# arg_Model : which model to use
# arg_DataRoot : path to the dataRoot
# arg_thres : threshold of the image output from the model
Thres = 200
dataRoot = 'o... |
from django.shortcuts import render
import requests
from django.http import HttpResponse
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from conversion.models import save_data
def conversion_page(request):
return render(request, 'conversion_page.html')
@csrf_exempt
def conversion_... |
from PyCircuit import Vector, Or, Memory, Register, VFalse, VTrue, \
FeedbackVector, If, Enum, ConstantVector, And, Case
class abstractDo:
pass
class doIf(abstractDo):
def __init__(self, cond):
self.cond = cond
def do(self, val):
assert len(self.cond) == 1
for r in val:
... |
# The superclass to implement selection operators.
# It is an abstract class.
class SelectionOperator:
# Constructor
# name: name of the selection operator
def __init__(self, name: str="Unspecified selection operator"):
self.name = name;
# Accessor on the name of the operator
def getName(s... |
z1,z2,z3=map(int,input().split())
w=(z1/2)*(2*z2+(z1-1)*z3)
print(int(w))
|
""" Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (o... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Apriori
#Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the DataSet
dataset = pd.read_csv('Market_Basket_Optimisation.csv', header = None)
transactions = []
for i in range(0,7501):
transactions.append([str(... |
import sunspec2.mdef as mdef
import json
import copy
import pytest
def test_to_int():
assert mdef.to_int('4') == 4
assert isinstance(mdef.to_int('4'), int)
assert isinstance(mdef.to_int(4.0), int)
def test_to_str():
assert mdef.to_str(4) == '4'
assert isinstance(mdef.to_str('4'), str)
def test... |
#This Is Calculator Projects
import os
import math
print("Welcome To My First Simple Project(Calculator using Python3)")
list_menu = ["Addition",
"Substraction",
"Multiplication",
"Division",
"Modulo",
"Raising to a power",
... |
import copy
def one_hot(x, len):
a = []
for i in range(len):
if i == x:
a.append(1)
else:
a.append(0)
return a
def normal_1(a):
b = copy.deepcopy(a)
sum = 0
for i in b:
sum += i
if sum == 0:
print('divide zero error')
exit(1)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
delete_nvl_circle_element_query = """
UPDATE public.nvl_circle AS ncr SET deleted = TRUE,
active = FALSE WHERE ($1::BIGINT is NULL OR npg.user_id = $1::BIGINT) AND ncr.id = $2::BIGINT RETURNING *;
"""
# delete_nvl_circle_element_by_location_id... |
# Generated by Django 2.0 on 2018-01-30 15:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('karbar', '0003_auto_20180130_1513'),
]
operations = [
migrations.AlterField(
model_name='myuser',
name='user_type',
... |
from flask_wtf import FlaskForm
from wtforms import *
from wtforms.validators import *
from wtforms.widgets import HiddenInput
from app.models import Category
def unique_create_name(form, field):
if field.data:
if Category.query.filter_by(name=field.data).first():
raise ValidationError(f"A cat... |
import pyterrier as pt
import unittest
import os
import shutil
import tempfile
class TestTRECIndexer(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestTRECIndexer, self).__init__(*args, **kwargs)
if not pt.started():
pt.init(logging="DEBUG")
# else:
#... |
__author__ = 'Supa'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Foursquare venue scraper
"""
from scraper import BaseVenueScraper
import foursquare
import json
# Foursquare venue scraper
class Scraper_4SQVenues(BaseVenueScraper):
source_name = '4sq'
def __init__(self):
"""
Initialises foursquare api libr... |
def wdm(talk):
return ' '.join(x for x in talk.split() if x not in ('puke','hiccup'))
'''
Fortunately last weekend, I met an utterly drunk old man. He was too drunk to
be aggressive towards me. He was letting everything what he held out,
from both his mind and his stomach. Although i was a bit uncomfortable,
th... |
import socket
import sys
import time
HOST = socket.gethostname()
PORT = 5001
client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client_socket.connect((HOST,PORT))
print(""" Welcome to file share server
Choose a option from the menu
To download a file enter: D
... |
import unittest
from katas.beta.string_to_list_of_integers import string_to_int_list
class StringToIntegerListTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(string_to_int_list('1,2,3,4,5'), [1, 2, 3, 4, 5])
def test_equal_2(self):
self.assertEqual(string_to_int_list('2... |
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import sys, os
sys.path.append(os.getcwd())
from utils.data import time, series, plot_series
from utils.prepDataset import create_window_dataset, create_seq2seq_window_dataset
from utils.modelForecast import model_fo... |
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from player import Player
player = Player()
player.play(["files/start.mp3"])
input("Press Enter stop...")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 23:29:27 2018
@author: ck807
"""
import numpy as np
import tensorflow as tf
from residual import Residual
from keras.models import Model
import matplotlib.pyplot as plt
import keras
from keras.layers.convolutional import Conv2D, UpSampling2D... |
# 要求时间复杂度小于O(nlogn)
# O(n*logk)解法
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
res = []
cnt = {}
for item in nums:
c = cnt.get(item, 0)
cnt[item] = c + 1
for key, val in cnt.items():
if len(res) < k:
... |
import kivy
kivy.require('1.9.1')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
Builder.load_string("""
<ScreenOne>:
BoxLayout:
Button:
text: "Go to Screen 2"
on_press:
root.manager.trans... |
from __future__ import annotations
import sys
from typing import (
Any,
Callable,
Mapping,
Optional,
Sequence,
)
from tabulate import tabulate
from ai.backend.client.cli.pretty import print_error, print_fail
from ai.backend.client.cli.pagination import (
echo_via_pager,
get_preferred_page... |
import mysql.connector
import logging
import json
formatStr = '%(asctime)s - %(message)s'
logging.basicConfig(level=logging.INFO, filename='crypto.log', filemode='w', format=formatStr)
logFormatter = logging.Formatter(formatStr)
rootLogger = logging.getLogger()
fileHandler = logging.FileHandler(filename='crypto.log'... |
print("about to import")
from pyspark.sql import SQLContext
from pyspark.sql import HiveContext
from pyspark.sql.types import *
#import steel_thread
import ml_processing
from pyspark import SparkContext
#import forecast_data_v3
import forecast_data_v4
import numpy as np
import pandas as pd
print("finished importing")
s... |
num1 = float(input ("insira um numero: "))
#num1 = float(input ("insira um numero: "))
print ("o cubo eh : " , num1**3)
print ("o quadrado eh : ", num1**2)
|
# 模拟题
class Solution:
def validUtf8(self, data: List[int]) -> bool:
n = len(data)
i = 0
while i < n:
if (data[i] >> 7) ^ 1:
i += 1
else:
cnt = 0
while (data[i] >> (7 - cnt)) & 1:
cnt += 1
... |
# Copyright 2021-2022 NVIDIA Corporation
#
# 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 ... |
#!/usr/bin/env python
#This script will pull ERA-Interim data from Dec. 1997 thru Dec. 2012
#
#One input is accepted and sets the grid interval
#
#List of variables to get
# 130 - Temperature (K)
# 131 - Eastward wind component (m s^-1)
# 132 - Westward wind component (m s^-1)
# 133 - Specific Humidity (kg kg^-... |
# Author: Vyas K. Srinivasan
# Bollinger Band Code - Calculate Bollinger Band
import pandas as pd
import numpy as np
from utils import getData
# Helper function to get rolling sum for a given lookback
def getSMA(df_data, lookback=20):
return df_data['Close'].rolling(lookback).mean().values
# Helper function to ... |
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data() # 导入mnist 数据集
# 归一化处理
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
''' 定义神经网络 输入层1个神经元,隐含层10个神经元,输出层1个神经元 '''
model = tf.keras.models... |
import numpy as np
import matplotlib.pyplot as plt
def data_parse(filename, trainSplit = 0.5, returnMatches = False):
'''
Data parsing function - usable for all datasets in Chen (2016)
Input:
filename - path to data file to read
Output:
matches - list of all individual matches in ... |
myFile = open('first.txt', 'w') # Open the file
myFile.write('hello Python\n')
myFile = open('first.txt', 'a') # Open the file to append something
myFile.write('hello Python 3.5 ')
myFile = open('first.txt')
#print(myFile.readline()) # Read the lines in the file
for line in open('first.txt'): # Using iterator ... |
import pymysql.cursors
connection = pymysql.connect(host=#'hostname',
user=#'username',
password=#'password',
db=#'dbname',
charset=#'utf8',
cursorclass=pymysql.cursors.DictCursor)... |
#
from rest_framework import serializers
from mywing.angel.models import Angel
from mywing.task.serializers import TaskSerializer
class AngelSerializer(serializers.ModelSerializer):
owned_tasks = TaskSerializer(many=True, read_only=True)
helped_tasks = TaskSerializer(many=True, read_only=True)
class Met... |
import pandas as pd
import pydeck
import altair as alt
import folium
from vega_datasets import data
COLOR_BREWER_BLUE_SCALE = [
[240, 249, 232],
[204, 235, 197],
[168, 221, 181],
[123, 204, 196],
[67, 162, 202],
[8, 104, 172],
]
mydf = pd.DataFrame({
'name': ['Constanta', 'Turin', 'Madrid'... |
from django.urls import path
from .views import (PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView
)
from . import views #. is for the current directory
"""
urlpatterns
after being called from django_project blog.urls, it will come to this folder
and... |
# Copyright 2014 OpenStack Foundation
# 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 requ... |
import collections.abc
import difflib
import io
import mmap
import platform
from typing import BinaryIO, Callable, Collection, Sequence, TypeVar, Union
import numpy as np
import torch
from torchvision._utils import sequence_to_str
__all__ = [
"add_suggestion",
"fromfile",
"ReadOnlyTensorBuffer",
]
def ... |
import sys
import numpy as np
import scipy as sp
import math
from scipy.io import loadmat
from scipy.signal import medfilt
from keras import backend as K
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import MaxPooling1D, Conv1D, Activation
from keras.optimizers i... |
from divisors import divisors
def test_one():
assert divisors(1)==[1]
def test_two():
assert divisors(2)==[1,2]
def test_three_to_nine():
assert divisors(3)==[1,3]
assert divisors(4)==[1,2,4]
assert divisors(5)==[1,5]
assert divisors(6)==[1,2,3,6]
assert divisors(7)==[1,7]
assert divisors(8)==[1,2,4,8]
asse... |
num_alunos = 5
nomes = []
notas = []
media = 0
for i in range(num_alunos):
nomes(input('Informe o nome do aluno: '))
notas.append(eval(input('Informe a nota de '+ nomes[i] +': ')))
media = media + notas[i]
media = media / num_alunos
print('A media da turma é: ',media)
for i in range(num_alunos):
if n... |
import alpaca_trade_api as tradeapi
import yfinance as yf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import coloredlogs
import tensorflow as tf
import numpy as np
import time
import sys
from agent import Agent
from methods import eval_model_new
from utils import get_stock_data, get_state
from get_all_tickers im... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.build_files.fmt.base import FmtBuildFilesRequest
from pants.backend.python.lint.black import subsystem as black_subsystem
from pants.backend.python.lint.black.rules impo... |
"""
Author : Lily
Date : 2018-09-21
QQ : 339600718
赫妍 HERA Hera-s
抓取思路:所有页面在同一个页面上,直接解析页面即可
Url: http://www.hera.com/cn/zh/misc/store.html
"""
import requests
import re
import datetime
from lxml import etree
filename = "Hera-s" + re.sub('[^0-9]', '', str(datetime.datetime.now())) + ".csv"
url = "http://www.hera.com/cn/... |
import cv2
import segmentation as seg
import preprocessingImage as ppi
# class containing logic for counting areas in a grayscale image & process it in 2 stages
# stage 1: pre-processing
# stage 2: segmentation
class count_area:
# function to display properties of gray image
def properties_image(gray):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import csv
class htls(object):
""" HTLS """
def __init__(self, word = None):
""" Do init. """
## Read txt file.
self.aw = open('./behao2.txt', 'r').read().split('\n')[:-1]
## set the HTLS vars.
self.hts = ['成熟運','發展運',... |
# The classic Hubot Shipit script.
import random
from espresso.main import robot
squirrels = [
"http://images.cheezburger.com/completestore/2011/11/2/aa83c0c4-2123-4bd3-8097-966c9461b30c.jpg",
"http://images.cheezburger.com/completestore/2011/11/2/46e81db3-bead-4e2e-a157-8edd0339192f.jpg",
"http://28.media.tum... |
# -*- coding: utf-8 -*-
"""
@author: tut_group_50
"""
import numpy as np
import csv
from sklearn.preprocessing import LabelEncoder
def load_data(folder):
"""
Loads the data to numpy arrays
Parameters:
folder: foldername in working dir that contains the data or path to folder
Returns:
... |
import unittest
import json
from flask import current_app as app
from unittest.mock import patch
from app.test.base import BaseTestCase
class TestHealthcheckBlueprint(BaseTestCase):
def test_healthcheck_api_with_good_config(self):
response = self.client.get('/healthcheck/')
result = json.loads(response.data... |
import socket
import time
from contextlib import closing
import datetime
import numpy as np
import matplotlib.dates as mdates
def main():
host = '127.0.0.1'
port = 4000
count = 0
dat = 1
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
n_cnt =400
time_range = n_cnt# 24 * 30
... |
from selenium.webdriver import ActionChains
class MainMenu():
def __init__(self, driver):
self.driver = driver
def goto_users_sub_menu(self):
ActionChains(self.driver).move_to_element(self.driver.find_element_by_xpath('//*[@id="menu_admin_viewAdminModule"]/b')).move_to_element(self.driver.... |
get_age = int(input("Enter your age"))
if get_age <= 13:
print("Kids are allowed from Gate No. 3")
elif get_age <= 40:
print("Adults are allowed from Gate No. 4")
else:
print("Old Citizen are allowed from Gate No. 5") |
import unittest
from katas.kyu_7.batman_quotes import BatmanQuotes
class BatmanQuotesTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(BatmanQuotes.get_quote([
'WHERE IS SHE?!', 'Holy haberdashery, Batman!',
'Let\'s put a smile on that faaaceee!'], 'Rob1n'
... |
class Vec3:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __add__(self, rhs):
c = self.clone()
c += rhs
return c
def __iadd__(self, rhs):
self.x += rhs.x
self.y += rhs.y
self.z += rhs.z
return self
... |
import numpy as np
import glob
import os
import queue
from bbcliutils.rztdata import ExecContexts
from bbcliutils.rztdata.RZTData import RZTData
def generate_queue(source):
queue_array = [filename for filename in glob.glob(source)]
queue_array.sort()
file_queue = queue.Queue()
for i in range(len(queu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.