text stringlengths 38 1.54M |
|---|
from enum import Enum
from sklearn.cluster import KMeans
from sklearn.utils import resample
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, pairwise_distances, recall_score, f1_score
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np... |
from typing import Union, Tuple
import numpy as np
import tensorflow as tf
from tensorflow.keras.losses import Loss, binary_crossentropy
from config import cfg
class YOLOv4Loss(Loss):
def __init__(
self,
num_class: int,
yolo_iou_threshold: float,
label_smoothing_f... |
# -*- coding: utf-8 -*-
""" Tests for the geometry module
SPDX-FileCopyrightText: 2016-2021 Uwe Krien <krien@uni-bremen.de>
SPDX-License-Identifier: MIT
"""
__copyright__ = "Uwe Krien <krien@uni-bremen.de>"
__license__ = "MIT"
from nose.tools import ok_, assert_raises_regexp
import os
import pandas as pd
from reeg... |
from sqlalchemy import Sequence
from sqlalchemy import Column, Integer, BigInteger, String, Boolean
from sqlalchemy.orm import relationship
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.exc import MultipleResultsFound
from Base import Base
from SessionFactory import SessionFactory
class User(Base... |
# Copyright 2013 Devsim LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
import unittest
import random
from calculator import Calculator
from rand_gen import RandomGenerator
from desc_stats import DescStats
from pop_sampling import PopSampling
class TestOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(Calculator.add(2, 3), 5, "Must be 5")
def test_subt... |
"""Various strategies for othello.
"""
import random
class Minimize:
"""Put disk to minimize number of one's disks."""
def __init__(self):
return
def put_disk(self, othello):
"""Put disk to minimize number of one's disks."""
min_strategy = []
min_merit = float('inf')
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 18 18:38:21 2016
@author: pi
"""
from rrbs import *
robot = RRB3(12, 6)
|
'''
Created on Apr 9, 2016
@author: Ibrahim
'''
def count (pancakes):
flips = 0
i =0
flipTogether = False
while True:
if i>=len(pancakes):
return flips
if pancakes[i]=='+':
flipTogether = True
i=i+1
... |
import click
from barique.cli import pass_context, json_loads
from barique.decorators import custom_exception, str_output
@click.command('pull')
@click.argument("path", type=str)
@click.option(
"--email",
help="User email adress for notification",
type=str
)
@click.option(
"--dry_run",
help="Do no... |
from distutils.core import setup
setup(name='PyKDE',
version='0.1.1',
packages = ['pykde'] )
|
#!/usr/bin/python3
# move the filter wheel using half step mode on a bipolar stepper
#
# usage: move_filter.py steps slow_level
# steps = number of steps (400 for a complete rotation)
# slow_level 1=fastest n=max_speed/n
import RPi.GPIO as GPIO
import time
import sys
# Variables
reverse=0
steps = int(sys.argv[1])
if ... |
#
# nested.py
# Copyright, 2007 - Paul McGuire
#
# Simple example of using nestedExpr to define expressions using
# paired delimiters for grouping lists and sublists
#
from pyparsing import *
data = """
{
{ item1 "item with } in it" }
{
{item2a item2b }
{item3}
}
}
"... |
from recherche.RI_Methodes import reverseFileConstructionMethods as ifcm
import math
def scoreInnerProduct(reverseFile,fquery,w):
return sum([ifcm.f(fquery,w)*ifcm.f(reverseFile,w) for w in fquery])
def scoreCoefDice(reverseFile,fquery,words):
up = 2*scoreInnerProduct(reverseFile,fquery,words)
# words = s... |
from sklearn.svm import SVC
from DataSet.iris import learn_iris
# ---------------------
# 線形SVMのインスタンスを生成
svm = SVC(kernel='linear', C=1.0, random_state=0)
# irisデータに対して学習
learn_iris(svm, title='SVM')
# ---------------------
from sklearn.linear_model import SGDClassifier
# 確率的勾配降下法バージョンのパーセプトロン
ppn = SGDClassifie... |
from lib import gcd, get_primes
import sys
primes = list(get_primes(500))
def small_factor(d):
# the answer cannot have a large prime in it, since that makes it
# more resilient - so we can be fast and lazy
f = []
for x in primes:
while d % x == 0:
f.append(x)
d /= x
... |
import copy
import esprima
import esprima.nodes as nodes
import re
import subprocess
from z3 import *
def printWithIndent(text, level):
print(' ' * level, end='')
print(text)
def representsInt(s):
try:
int(s)
return True
except ValueError:
return False
def fn_lookup(var, var... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def base(request):
return HttpResponse("Welcome to Webapp. Be happy.. your are the first one here!") |
from vocab import *
import numpy as np
import torch
from torch.autograd import Variable
# from k_means import KMeans
from simple_bucketing import Bucketing
from instance import *
import math
class Dataset(object):
def __init__(self, task, idx, type, src_type, file_name, max_bucket_num=80, word_num_one_batch=5000, ... |
# -*- coding: utf-8 -*-
peso = float(raw_input('Informe o peso de peixes: '))
peso_estabelecido = 50
excesso = 0
multa = 0
if peso > peso_estabelecido:
excesso = peso - peso_estabelecido
multa = 4 * excesso
print 'Excesso:', excesso
print 'Multa de R$ %.2f' % multa
|
# ------------------------------------------------------------
# "THE BEERWARE LICENSE" (Revision 42):
# <so@g.harvard.edu> and <pkk382@g.harvard.edu> wrote this code.
# As long as you retain this notice, you can do whatever you want
# with this stuff. If we meet someday, and you think this stuff
# is worth it, you can... |
# -*- coding:utf-8 -*-
import json
import tornado.escape
import tornado.web
from torcms.core.base_handler import BaseHandler
from torcms.model.reply_model import MReply
from torcms.model.reply2user_model import MReply2User
from torcms.core.tools import logger
class ReplyHandler(BaseHandler):
def initialize(self):... |
import json
import uuid
from app.constants import EMAIL_TYPE, MOBILE_TYPE
from app.dao.service_guest_list_dao import (
dao_add_and_commit_guest_list_contacts,
)
from app.models import ServiceGuestList
from tests import create_admin_authorization_header
def test_get_guest_list_returns_data(client, sample_service_... |
import pyautogui
import time
time.sleep(0.3)
def play2048(keys_combination):
while True:
for key in keys_combination:
pyautogui.press(key)
time.sleep(0.1)
play2048(['up', 'left', 'down', 'right']*20) |
import random
def rand_num (rnd_n):
for i in range(1, rnd_n+1,2):
print(f'Для {i} итерации случайное число {random.randint(1,int(i))}')
yield
n = int (input('Введите число: '))
rand_num(n)
|
'''
---------------------------------------------------------------------------
Question
---------------------------------------------------------------------------
Given an array nums, write a function to move all 0's to the end of it while
maintaining the relative order of the non-zero elements.
--------------------... |
#coding=utf-8
from pyvmodule.tools.pipeline import DataLine,PipeLine
from .bitdoc import BitDoc,Entry
__all__ = ['PipeDoc','PipeEntry']
class PipeEntry(Entry):
width = Entry.int_property('width')
class PipeDoc(BitDoc):
def __init__(self,filename,sheetnames,Entry=PipeEntry,**kwargs):
BitDoc.__init__(se... |
import abc
import os.path
from abc import ABC
from typing import Optional
import requests
from bs4 import BeautifulSoup
from .exceptions import CouldntFindDownloadUrl
from .utils import random_string
class MirrorDownloader(ABC):
def __init__(self, url: str, timeout: int = 10) -> None:
"""Constructs a ne... |
class Node: #Nodes are the basically the placeholders for the elements of the linkedlist
def __init__(self, data): #
self.data = data #Each node has a value stored in it, you pass ther value by creating an object
self.next = None #It also has a pointer that points to the next node, here that pointe... |
# -*- coding: utf-8 -*-
from ecore.release import version_info
try:
import models # noqa
import controllers # noqa
except ImportError:
if version_info >= (8, 'saas~6'):
raise
|
def answer(l,t):
'''
Args:
l (list of ints): list of numbers to be added
t (int): desired sum
Return:
inds (list of indexes): The starting and ending indexes which will sum to t from list l
'''
# We're looking for the first sublist of integers in l which s... |
import re
from datetime import datetime
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.response import Response
from django_news.utils.response_code import RET
from django_news.utils.to_dict import user_to_dict
from users.models import User
class SMSSerializ... |
import os
import numpy as np
import matplotlib.pyplot as plt
import sis_utils
import ersa_utils
class StatsRecorder:
def __init__(self, data=None):
"""
data: ndarray, shape (nobservations, ndimensions)
"""
if data is not None:
data = np.atleast_2d(data)
self... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.urls import reverse, reverse_lazy
from employee.forms import UserForm
from django.shortcuts import render, redirect
from django.contrib.auth import (
authentica... |
from django.conf.urls import url, include
from rest_framework import routers
from .views import LibraryViewset, BookInformationViewset, ItemViewset, \
LoanViewset, LoanUserViewset
router = routers.DefaultRouter()
router.register(r'libraries', LibraryViewset)
router.register(r'books', BookInformationViewset)
router.... |
# coding=utf-8
# 导入webdriver模块
from selenium import webdriver
import time
#导入键盘模块
from selenium.webdriver.common.keys import Keys
#打开浏览器
driver = webdriver.Chrome()
#打开工位系统
driver.get("http://192.168.203.112/")
driver.implicitly_wait(10)
h = driver.current_window_handle
print h
driver.find_element_by_xpath("//input[@cl... |
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #对象=属性加方法 属性为静态 方法为动态
>>> class Turtle:#
#属性
color='green'
weight=10
legs=4
>>> class Turtle:#
#属性
color='green'
weight=10
le... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-06-14 08:12
from __future__ import unicode_literals
import django.contrib.auth.models
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('projects', '0004_auto_20190613_... |
import numpy as np
import toynet as tn
def make_network(batch_size=1):
num_classes = 10
img = tn.nn.Input(name='img', shape=(batch_size, 28, 28, 1), dtype='uint8')
label = tn.nn.Input(name='label', shape=(batch_size, num_classes), dtype='uint8')
x = (img - 128.) / 128.
# for layer in [20, 20]:... |
#!/usr/bin/env python
""" This script runs a pre-trained network with the game
visualization turned on.
Specify the network file first, then any other options you want
"""
import subprocess
import sys
import argparse
def run_watch(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argum... |
# -*- coding: utf-8 -*-
__author__ = "Sergey Aganezov"
__email__ = "aganezov(at)cs.jhu.edu"
__status__ = "production"
version = "1.10"
__all__ = ["grimm",
"breakpoint_graph",
"graphviz",
"utils",
"edge",
"genome",
"kbreak",
"multicolor",
... |
import os
graph_model = open(os.path.join(os.path.dirname(__file__),"../../app/assets/graphs/exemplo_afd.txt"), "r").read()
initial_and_final_states: list = [item.strip()
for item in graph_model.splitlines()[0].split(";")]
initial_states: list = [
item for item in initial_and_fi... |
import sqlalchemy
engine = sqlalchemy.create_engine('postgresql://netology:netology1995@localhost:5432/music_site')
connection = engine.connect()
connection.execute("""INSERT INTO performer
VALUES('The Beatles'),
('Eminem'),
('Celine Dion'),
('Tim McMorris'),
(... |
from rest_framework.exceptions import ValidationError
class TypeSystemValidator(object):
def __init__(self, TypeSystemSchemaClass):
self.TypeSystemSchemaClass = TypeSystemSchemaClass
def run_validation(self, data: dict):
instance, errors = self.TypeSystemSchemaClass.validate_or_error(data)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipaySecurityDataAlibabaSecuritydataSendModel(object):
def __init__(self):
self._biz_content_value = None
self._biz_id = None
self._ingest_name = None
self._main_... |
#!/usr/bin/env python3
# From: https://towardsdatascience.com/python-webserver-with-flask-and-raspberry-pi-398423cc6f5d
'''
Raspberry Pi GPIO Status and Control
'''
import Adafruit_BBIO.GPIO as GPIO
from flask import Flask, render_template
app = Flask(__name__)
button = "P9_11"
buttonSts = GPIO.LOW
# Set button as ... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import argparse
import math
def argparser():
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mutations', help = "Path to a mutation dataframe (output of make_mutation_frame.py)")
parser.ad... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-14 11:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
from django.core import serializers
import os
def load_data_currency(apps, schema_editor):
c... |
from pyramid.view import view_config, view_defaults
from pyramid.httpexceptions import HTTPFound
from pyramid.response import Response
from pyramid.renderers import render_to_response
import json
from . import session_validation
from ..models.frigider import Frigider
from ..models.meta import DBSession
@view_config(re... |
"""
1. 校验数据集的合法性
2. 将数据集修改成一列一列的形式
3. 将一些一维的数据转化成二维的形式
"""
import numpy as np
def valid_dataset(data, axis=0):
if ('train' in data) & ('test' in data):
train = data['train']
test = data['test']
[train_flag, train] = valid_data(train, axis)
if train_flag is False:
return... |
import tkinter as tk
from tkinter.filedialog import *
filename = None
def newFile():
global filename
filename = "untitled"
text.delete(0.0, END)
def saveFile():
global filename
document = text.get(0.0, END)
outputFileStream = open(filename, 'w')
outputFileStream.write(document)
o... |
import sys
class EventHandler:
def __init__(self):
pass
def setInputs(self, events, pg):
for e in events:
if e.type == pg.QUIT:
sys.exit()
|
from processors.awards import AwardProcessor,Column,PLAYER_COL
from models.vehicles import PARACHUTE
class Processor(AwardProcessor):
'''
Overview
This processor keeps track of the number of parachutes the player uses.
Implementation
Whenever a vehicle enter event is received involving the parachuti... |
import sys
import time
import random
import signal
import threading
import socket
from struct import *
host = '127.0.0.1' # Hostname
# fileName = sys.argv[1] # File holding configuration info 1) Protocol 2) Window size 3) Timeout 4) MSS
# file_contents = open(fileName, 'r')
protocol = "GBN" # Protocol to be used
win... |
from PySide2.QtWidgets import QApplication, QWidget
from PySide2.QtGui import QPainter, QPen, QBrush, QPolygon
from PySide2.QtCore import Qt, QPoint
import sys
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.setWindowTitle("Pyside2 Simple Application")
self.... |
{
"targets": [
{
"target_name": "native_wrap",
"sources": [ "native_wrap.cpp", "third_party.cpp" ]
}
]
}
|
"""update tableau_emolument
Revision ID: b632e71b4788
Revises: 6529461c9152
Create Date: 2021-12-15 15:48:33.590473
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b632e71b4788'
down_revision = '6529461c9152'
branch_labels = None
depends_on = None
def upgrade... |
def chain_import(chained_path):
"""allows import of a nested module from a package
"""
try:
chain = chained_path.split('.') #attempt on stringlike object first
except AttributeError:
chain = [mod for grp in chained_path for mod in grp.split('.')] #n... |
import time
import logging
from flask import Flask, request
storage = {}
app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
@app.route('/<key>/', methods=['POST', 'GET'])
def relay_payload(key):
try:
if request.method == 'POST':
if key in sto... |
# -*- coding: utf-8 -*-
import os
import re
import core.mining.lsimodel
import core.mining.lsisimilarity
import jieba.posseg
REJECT = re.compile('(('+')|('.join([
u'中文', u'日期', u'汽车',
#u'个人', u'未填写',
#u'财务',
#u'招聘', u'英才网', u'人力',
u'互联网',
])+'))')
def silencer(document):
FLAGS = ['x'... |
# from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Player
class PlayerListView(ListView):
model = Player
class PlayerDetailView(DetailView):
model = Player
|
import sys, os, subprocess, time, json
def clean(*args):
# CONFIG = args[0]
# index = args[1]
print("TM Cleaner is working")
time.sleep(2)
print('Cleaning is done.')
if __name__ == '__main__':
CONFIG, index = sys.argv[1:]
clean(CONFIG, index)
|
# Generated by Django 2.0 on 2018-05-10 16:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0012_remove_question_ans'),
]
operations = [
migrations.RemoveField(
model_name='answer',
name='blog',
),
... |
import flask
from flask import Flask
app = Flask(__name__)
app.url_map.strict_slashes = False # Be forgiving with trailing slashes in URL
GAMES = {}
NUMGAMES = 0
@app.route("/games", methods=['POST'])
def create_game():
r"""
Creates an initialized game of tic tac toe with a unique game_id.
:return: a n... |
# 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... |
from ListNode import ListNode
'''
19. 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
'''
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
... |
from PIL import ImageOps
from PIL import Image
import numpy as np
from PIL import Image
def imageList(path):
addresses = glob.glob(path)
images = []
for path in addresses:
img = Image.open(path).convert('L')
images.append(img)
return images
def vectorizeImg(img):
flatten = np.asmat... |
# -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
from ISR.models import RDN
img = Image.open('car1.jpg')
lr_img = np.array(img)
rdn = RDN(arch_params={'C':6, 'D':20, 'G':64, 'G0':64, 'x':2})
rdn.model.load_weights('weights/sample_weights/rdn-C6-D20-G64-G064-x2/ArtefactCancelling/rdn-C6-D20-G64-G064-x2... |
# checks if httpretrieve raises an timeout exception if the http header isnt sent by the server
# prints failed error msg if httpretrieve fails the test and excutes without printing
# if the test pass's
include httpretrieve.repy
include registerhttpcallback.repy
def server_test_header_timeout(httprequest_diction... |
cube = []
sum_digits = 0
for numbers in range(1, 1000, 2):
cube.append(numbers ** 3)
for numbers in cube:
sum_number = 0
numbers_second = numbers
while numbers_second > 0:
number = numbers_second % 10
sum_number += number
numbers_second = numbers_second // 10
if sum_number % ... |
# Pairs
# Write a function to find all pairs of an integer array whose sum is equal to a given number.
# Example: pair_sum([2,4,3,5,6,-2,4,7,8,9], 7)
# Output: ['2+5', '4+3', '3+4', '-2+9']
my_list = [2,4,3,5,6,-2,4,7,8,9]
def pair_sum(list, num_sum):
output = []
for i in range(len(list)):
for j in r... |
# Colorful 3 Channel image difference
import os
import cv2
import numpy as np
Label_dir = 'S:/UCSD_ped2/Test256/label_dis_removal/'
Result_dir = 'S:/UCSD_ped2/Test256/Unet_Reverse_dis_removal_test/'
Output_dir = 'S:/UCSD_ped2/Test256/Unet_Reverse_dis_removal_test_diff/'
# Label_dir = 'S:/UCSD_ped2/Test256/label/'
# R... |
# -*- coding: utf-8 -*-
"""GEModelClass
Solves an Aiygari model
"""
##############
# 1. imports #
##############
import time
import numpy as np
from numba import njit, prange
# consav
from consav import ModelClass, jit # baseline model class and jit
from consav import linear_interp # linear interpolation
from cons... |
from flask import Blueprint, render_template
playlist = Blueprint('playlist', __name__, template_folder='templates')
@playlist.route('/')
def index():
return render_template('playlist/playlist.html')
|
"""Using Ternary operator or COnditional operator: Identify minimum of two numbers"""
a = 10
b = 20
print(a if a < b else b)
|
import os
import sys
n_files = 250
# Loop over recording units.
for file_id in range(1, 1+n_files):
# Define file path.
job_name = "hecker_formulations_" + str(file_id).zfill(2)
file_name = job_name + ".sbatch"
file_path = os.path.join("sbatch", file_name)
# Open file.
with open(file_path, ... |
from keras import Model, Input
import keras.backend as K
import tensorflow as tf
from keras.initializers import Constant
from keras.layers import Concatenate, LSTM, Dense, Multiply, Flatten, Subtract, Lambda
from src.model.meta_learner.lstm_model import inverse_sigmoid
from src.model.meta_learner.meta_model import Met... |
# WERTSON FURTADO
# COMI-1150-399# ASSIGNMENT
# MIDTERM PROJECT - PART II: MAGIC 8-BALL PROGRAM
# 03/06/19
# PROGRAM TITLE: MAGIC 8-BALL
# PROGRAM DESCRIPTION: A Python program that simulates the magic 8-ball game
# by having the user ask a question and then outputting
# ... |
__author__ = 'bensmith'
lattice = []
for i in range(20):
lattice.append([])
ct = 0
for i in range(20):
for j in range(20):
lattice[i].append(ct)
ct += 1
adj = []
for i in range(400):
adj.append([])
for i in range(20):
for j in range(20):
if j != 19:
adj[lattice[... |
import socket
s=socket.socket()
host=socket.gethostname()
port=12345
s.connect((host,port))
print s.recv(3)
s.close() |
from flask_restful import Resource, marshal_with, reqparse, request, abort
from flask import Response
from models.Pessoa import Pessoa, pessoa_fields
from models.Encoding import Encoding
from common.database import db
import face_recognition
class PessoaResource(Resource):
# GET /pessoas
# GET /pessoas/<pessoa... |
# coding=utf-8
import sys
import ConfigParser
reload(sys)
sys.setdefaultencoding("utf-8")
classroom_para = []
classroom_tmp = []
base_url = ''
cf = ConfigParser.ConfigParser()
# config = ConfigParser.ConfigParser()
# config.read("G:\\05_pypro\\01\\init.conf")
cf.read("/opt/myspace/pro/py_all_pro/02_tmp/01/init.con... |
from .scopes import Scope
class NodeBase(object):
'''
this object redirects getattribute and setattr on descriptors through to the
node context.
'''
def __getattribute__(self, item):
desc = getattr(super().__getattribute__('__class__'), item, None)
if isinstance(desc, property):
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 16:34:03 2018
@author: stanley
"""
from music21 import *
import xlrd
import pyfpgrowth
from collections import Counter
import matplotlib.pyplot as plt
template = {'maj':(0,4,7),
'min':(0,3,7),
'dim':(0,3,6),
'7' :(0,4,7,10),
... |
from pyjob.cexec import cexec
from pyjob.config import PyJobConfig
from pyjob.factory import TaskFactory
from pyjob.script import Script
from pyjob.stopwatch import StopWatch
from pyjob.version import __version__
read_script = Script.read
config = PyJobConfig.from_default()
|
from django.conf.urls import patterns, url, include
from travel.views import *
urlpatterns = patterns('',
url(r'^$', travel_search, name="travel_search"),
url(r'^(?P<station_id>\d+)/$', guide_list, name="guide_list"),
url(r'^(?P<station_id>\d+)/(?P<username>\w+)/$', guide, name="guide"),
url(r'^(?P<st... |
from django.template import Library
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.template.loader import render_to_string
from .. import actions
from ..models import Follow
register = Library()
@register.simple_tag
def is_following(user, obj, ftype):
if ... |
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
from sklearn.externals import joblib
from parsingText import extractor_Y_train
from extract_feature import *
import pickle
import numpy as np
# 数据的加载
X_train = []
fea = Features()
with open(r'./rdata/object_essay_allData_... |
"""
##########################
# WARNING #
##########################
You should not read this or `othello.apps.games.consumers` without first looking at
the file `run_ai_layout.txt' at the root of this repo. It contains the basic
layout for how everything fits together to run a game, which is really ha... |
"""Function to apply a given function recursively to a JSON structure.
fn should either return a replacement value for its argument or return None.
Each part of the structure on which fn returns a non-None value is replaced.
"""
def traverse(data, fn):
r = fn(data)
if r is not None:
return r
t = t... |
import shutil, csv, traceback
from openpyxl import load_workbook
from datetime import datetime
from functools import wraps
rnd_file_name = 'Released plan B1, B2, B3 2018.05.24.xlsx'
output_files_list = 'list.txt'
ss_template_file = 'New Site Solution Template V3.92 Template updated.xlsx'
ss_template_file_dummy = 'Du... |
"""
Make data for qinit by evaluation Okada in the grid cells
determined by grid.data
"""
from __future__ import print_function
from pylab import *
import setfault
fault = setfault.make_fault()
tend = 0.
for s in fault.subfaults:
tend = max(tend, s.rupture_time + 2*s.rise_time)
times = [tend + 10] # after all... |
Hfreq = 200
azm_freq = 50
alt_freq = 50
top_pin = 11
bot_pin = 13
azm_pin = 32
alt_pin = 33
hhspd = 100
hspd = 95
mspd = 85
lspd = 75
azm_center = 7.5
azm_left = 5
azm_right = 10
alt_center = 7.5
alt_up = 2.5
alt_down = 11
class Shot:
def __init__(self, tfreq, bfreq, azmfreq, altfreq, tpin, bpin, azmpin, altp... |
import random
tries = 1
npcNum = random.randint(1, 100)
while True:
guess = input("Guess the number! ")
guess = int(guess)
if guess == npcNum:
print(f"Yup, I picked {npcNum}! You win!")
print(f"It took you {tries} tries.")
break
elif guess < npcNum:
print("Nope, too low... |
# Generated by Django 2.2.5 on 2021-02-14 13:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='order',
name='comments',
fie... |
print("Today's date?")
date = input()
print("Breakfast calories?")
first_number = int(input())
print("Lunch calories?")
seconde_number = int(input())
print("Dinner calories?")
third_number = int(input())
print("Snake calories?")
bedroom_number = int(input())
sum = first_number + seconde_number + third_number + bed... |
#!usr/bin/env python
import kivy
kivy.require('1.0.7')
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kiv... |
n=int(input("Enter No."))
if n%2==0 and n>=2 and n<=5:
print("Not weird")
elif n%2==0 and n>=6 and n<=20:
print("weird")
elif n%2==0 and n>20:
print("most rere")
else:
print("Its an odd") |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from b import b
def a():
print("-----1----")
b()
a() |
# About - Compute Harris Corner Detection
# Updated 09/12/2015
import cv2
import numpy as np
import math as m
import timeit
from scipy import *
from scipy import signal
from scipy.ndimage import filters
from pylab import *
from scipy import ndimage
def ComputeHarrisCorner(sourceImage, kconstan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.