text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 20:41:01 2021
@author: marina
Interesting:
- T2000_NPOP100_NGEN500_NEU2-10-5-2-1_05-04-2021_19-08-51: Really smooth and contained between (-3,3)
- T2000_NPOP100_NGEN500_NEU2-10-5-2-1_05-04-2021_19-25-20
"""
# Set absolute package path
i... |
# coding: utf-8
import re
from exceptions import TemplateError
import operator
BLOCK_ROOT = 'root'
BLOCK_CODE = 'code'
BLOCK_VAR = 'var'
BLOCK_TEXT = 'txt'
logical = {
'==': operator.eq,
'!=': operator.ne,
'>': operator.gt,
'>=': operator.ge,
'<': operator.lt,
'<=': operator.le,
}
class _Node... |
import random
PlayerOne = "Анна"
PlayerTwo = "Алекс"
AnnaScore = 0
AlexScore = 0
# У каждого кубика шесть возможных значений
diceOne = [1, 2, 3, 4, 5, 6]
diceTwo = [1, 2, 3, 4, 5, 6]
def playDiceGame():
"""Оба участника, Анна и Алекс, бросают кубик, используя метод shuffle"""
for i in range(5):
# ... |
def discard(POKER, hand, board):
h = hand
possibleHands = [[h[1],h[2]],[h[0],h[2]],[h[0],h[1]]]
bestHand = 0
bestEq = 0
for i in xrange(3):
eq = twoCardPostFlopEquity(possibleHands[i],h[i],board) # DEFINE THIS FUNCTION!!!!!
if eq > bestEq:
bestEq = eq
bestHand... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='datetime_tools',
version='1.4.3',
description='Datetime tools for Django',
author='Proteus Technologies',
author_email='team@proteus-tech.com',
url='http://proteus-tech.com',
packages=['datetime_tools', 'datetime_to... |
#!/usr/bin/env python
"""
This code runs the neural network on frames and outputs detections of lenses.
"""
import numpy as np
import cv2
import os
import rospy
from std_msgs.msg import String
from sensor_msgs.msg import Image
from geometry_msgs.msg import Point, PointStamped
from cv_bridge import CvBridge, CvBridgeErr... |
import sqlite3
import json
def main():
db = sqlite3.connect('climatedata.db')
cur = db.cursor()
data = cur.execute('SELECT * FROM CLIMATE_DATA;').fetchall()
print(data[0])
cur.close()
ans = []
for row in data:
ans.append({
'latitude': row[0],
'longitude': r... |
from django.db import models
# import locations
from locations.models import Country, Canton, Municipality, PLZ
# *****************************************************************************************
# Fraction
# *****************************************************************************************
class Fract... |
import torch
import torch.nn as nn
import torchvision.models
import torch.nn.functional as F
from scipy.special import softmax
from .backbones import *
from .senet import *
from .activation import *
from .layers import *
from .self_attention import SelfAttention
def drop_fc(model):
if model.__class__.__name__ ==... |
# coding:utf-8
# @author : csl
# @date : 2018/10/09 16:51
# 币币交易页面
from BaseSe.Selenium3 import Pyse
class DKpc_ExchangePage(Pyse):
"""
@descreption:币币交易页面
"""
|
# zip takes n number of iterables and returns a list of tuples.
# the ith element of the tuple is created using the ith element from each of the iterables.
list_a = [1, 2, 3, 4, 5]
list_b = ['a', 'b', 'c', 'd', 'e']
zipped_list = list(zip(list_a, list_b))
print (zipped_list) # [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')... |
from django.contrib import admin
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('',views.store, name='store'),
path('cart/',views.cart, name='cart'),
path('checkout/',views.checkout, name='checkout'),
path('update-item/', views.updateItem, name='update-item'),... |
from django.db import models
from django.contrib.auth import get_user_model
import numpy as np
User = get_user_model()
class Polygon(models.Model):
ADS_TYPE = [
('Сдам', 'Сдам'),
('Продам', 'Продам'),
]
name = models.CharField(max_length=250, verbose_name='Название полигона')
user ... |
from selenium import webdriver
class RuffTests():
def testMethod(self):
driver= webdriver.Firefox()
driver.get("http://www.letskodeit.com")
ff= RuffTests()
ff.testMethod() |
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
h = ListNode(None)
p1 = p2 = h
h.next = head
while p2.next and p2.next.next:
p2 =... |
from tkinter import *
import tkinter as tk
from first_window import LogIn_Screen
def main():
root = tk.Tk()
root.geometry("400x400")
root.title("Main Window")
ls = LogIn_Screen(root)
# f1 = Frame(root, bg = 'cyan', height= 100, width=100)
# f1.pack()
root.mainloop()
if __name__ == "__ma... |
# -*- coding: utf-8 -*-
from openerp import http
import openerp
import re
from openerp.http import request
#
class website_sale(openerp.addons.website_sale.controllers.main.website_sale):
@http.route()
def cart(self, **post):
# Todo I need change this function is no good sorry the time is fast
... |
def filter(list, object):
filtered_list = []
for i in list:
if i == object:
filtered_list.append(i)
return filtered_list
def exclude(list, object):
lenght = len(list)
for i in range(lenght-1, -1, -1):
if list[i] == object:
list.pop(i)
return list
def un... |
# Generated by Django 2.0.2 on 2018-03-14 15:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('demoapp', '0011_remove_car_brand'),
]
operations = [
migrations.RenameField(
model_name='car',
old_name='brand_svyaz',
... |
# Match staff record to barcode
# Inputs
# barcode table - a csv loaded into a Dict
# staff file - a csv from CHCCS with all staff records
import csv
update_patrons = open("update_staff_patrons.csv", encoding='utf-8', mode='w+')
update_patron = csv.writer(update_patrons)
new_patrons = open("new_staff_patro... |
# Generated by Django 3.0.7 on 2020-06-14 06:44
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Documents',
fields=[
('id', models.AutoFiel... |
#!/usr/bin/ptyhon3
from pathlib import Path
import sys
import os
import random
from subprocess import call
import re
from Bio import SeqIO
from Bio.Seq import Seq
from tempfile import NamedTemporaryFile
rna2dna_maps = {
'A' : ['GCT', 'GCC', 'GCA', 'GCG'],
'R' : ['CGT', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'],
'N' : ['AAT',... |
import sys
sys.path.append("/home/profesor/GatewayIoT")
import time
import requests
import json
from gateway import RD_functions
import redis
import socket
# def main():
# pool = redis.ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True)
# pool = redis.ConnectionPool(host='172.24.100.98', port=808... |
from tkinter import *
from tkinter import messagebox
import time
"""Concept----->
# This Concept is made to make the program too efficient in GUI apps
1.Insert first: New node should add after the last node but the new node value should set to the
first node of the list after shifting node value in a required di... |
import numpy as np
import mxnet as mx
from mxnet import nd
from mxnet.gluon import Block, HybridBlock, nn, rnn
from config import ROWS, COLUMES, FLOW_OUTPUT_DIM, FLOW_OUTPUT_LEN
from model.structure import MFDense, ResUnit
N_LOC = ROWS * COLUMES
class ResNet(Block):
def __init__(self, filters, hiddens... |
from django.shortcuts import render
from .models import Post
# Create your views here.
def all_article(request):
all_article = Post.objects.all()
context = {
'posts':all_article,
}
return render(request,'all_article.html',context)
def article(request,id):
article = Post.objects.get(id=id)
... |
from functools import reduce
cubo = lambda x: x * x * x
soma = lambda x,y: x + y #paradigma funcional
print(soma(2,3))
lista= [10,2]
isMaior10 = lambda x : x > [10]
# maiores10 = lambda x : isMaior10(x)
print(isMaior10(lista))
print(sorted(lista)) #ordena crescente
print(sorted(lista,reverse=... |
from num2words import num2words
from word2number import w2n
import re
import itertools
from .core import op
_w_zero_to_ten = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
'nine', 'ten']
_w_eleven_to_nineteen = ['eleven', 'twelve', 'thirteen', 'fourteen',
'fif... |
##unsorted list
mylist=[5,6,23,0,2,1,77,33,2]
##call built in function sorted
newlist=sorted(mylist)
##showing the result
print ' mylist '
print mylist
print 'sorted list '
print newlist
|
user_input = input("Enter your first choice: ")
user_input2 = input("Enter your second choice: ")
playlist = [user_input, user_input2]
print(playlist)
playlist.sort()
print(playlist)
user_input3 = input("Enter your third choice: ")
playlist.append(user_input3)
playlist.reverse()
print(playlist) |
import pylab as pb
import numpy as np
from math import pi
import scipy
from scipy.spatial.distance import cdist
from scipy.stats import multivariate_normal
import matplotlib.pyplot as plt
import random
def sqExpKernel(X,Y,length_scale):
return np.exp(-cdist(X, Y, 'sqeuclidean')/(length_scale**2))
def data():
# X=n... |
import turtle as t
t.shape('turtle')
t.bgcolor('black')
t.color('yellow')
t.speed(0)
angle = 89 # 거북이가 왼쪽으로 회전할 각도를 지정한다
for i in range(200):
t.forward(i) # i 만큼 앞으로 이동한다(실행을 반복하면서 선이 길어짐)
t.left(angle) # 거북이가 왼쪽으로 89도 회전한다 |
#!/usr/bin/env python
import sys, os
from pprint import pprint
# sys.path.append("/home/maarten/TwitterMySQL")
from TwitterMySQL import TwitterMySQL
from TwitterAPI import TwitterAPI
locationPath = '/'.join(os.path.abspath(__file__).split('/')[:-2]) + "/Code/"
locationPath += "PERMA/data/twitter"
print "locationPath:... |
from features import Feature
from consts import Consts
from training import Training
import pickle
import abc
class Model(metaclass=abc.ABCMeta):
feature = None
v_parameter = None
def __init__(self, method: str, file_full_name: str=None):
if method == Consts.TRAIN:
self._training(fil... |
"""Display an image in a Tk label."""
from tklib import *
# from cvlib import *
import cv2 as cv
from PIL import Image, ImageTk
class Demo(App):
def __init__(self, **kwargs):
super(Demo, self).__init__(**kwargs)
Label('Change Colorspace of OpenCV image', font='Arial 24')
img0 = cv.imread('... |
import json as simplejson
from django.http import HttpResponse
from django.contrib.auth.models import User
def user_search(request):
search_qs = User.objects.filter(username__contains=request.GET['search']).all()
results = []
for r in search_qs:
results.append(r.username)
resp = request.GET[... |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2013 Contributor
#
# 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 Li... |
import os
import csv
import pickle
class PySplunk(object):
"""Get log clustering using Python Splunk API [SplunkDev2016]_.
This script is used to cluster log file which manually inputted to Splunk.
References
----------
.. [SplunkDev2016] Command line examples in the Splunk SDK for Python.
... |
import numpy
import wave
# 'rb' is binary reading modes. otherweise EOL chars corrupt on windows
wavefile = wave.open("tmp/11k16bitpcm.wav", 'rb')
channels = wavefile.getnchannels()
sampwidth = wavefile.getsampwidth()
nsamp = wavefile.getnframes()
framerate = wavefile.getframerate()
print ("channel, sampwidth, framer... |
from django.shortcuts import render
from django.views import View
from rest_framework.views import APIView
from rest_framework import status
from ikeng.core.models.profile import Profile
from ikeng.core.forms import SubscriberForm
from ikeng.core.models.subscriber import SubscriberModel
from ikeng.core.models.post impo... |
"""Timesketch magic module.
This module conatins an implementation for the Picatrix Timesketch integration.
It enables colab/jupyter to send and receive data from a Timesketch sketch.
"""
import datetime
import logging
import os
from typing import Any
from typing import Dict
from typing import List
from typing import... |
from binascii import hexlify
from typing import IO
from base.header import MagicFileHeader
from format.pkg.revision import PkgRevision
from format.pkg.type import PkgType
from utils.utils import read_u32, read_u64, Endianess
from .ext_header import PkgExtHeader
class PkgHeader(MagicFileHeader):
def __init__(self... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpRequest
from django.db.models import Avg
from .models import Book
def index(request: HttpRequest):
books = Book.objects.all().order_by("-rating")
num_books = books.count()
avg_rating = books.aggregate(Avg("rating"))
r... |
#!/usr/bin/env python
""" train_model.py
To run:
train_model.py
Output:
intermediary.pkl
intermediary.pkl is a python dictionary with the following keys, values:
{
"vectorizer" : a scikit-learn vectorizer for text data,
"country_dict" : a dictionary for converting between country code and integer,
... |
import pickle
import cv2
import numpy as np
import glob
# Step through the test images list and undistort
def undistort(filename, cameraMatrix, distCoeffs):
image = cv2.imread(filename)
print('processing filename: ', filename)
# undistort the image
undistorted_image = cv2.undistort(image, ... |
class ServerInstance:
def __init__(self, client, server):
self.server_obj = server
self.client = client
self.member = self.server_obj.me
self.text_channel_instances = []
def register_channel(self, channel):
self.text_channel_instances[channel.id] = ChannelInstance(self.c... |
def water_state(temperature):
if temperature > 100:
print "Steam ", temperature, "C"
elif temperature < 0:
print "Ice", temperature, "C"
else:
print "Liquid", temperature, "C"
water_state(23)
water_state(125)
water_state(-20)
water_state(33)
|
# -*- coding: utf-8 -*-
import re
import scrapy
from scrapy_redis.spiders import RedisSpider
from ganji.items import CheSuPai
import time
import logging
# from spiders.SpiderInit import spider_original_Init
from ganji.spiders.SpiderInit import spider_original_Init
website ='carsupai'
# main
class CarSpider(RedisSpide... |
# Contestant ID: 506
# The Pizza.py class file will hold all of our data for a single pizza.
class Pizza:
# "Private" access attributes
# (These aren't really private in the sense of private in Java,
# as there are no access modifiers in Python.
# This is simply a way of naming variables that is common... |
#!/usr/bin/python
import sys
import os
import time
import re
import synapseclient
from synapseclient import File
syn = synapseclient.login()
tbl = syn.tableQuery("select * from syn17025501 where individualID is not null")
df = tbl.asDataFrame()
format = lambda x: x.replace(' ','_')
df['group'] = df['specimenID'].ma... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823"
pi = pi.replace(".", "")[:100]
# initialize result as dict
result = {str(x):0 for x in xrange(10)}
for i in xrange(100):
result[pi[i]] += 1
... |
from srv import pricedata, portfolio, inputs, format
import finnhub
from decouple import config
FINNHUB_CLIENT_KEY = config("FINNHUB_KEY")
FINNHUB_CLIENT = finnhub.Client(api_key=FINNHUB_CLIENT_KEY)
def start_program():
"""
Provide opening option to user and runs appropriate
function based on the respons... |
import requests
from covid_stats import COVID_Data
state = (input("Abbreviation of State: ")).lower()
user_input = ""
while(user_input != 'exit'):
print("")
print("1. Number of Cases")
print("2. Mortality Rate")
print("3. Hospitalization Rate")
print("4. Recovery Rate")
print("5. Travel Adivso... |
# coding=utf-8
from django import template
from ..models import News, Portfolio
register = template.Library()
@register.inclusion_tag('content/block_news_list.html')
def latest_news(count):
news_list = News.objects.active()[:count]
return dict(news_list=news_list)
@register.inclusion_tag('content/block_por... |
#!/usr/bin/env python3
import argparse
import json
import sys
"""
Function to set any value from database.
Example usage:
`python3 setConfigEntry configuration.network.hostname horst`
would change the hostname of the network to "horst"
in BASH use:
setConfigEntry configuration.network.hostname $NAME
"""
parser = ar... |
from torch.utils.data import SequentialSampler, DataLoader
from tqdm import tqdm
from seqeval.metrics import f1_score, classification_report
import torch
import torch.nn.functional as F
def add_xlmr_args(parser):
"""
Adds training and validation arguments to the passed parser
"""
parser.add_argum... |
#!/usr/bin/env python3
# url="http://api.openweathermap.org/data/2.5/weather?zip=33472&units=imperial&wind.direction.name&appid={}"
lat="26.5463162"
lon="-80.152788"
url="http://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&units=imperial&wind.direction.name&appid={}"
import os
import requests
import datetim... |
# import gym
import numpy as np
from utils import *
from MCTS import MCTS
from utils import *
import pandas as pd
import time, csv, os
class Evaluate:
def __init__(self, nnet, env, args):
self.env = env
self.tot_ep_length = self.env.steps_till_done + self.env.max_steps_beyond_done + 1
self... |
__version__ = '0.4.0'
import os
# Switch matplotlib backend if display is not set up correctly
cmd = 'python3 -c "import matplotlib.pyplot as plt; plt.figure()" 2> /dev/null'
if os.system(cmd): # if command fails
print('No display found. Switching matplotlib backend to "Agg"')
import matplotlib; matplotlib.u... |
class HighScore:
def __init__(self, db):
self.db = db
@property
def name(self):
if self.db.exists('name'):
# Redis returns a byte string. We decode to a Unicode string
# (which is what we get when we say something like 'hi')
return self.db.get('name')... |
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView, TemplateView, UpdateView, ListView
from django.contrib.auth.mixins import LoginRequiredMixin
from accounts import forms
from matches.models import UserPredictions
from django.contrib.auth.models import ... |
import hashlib
import re
import xml.etree.ElementTree as ET
from os import listdir
from os.path import isfile, join, isdir
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
nltk.download('stopwords')
nltk.download('wordnet')
# case insensitive stop words removal
def no_stopwords(toke... |
from tkinter import *
from tkinter.ttk import *
from tkinter import ttk
import tkinter.messagebox as ms
import hashlib
from pymongo import MongoClient
import os
import main
import Passwords
class Login(Frame):
def __init__(self, root):
root.maxsize(600, 300)
root.minsize(600, 300)
root.tit... |
"""Determine the best rocket propulsion designs for one stage of a rocket, given a set of
constraints and preferences (Kerbal Space Program)."""
__version__ = '0.11'
|
'''
Created on Apr 20, 2015
Usage: python subfier.py <subtitle file>
@author: Matan Keidar
'''
import os.path
import codecs
import sys
INPUT_ENCODING = "windows-1255"
OUTPUT_ENCODING = "windows-1255"
prefixPunctuation = { '-', '.', '?', '!', ',', '"', ':', ';' }
suffixPunctuation = { '-', '.', '?', '!', ',', '"', ... |
from evxpredictor import mlbot
from concurrent.futures import ThreadPoolExecutor
import time, asyncio
async def runner(alpha,sig):
with ThreadPoolExecutor(max_workers=2) as executor:
futures = executor.submit(mlbot.signal, 20,65,120,alpha,f'{sig}')
return futures.result()
start = time.perf_counter()
print(asyn... |
#!/usr/bin/python3
from sys import argv
from shutil import copy
from string import Template
from argparse import ArgumentParser
from os import makedirs, path, readlink, system
BASE_DIR = path.dirname(readlink(argv[0]))
def create_dir(name):
if not path.exists(name):
makedirs(name)
def read_file(name):
... |
from System.Utilities.Logging import get_system_logger, get_telemetry_logger
class Vessel:
def __init__(self):
""" """
pass
|
from domain_lexicon import *
class Domain_Identifier:
''' Runs methods for the list of words recieved from the tokenizer '''
def __init__(self, message):
self.message = message
def check_healthcare(self):
''' Check to see if any words in the list of words matches
the healthcare section of the ... |
from member import views
from django.conf.urls import url
from django.urls import path
urlpatterns = [
url(r'^register', views.members),
url(r'^list', views.members),
url(r'^login', views.login),
url(r'^modify', views.member_modify),
path('delete/<slug:pk>', views.member)
# 바로옆에있는 view중 memb... |
#!python3
import sys
import dash_core_components as dcc
import dash_html_components as html
from dash import Dash
from dash.dependencies import Output, Input, State
from projection_viewer import callbacks
from projection_viewer.frontend import layouts
from projection_viewer.frontend import visualiser
from projection... |
#!/usr/bin/env python3
"""
superstat -- easy multi directory git status
MIT License
Copyright (c) 2019 Owen Stranathan
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, includ... |
class Solution:
def topKFrequent(self, words: 'List[str]', k: 'int') -> 'List[str]':
from collections import Counter
c = Counter(words)
c = sorted(c.items(),key = lambda x:(-x[1],x[0]))
res = []
for i in range(k):
res.append(c[i][0])
return res
a = Solut... |
import numpy as np
import math
def get_frames(replay):
frames = np.array(replay['frames'])
prods = np.repeat(np.array(replay['productions']).reshape((1,frames.shape[1],frames.shape[2],1)),frames.shape[0],axis=0)
return np.concatenate([frames,prods],axis = 3)
def center_frame(frame,position,wrap_size=None)... |
import sys
from cloud_oos_detection.app_utils.utils import reformat_oos_coords_to_x_y_axis, \
reformat_label_coords_to_x_y_axis, format_coords_output
from utils.rect_utils import read_boxes, filter_boxes_by_size, \
filter_boxes_by_shelves, filter_oos_by_labels
from utils.shelf_estimator import extract_shelves
f... |
from .helper import *
@ratelimit(key='ip', rate='6/m', method='POST')
def register(request):
args = {
'errorMsg': '',
'infoMsg': ''
}
if request.method == 'POST':
buttonRegister = request.POST.get('buttonRegister')
inputEmail = request.POST.get('inputEmail')
inputUsername = request.POST.get('inputUserna... |
#!/usr/bin/eny python3
#sutimar pengpinij
#590510137
#Lab 11
#problem 1
#204111 Sec 003
def main():
m1 = input()
m2 = input()
print(matrix_mult(m1, m2))
def matrix_mult(m1, m2):
rows_m1 = len(m1[:])
rows_m2 = len(m2[:])
## colum_m1 ##
for row in range(rows_m1):
c... |
# Copyright 2011 Google 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/LICENSE-2.0
#
# Unless required by applicable law or a... |
from src.dataImporter import dataImporter
from src.preProcessor import preprocessor
from src.smoothingFilter import smoothingFilter
from src.orientation import orientation
from src.stepCounter import stepCounter
from src.stepLength import stepLength
from src.position2D import position2D
from src.simulator import simula... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
not_li =[]
def get_user_agent():
li = [
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)"
"Mozilla/5.0(Macintosh;U;IntelMacOSX10_6_8;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50",
... |
# Zadanie 4
# Napisz funkcję fibonacci_list, która dla zadanego n obliczy n liczb ciągu Fibonacciego, zwracając listę liczb
# z zadanego ciągu.
def fibonacci_list(n):
if n == 0:
return []
elif n == 1:
return [1]
elif n == 2:
return [1, 1]
elif n > 2:
result = [1, 1]
... |
from discord import Embed
from discord.ext import commands
from os import getenv
from pyowo import owo
from src.internal.bot import Bot
from src.internal.context import Context
from src.internal.checks import in_channel
from src.utils.msgfetch import fetch
class Misc(commands.Cog):
"""Miscellaneous fun commands... |
def print_multiplication_table(n):
i=1
while i<=n:
j=1
while j<=n:
print (str(i)+"*"+str(j)+"="+str(i*j))
j=j+1
i=i+1
print (print_multiplication_table(2))
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-23 15:20
from __future__ import unicode_literals
import django.contrib.postgres.fields
import django.contrib.postgres.fields.jsonb
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import opencivicdata... |
import pytest
from population_modeling import create_bacteria
from population_modeling.life_cycle import LifeCycle
from population_modeling.mutations.normal_mutator import NormalMutator
from population_modeling.mutations.variation_parameters import MutationParams
from population_modeling.population import create... |
import numpy as np
from matplotlib import pyplot as plt
import math
import math
x= np.arange(-2*math.pi,2*math.pi,4*math.pi/150) #vetor com 150 pontos linearmente espaçados entre -2pi e 2pi.
fig = plt.figure(figsize=(10, 10))
#gráfico seno
y1= np.sin(x)
ax1 = fig.add_subplot(2,2,1)
ax1.plot(x,y1,'r',linewidth=2)
p... |
#!/usr/bin/python
#coding=utf8
"""
@:param 在FetchBas2Csv.yml中配置:包括:数据库参数,表名称
@:creator wuyudong
@:description 读取当天的聚源和贝格数据表中终止上市的数据,取出两表数据中国不同的部分打印在控制台上。
@:return
********what need to install************
pip install cx_Oracle
pip install yaml
***********how to run*******************
1. please chmod +x FetchBas2Csv... |
import pandas as pd
import numpy as np
from Streams import stream
# Import data table for stream data
Data = pd.read_excel('test values.xlsx', index_col=0)
# Extract data from table
InletT = Data.loc[:, "Inlet"]
OutletT = Data.loc[:, 'Outlet']
CP = Data.loc[:, 'cp']
# Create and add streams
streams_cont... |
from django.shortcuts import render, redirect
from django.views.generic.edit import CreateView
from django.views.generic import ListView
from .models import Item
class ItemList(ListView):
model = Item
def home(request):
print('hi')
item_list = Item.objects.all()
print(item_list)
return render(requ... |
import openpyxl as xl
from CommandDecorator import *
from config import *
import json
def read_TableDefinition(excelDir):
book = xl.load_workbook(excelDir)
questions = listQ(
message="Select Sheet >> ", name="sheet", choicelist=book.sheetnames,
)
answer = prompt(questions, style=style)
s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-03-08 05:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0014_auto_20180308_1102'),
]
operations = [
migration... |
import turtle
import random
pen = turtle.Pen()
pen.speed(0)
turtle.bgcolor("black")
colors = ["red","blue","yellow","orange"]
for i in range(100):
x = random.randrange(-turtle.window_width()//2,turtle.window_width()//2)
y = random.randrange(-turtle.window_height()//2,turtle.window_height()//2)
pen.color... |
import sys
from unittest import TestSuite
from tornado.test.runtests import main
from .models_tests import TestUser
def all():
suit = TestSuite()
suit.addTest(TestUser('test_select'))
suit.addTest(TestUser('test_save_user'))
# suit.addTest(TestNote('test_get_method'))
# suit.addTest(TestNote('te... |
__author__ = '10014422'
import pygame
import random
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
red = (255, 0, 0)
orange = (255, 69, 0)
purple = (148, 0, 211)
y = 0
add = False
font = pygame.font.SysFont("comicsansms", 50)
speed = 0
level = 0
game... |
#
# test Python script to read Yelp data
#
import http.client
conn = http.client.HTTPSConnection("yelp-com.p.rapidapi.com")
headers = {
'x-rapidapi-host': "yelp-com.p.rapidapi.com",
'x-rapidapi-key': "b7b5f2745dmshabc69c1dcba13f2p191da7jsnd98306ea16c5"
}
conn.request("GET", "/business/DAiqwrmv19Uv-I1bOo... |
import pandas as pd
import os
import glob
import re
from enum import Enum
class StatType(Enum):
BATTING = 1
PITCHING = 2
def main():
batting_cols = [
"system",
"year",
"mlbam_id",
"G",
"AB",
"R",
"H",
"2B",
"3B",
"HR",
... |
import unittest, database
from subprocess import Popen, PIPE
class ProductTestCase(unittest.TestCase):
def testWithPyLint(self):
cmd = 'pylint', '-rn', 'database'
pylint = Popen(cmd, stdout=PIPE, stderr=PIPE)
self.assertEqual(pylint.stdout.read(), '')
if __name__ == '__main__':
unittest... |
#<editor-fold> Import Statements
import matplotlib.pyplot as plot
#%matplotlib inline
import numpy
#import tensorflow
import tensorflow.compat.v1 as tensorflow
tensorflow.disable_v2_behavior()
#</editor-fold> Import Statements
#<editor-fold> Unzipping the file and getting each picture.
CIFAR_DIR = "./cifar-10-batche... |
from enum import Enum
from selenium_wrapper.elements import Element
class LocatorsEnum(Enum):
def __init__(self, element: Element):
self.element = element
class PagesEnum(Enum):
def __init__(self, page_class):
self.page_class = page_class
|
import numpy as np
import pandas as pd
from scipy.constants import codata
from RF_mathematica import *
hc=codata.value('inverse meter-electron volt relationship')*1E+2 #eV.cm
def iter_calc(l2, react_S_B, react_L_B, I_B, term, J, L, S, level, skipped_level, second_ce, df_double_ce, ele_B, ele_A, prod_S_A, react... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.