text stringlengths 8 6.05M |
|---|
class Check_negative_positve:
def __init__(self):
x = input("input number")
try:
self.x = float(x)
except ValueError:
print("input is not a number")
Check_negative_positve()
def Check(self):
if self.x < 0:
print("this is a negativ... |
"""
This script reads power through the wire of a 220v AC sine signal
This script can be called in console for debug purpose
If called by an external software (eg Chaudiere app), the entry point is api_get_watt_values()
Hardware interface
SCT-013-030-30A-1V-ac-current-sensor is connected to ADS1115
ADS1115 isconnecte... |
# -*- coding: utf-8 -*-
import json
import re
import datetime
import jsonpickle
"""
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
if isinstance(obj, datetime.date):
return obj.isoformat()
... |
#! python3
# downloadXKCD.py - Downloads EVERY single XKCD comic!
import requests, os, bs4
comicUrl = ''
url = 'https://xkcd.com' # Starting url
os.makedirs('xkcd', exist_ok=True) #Store comics in ./xkcd/comics
while not url.endswith('#'):
# Download the page
print('Downloading page %s...' % url)
res = req... |
import cv
from PyQt4 import QtCore
class CameraDevice(QtCore.QObject):
_DEFAULT_FPS = 30
newFrame = QtCore.pyqtSignal(cv.iplimage)
def __init__(self, cameraId=0, mirrored=False, parent=None):
super(CameraDevice, self).__init__(parent)
self.mirrored = mirrored
self._came... |
from flask import Flask
from flask import request
import inputParsing.equationParse as rpn
app = Flask(__name__)
@app.route("/")
def main():
return rpn.rpnToString(rpn.shuntingYardAlgorithm('( ( 15 / ( 7 - ( 1 + 1 ) ) ) * 3 ) - ( 2.4 + ( 1 + 1 ) )'))
@app.route("/api/infixNotation")
def infix():
if 'q' no... |
import smartpy as sp
class Transaction(sp.Contract):
def __init__(self):
self.init(
origin = sp.address('tz1'),
destiny = sp.address('tz2'),
amount = sp.tez(0),
immutability = sp.bool(False)
)
@sp.entry_point
def transaction(self, params... |
class Solution:
# https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2511/Intuitive-Python-O(log-(m+n))-solution-by-kth-smallest-in-the-two-sorted-arrays-252ms
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype:... |
import ntdll
import kernel32
api_defs = {}
api_defs.update(ntdll.api_defs)
api_defs.update(kernel32.api_defs)
def getImportApi(impname):
impname = impname.lower()
return api_defs.get(impname)
|
import secrets
secretsgen = secrets.SystemRandom()
print("Generating 6 digits random OTP ")
otp = secretsgen.randrange(100000,999999)
print("Secure random One-Time-Password(OTP) ", otp) |
#
# @author: ChrisMCodes
#
# purpose: mostly just a general webscraper
# (with a few fun features after the scrape)
# Users can export scraped data to txt
# or CSV after scraping.
#
# fun fact: my IDE doesn't seem to recognize the shebang *facepalm*
#!/usr/bin/env python3
# change python3 to python in the shebang abo... |
from rest_framework import serializers
from accounts.models import User
from manager.models import certPage
class AIinfoSerialilzer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(
help_text='유저',
queryset=User.objects.all()
)
time = serializers.DateTime... |
import pandas as pd
from sklearn import preprocessing
from preprocessing import read, split, non_numerical_features, one_hot_encoding
from preprocessing import drop_features, deal_with_23 , deal_with_58
from postprocessing import writeoutput
from csv import DictReader, DictWriter
from sklearn.feature_selection import ... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 25 09:09:38 2019
@author: Vall
"""
import iv_utilities_module as ivu
import iv_save_module as ivs
import numpy as np
import os
# Parameters
home = r'C:\Users\Valeria\OneDrive\Labo 6 y 7'
path = os.path.join(home, r'Muestras\SEM\LIGO5bis\1')
series = 'LIGO5bis_1'
# Load... |
###################################
# INTALLS : - passlib #
###################################
from passlib.hash import pbkdf2_sha512
inf = "$pbkdf2-sha512$95846$"
def hash_password(password):
try:
hashed_password = pbkdf2_sha512.using(salt_size=16, rounds=95846).hash(password)
print... |
import pandas as pd
import pyterrier as pt
import unittest
import os
from .base import BaseTestCase
class TestUtils(BaseTestCase):
def test_parse_trec_topics_file(self):
input = os.path.dirname(os.path.realpath(__file__)) + "/fixtures/topics.trec"
exp_result = pd.DataFrame([["1", "light"], ["2", ... |
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
import os
import sys
from setuptools import setup
INFO_PLIST_TEMPLATE = '''\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist v... |
from console_progressbar import ProgressBar
from nltk import word_tokenize, pos_tag
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
class StemTokenizer(object):
counter = 0
def __init__(self, num_docs=None):
self.num_docs = num_docs
self.pb = ProgressBar(
... |
import os #system함수를 사용하기 위한 모듈
#C언어 배우신 분들은 #include<> => header파일과 유사
num = 0
while True: #무한반복문 : 조건식이 거짓말이 안되는 반복문
print("""
====메뉴====
1.정수 입력
2.입력된 정수 출력
3.종료""")
select = int(input("메뉴 선택 : "))
if select == 1:
num = int(input("정수 입력 : "))
elif select == 2:
... |
n = int(input('Digite um número: '))
div = 0
for c in range(1, n+1):
if n % c == 0:
div += 1
print('\033[0;33m', c, '\033[m', end='')
else:
print('\033[0;31m', c, '\033[m', end='')
print(f"""\nO número {n} foi divisível {div} veze(s)
E por isso ele """, end='')
if div == 2:
print('É... |
# Generated by Django 3.1.5 on 2021-03-02 13:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('JOB', '0009_jobapplied'),
]
operations = [
migrations.AddField(
model_name='reqruiteruser',
name='email',
... |
import requests, random, logging
from kkbox_line_bot import app
from kkbox_line_bot.nlp import olami
from kkbox_line_bot.nlp.error import NlpServiceError
from linebot import LineBotApi, WebhookHandler
from linebot.models import MessageEvent, TextMessage, TextSendMessage, ImageMessage, ImageSendMessage, VideoMessage, ... |
#!/usr/bin/env python
import base64
import datetime
import json
# import os
import requests
import shutil
import numpy as np
import pandas as pd
import xarray as xr
import sys
import os
# %%
fildir = '/sand/usgs/users/ssuttles/wind/'
def fetch_api_data(params):
s = requests.Session()
r = s.get('https://da... |
"""Sample AWS Lambda function for remembering a favorite color."""
from alexa import AlexaSkill, AlexaResponse, intent_callback
class Color(AlexaSkill):
card_title = "Favorite Color"
def _get_welcome(self):
reprompt_text = ("Please tell me your favorite color by saying, "
"... |
#!/usr/bin/env python
from latex_meta_lib import metacls_objlib
class SingleSentence():
''' single figure class'''
def __init__(self,tag=None):
self.tag = tag # variable name
self.text = ''
self.filepath = None # value
self.format = None # description
class Para... |
import os
import sys
import warnings
import pytest
import aospy
def test_tutorial_notebook():
pytest.importorskip('nbformat')
pytest.importorskip('nbconvert')
pytest.importorskip('matplotlib')
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
rootdir = os.path.join(ao... |
import logging
import json
import awacs.cloudwatch
import awacs.sns
import awacs.sts
import awacs.ssm
import awacs.ec2
import awacs.autoscaling
from awacs.aws import Allow, Policy, Principal, Statement
from runway.cfngin.blueprints.base import Blueprint as CFNGinBlueprint
from runway.cfngin.blueprints.variables.types i... |
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'sse_extensions',
'type': 'executable',
'msvs_settings': {
'VCCLCompilerTool': {
'EnableE... |
# -*- coding: utf-8 -*-
'''
@author : smh2208
@software: PyCharm
@file : adminx.py
@time : 2018/7/21 17:35
@desc :
'''
import xadmin
from .models import EmailVerifyRecord,Banner
#不再集成admin,而是object
class EmailVerifyRecordAdmin(object):
list_display = ['code', 'email', 'send_type', 'send_time']
search... |
default_app_config = 'colossus.apps.lists.apps.MailingConfig'
|
#!/usr/bin/python3
"""Square module"""
class Square:
"""Represents a square."""
def __init__(self, size=0):
"""Initializes the square.
Args:
size (int): Size to create the square, defautls to 0.
Attributes:
__size (int): Private, size of the square.
... |
#!/usr/bin/python3
lazy_matrix_mul = __import__('101-lazy_matrix_mul').lazy_matrix_mul
print(lazy_matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]]))
print(lazy_matrix_mul([[1, 2, 3], [3, 4, 5]], [[1, 2], [3, 4], [5, 6]]))
print(lazy_matrix_mul([[1, 2]], [[3, 4], [5, 6]]))
print(lazy_matrix_mul([[True, 2]], [[3, 4], [5, 9... |
from models import About_us, History, Facts, QnA
import xadmin
xadmin.autodiscover()
xadmin.site.register(About_us)
xadmin.site.register(History)
xadmin.site.register(Facts)
xadmin.site.register(QnA)
|
from words import sort_words_case_insensitively
def test_sort_words_case_insensitively():
words = ("It's almost Holidays and PyBites wishes You a "
"Merry Christmas and a Happy 2019").split()
actual = sort_words_case_insensitively(words)
expected = ['a', 'a', 'almost', 'and', 'and', 'C... |
def get_array(input_array):
splitter_arr = input_array.split(' ')
reversed_list = []
get_rev_bk_list = []
for word in splitter_arr:
print(word[::-1])
reversed_list.append(word[::-1])
reversed_list = sorted(reversed_list, key=lambda x: x[0])
for rev_word in reversed_list:
... |
import datetime
import json
import requests
from rest_framework.authtoken.models import Token
from .constants import SERVICE_CHOICES
from .models import Editor, Category, Author, Book
from .constants import local_api_service, google_api_service, get_google_book, get_oreilly_book, oreilly_api_service, local_save_book
... |
# -*- coding: utf-8 -*-
#title(),(全部字首大寫)
#capitalize(),(第一個字首大宿)
"""
upper():將字串轉成大寫,并返回一個拷貝
lower() :將字串轉成小写,并返回一個拷貝
capitalize() :將字串首字母大寫,并返回一個拷貝
title() :將每个單字的首字母大写,并返回一個拷貝
isupper() :判斷一個字串是否是大寫
islower() :判斷一個字串是否是小寫
"""
a=input()
print(a.upper())
print(a.capitalize()) |
import mglearn
import numpy as np
import pandas as pd
import sklearn
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib
import mglearn
from sklearn.datasets import load_boston
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
boston =... |
from .ttmltosrt import convert_file, srt_generator
__version__ = '1.3.0'
__all__ = ['convert_file', 'srt_generator']
|
# see http://www.unicode.org/reports/tr15/#Canon_Compat_Equivalence
import unicodedata
def nfkc(word):
return [unicodedata.normalize("NFKC", word)]
|
from django.db import migrations, models
"""
Hi! I made this because I can't stop making the same mistake: Never use a third-party ID as foreign
key, because every change will be painful. I am fixing this mistake here: We're going to walk over
all tables that reference osmcal_user.osm_id and replace this with a serial... |
#ENG II 26/04/21
def area_circuferencia(raio):
"""calcula a area de uma circuferencia"""
area = 3.14 * (raio * raio)
return area
def perimetro_circuferencia(raio):
"""Calcula o perimetro de uma circuferencia"""
perimetro = 2 * 3.14 * raio
return perimetro
def area_retangulo():
... |
# -*- coding: utf-8 -*-
__author__ = 'lish'
import time,datetime
import urllib2,cookielib,socket
import urllib,random
import re,json,os
import sys,time
import requests,MySQLdb
import crawlLWS as lws
import dealLWSdb as lwsdb
from multiprocessing.dummy import Pool as ThreadPool
import sys
reload(sys)
sys.setdefaultencod... |
# Generated by Django 2.2.7 on 2020-01-01 08:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0009_auto_20191212_1904'),
]
operations = [
migrations.AddField(
model_name='user',
name='initial',
... |
import tkinter as tk
from text import get_text
from tqdm import tqdm
from tag_LFM import RLTMF
class mix_re():
def __init__(self, window):
self.data = []
self.users = set()
self.items = set()
self.flag = True
self.read_data('ratings.dat')
self.load_model(... |
import numpy as np
import os,sys
from sklearn import linear_model
from sklearn import neighbors
from sklearn import svm
from sklearn import preprocessing
from sklearn.model_selection import StratifiedShuffleSplit, GridSearchCV
import tensorflow as tf
from tensorflow import keras
from helpers import *
from plots impo... |
#!/usr/bin/env python
import sys
import requests
import json
import logging
import argparse
import datetime
from boto.utils import get_instance_identity
from lockfile import FileLock
if sys.version_info < (2, 6):
if __name__ == "__main__":
sys.exit("Error: we need python >= 2.6.")
else:
raise ... |
# -*- coding: utf-8 -*-
# Operações Aritméticas
#subtração
print(11-2)
#resultado: 9
#soma
print(5+2)
#resultado: 7
#divisão
print(10/2)
#resultado: 5.0
#multiplicação
print(2*3)
#resultado: 6
#pegar apenas a parte inteira da divisão
print(10//9) #1.111111 o Python pega apenas a parte inteira ou seja 1.
#resultado:... |
def solution(sizes):
sizes = [sorted(size) for size in sizes]
return max(sizes, key = lambda x: x[0])[0] * max(sizes, key = lambda x: x[1])[1] |
#!/usr/bin/env python3
#test_makeBigWig.py
#*
#* --------------------------------------------------------------------------
#* Licensed under MIT (https://git.biohpc.swmed.edu/gudmap_rbk/rna-seq/-/blob/14a1c222e53f59391d96a2a2e1fd4995474c0d15/LICENSE)
#* -----------------------------------------------------------------... |
from datetime import datetime, timedelta
dfr = datetime.now() - timedelta(days=1)
print (dfr)
if datetime.now() > dfr:
print (True)
|
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
cache = {}
for i in range(len(numbers)):
if target - numbers[i] in cache:
return [cache[target - numbers... |
import numpy as np
import time
import random
from find_ball import FindBall
from KF import KF
if __name__ == "__main__":
fb = FindBall()
# kf = KF(mu0 = np.zeros((6,1)), sigma0 = 0.1 * np.eye(6),
# C = np.hstack((np.eye(3), np.zeros((3, 3)))), Q = 0.1 * np.eye(6),
# R = 0.1 * np.eye(6)... |
# Generated by Django 2.0.5 on 2018-06-03 15:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('calculation', '0010_auto_20180603_1526'),
]
operations = [
migrations.AddField(
model_name='map... |
import dash_bootstrap_components as dbc
button_group = dbc.ButtonGroup(
[
dbc.Button("Left", color="danger"),
dbc.Button("Middle", color="warning"),
dbc.Button("Right", color="success"),
]
)
|
'''
Facial analysis
2. face ++
a. locate the user by face groupping
b. identify user has partner, has child or not
1). parse all image captions to capture keyword
i). #mygirdfriend, #myboyfriend, #myhusband, #mywife, #mychildreb etc.
2). person repeatedly appear in the user's timeline => has partene... |
# -*- coding: utf-8 -*-
'''
博客1:python+opencv实现基于傅里叶变换的旋转文本校正
https://blog.csdn.net/qq_36387683/article/details/80530709
博客2:OpenCV—python 图像矫正(基于傅里叶变换—基于透视变换)
https://blog.csdn.net/wsp_1138886114/article/details/83374333
傅里叶相关知识:
https://blog.csdn.net/on2way/article/details/46981825
频率:对于图像来说就是指图像颜色值的梯度,即灰度级的变化速度
幅... |
# Print tempearture.
import requests
try:
location = input('Enter a city name: ')
address = 'https://api.openweathermap.org/data/2.5/weather?q=' + location + '&units=metric&appid=60113b36f0a83502fe59ba9e512b76d4'
data = requests.get(address)
temp = eval(data.text)
print('Temperature of ' + location + ' is ' + str(... |
# -*- coding: utf-8 -*-
"""Copy in and out (CPIO) archive format files."""
import os
from dtformats import data_format
from dtformats import data_range
from dtformats import errors
class CPIOArchiveFileEntry(data_range.DataRange):
"""CPIO archive file entry.
Attributes:
data_offset (int): offset of the dat... |
"""model database
Revision ID: 62fba533f72b
Revises: 6eaf085a217c
Create Date: 2020-10-17 08:32:25.493485
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '62fba533f72b'
down_revision = '6eaf085a217c'
branch_labels = None
depends_on = None
def upgrade():
#... |
#!/usr/bin/env python
'''
Entities folder importer.
'''
__author__ = 'Aditya Viswanathan'
__email__ = 'aditya@adityaviswanathan.com'
from entities.db import db as Db
from entities.models import *
from entities.action_executor import ActionExecutor
from entities.test_entities import make_entities
|
#!/usr/bin/python3
"""
Project: 0x0A-python-inheritance.
Task: 4
"""
def inherits_from(obj, a_class):
"""True if it is, False otherwise"""
if not type(obj) is a_class and issubclass(type(obj), a_class):
return True
return False
|
from coco.models import Image, Category, Coco50
from django.shortcuts import render
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponse, HttpResponseRedirect
import urllib2
import json
import os
from... |
from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired
class RegisterForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()]... |
# coding=utf-8
import os
import sys
import unittest
from time import sleep
from selenium import webdriver
sys.path.append(os.environ.get('PY_DEV_HOME'))
from webTest_pro.common.initData import init
from webTest_pro.common.model.baseActionAdd import user_login
from webTest_pro.common.model.baseUploadFile import add_U... |
import torch
import torch.fx
from torch import nn, Tensor
from torch.nn.modules.utils import _pair
from torchvision.extension import _assert_has_ops
from ..utils import _log_api_usage_once
from ._utils import check_roi_boxes_shape, convert_boxes_to_roi_format
@torch.fx.wrap
def ps_roi_pool(
input: Tensor,
bo... |
# Copyright (c) 2019 Certis CISCO Security Pte Ltd
# All rights reserved.
#
# This software is the confidential and proprietary information of
# Certis CISCO Security Pte Ltd. ("Confidential Information").
# You shall not disclose such Confidential Information and shall use
# it only in accordance with the terms of the... |
n = int(input())
i = 1
sum_series = 0
while i <= n:
sum_series += 1 / i ** 2
i += 1
print(sum_series)
|
def new_save(name) :
s_file = open("save.txt","w")
#Name, Floor, State
s_file.write(name + "#0#0")
s_file.close()
def load_save() :
s_file = open("save.txt","r")
save_data = s_file.read()
#Stats read and split into list for use
stats = save_data.split("#")
s_file.close()
return s... |
import boto3
from botocore.exceptions import ClientError
import time
import sys
bucket_name = sys.argv[1]
prefix = sys.argv[2]
start = time.time()
print('Baseline prep started...')
# Creating a copy of validation set for baseline
s3 = boto3.resource('s3')
bucket_key_prefix = prefix + "/data/val/"
bucket = s3.Bucke... |
"""
CCT 建模优化代码
局部坐标系
作者:赵润晓
日期:2021年4月27日
"""
from os import error, path
import sys
sys.path.append(path.dirname(path.abspath(path.dirname(__file__))))
from cctpy import *
# 为了便于磁场建模、粒子跟踪、束流分析,cctpy 中引入了全局坐标系和局部坐标系的概念
# 各种磁铁都放置在局部坐标系中,而粒子在全局坐标系中运动,为了求磁铁在粒子位置产生的磁场,需要引入局部坐标的概念和坐标变换。
# 局部坐标系有4个参数:原点、x轴方向、y轴方向、z轴方向。注意x... |
import random
import string
import pandas as pd
import uuid
import os
import git
import urllib.request
import json
from faker import Faker
fake = Faker('es_MX')
# nombres y apellidos
hombres = pd.read_csv('./corpus/hombres.csv')
hombres = hombres.values
mujeres = pd.read_csv('./corpus/mujeres.csv')
mujeres = mujeres... |
import os
import sys
current_path = sys.argv[1]
key_word = sys.argv[2]
def search(path, keyword):
dirs = os.listdir(path)
for d in dirs:
abs_path = os.path.abspath(d)
if os.path.isfile(d):
if(abs_path.find(keyword) > 0):
print abs_path
else:
... |
import sys
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker
import seaborn as sns
import conic_parameters
plotfile = sys.argv[0].replace('.py', '.pdf')
sns.set_style('white')
fig, axes = plt.subplots(3, 3, figsize=(9, 9), sharex=True, sharey=True)
incs_deg = 10.0*np.arange(9)
nbeta =... |
#!/usr/bin/env python
import boto3
from botocore.client import Config
import csv
from dateutil.parser import parse
import datetime
import os
from collections import OrderedDict
ordered_fieldnames = OrderedDict([('CreationDate', None),('SnapshotId',None),('SnapshotVolumeSize',None),('SnapshotTags',None)])
ec2 = boto3.... |
import string
from words import choose_word
from images import IMAGES
'''
Important instruction
* function and variable name snake_case -> is_prime
* contant variable upper case PI
'''
def is_word_guessed(secret_word, letters_guessed):
'''
secret_word: word guess by the user
letters_guessed: list hold all ... |
"""
Miscellaneous utilities
"""
import sys
from ..exceptions import GMTOSError, GMTCLibError
def clib_extension(os_name=None):
"""
Return the extension for the shared library for the current OS.
.. warning::
Currently only works for OSX and Linux.
Returns
-------
os_name : str or N... |
import pandas as pd
import csv
roster = pd.read_csv('FIFA17final.csv',encoding = 'utf8')
# roster.describe()
print(roster[1:10]) |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
try:
from django.http import JsonResponse
except ImportError:
from django.http import HttpResponse
def JsonResponse(response_data, *args, **kwargs):
return HttpResponse(json.dumps(response_data), *args, content_type='applic... |
"""
参考链接:
https://blog.csdn.net/HuangZhang_123/article/details/80660688
"""
import numpy as np
import cv2
from matplotlib import pyplot as plt
def orb_match(img1, img2):
orb = cv2.ORB_create(nfeatures=50)
kp1, des1 = orb.detectAndCompute(img1,None)
kp2, des2 = orb.detectAndCompute(img2,None)
# 暴力匹配B... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
a = raw_input()
nums = map(int, raw_input().split())
uniq = {}
map(uniq.__setitem__, nums, [])
print sorted(uniq.keys(), reverse=True)[1]
|
import datetime
from ..extensions.database import database as db
from ..extensions.marshmallow import marsh
class Revision(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
submission_id = db.Column(db.Integer, db.ForeignKey(
'submission.id'), nullable=False)
create_by = d... |
# -*- coding: utf-8 -*-
class Solution:
def transformArray(self, arr):
modified = True
current = arr[:]
while modified:
modified = False
previous = current[:]
for i in range(1, len(previous) - 1):
if previous[i - 1] < previous[i] and prev... |
projectPath = 'C:/Users/Peter/Documents/maya/projects/auto_rigging' |
import calendar
from django.db import models
class Department(models.Model):
name = models.CharField(max_length=1000)
shortname = models.CharField(max_length=5)
def __str__(self):
return self.name + ' - ' + self.shortname
# def get_default_department():
# return Department.objects.get_or_c... |
#!/usr/bin/env python
from __future__ import print_function
import fastjet as fj
import fjcontrib
import fjext
import tqdm
import argparse
import os
import numpy as np
from pyjetty.mputils import *
from heppy.pythiautils import configuration as pyconf
import pythia8
import pythiafjext
import pythiaext
import ROOT... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that device and simulator bundles are built correctly.
"""
import plistlib
import TestGyp
import os
import struct
import subpr... |
import Game as G
if __name__ == '__main__':
FirstMove = 'MAX'
min_max_depth = 10
board_dimension = 5
g = G.Game(board_dimension, FirstMove, min_max_depth) #inizializzo gioco
g.min_max_alfa_beta()
|
import pygame
from pygame.locals import *
from pygame.color import THECOLORS
import math
from sys import exit
import DigiMap
import Digimon
def config_window():
pygame.init()
screen_x = 600 + 200
screen_y = 600
screen = pygame.display.set_mode((screen_x, screen_y), 0, 32)
pygame.display.set_captio... |
from django.conf import settings
from dotenv import load_dotenv
import requests
import os
load_dotenv(verbose=True)
### getCoordinates
# Input: adress object
# Input Format: { 'Street_Address': '', 'City' : '', 'State' : '', 'Zip code' : ''}
# Output: lat and lng of given address
# Output Format: {'lat': '', 'lng': ... |
from django.conf.urls.defaults import patterns, include, url
import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include('blog.urls')),
... |
import unittest
import sbol3
import labop
import uml
from labop.execution_engine import ExecutionEngine
from labop_convert import MarkdownSpecialization
from labop_convert.behavior_specialization import DefaultBehaviorSpecialization
class TestSubprotocols(unittest.TestCase):
def test_subexecutions(self):
... |
def next_pal(val):
while True:
val+=1
nxt = str(val)
if nxt == nxt[::-1]:
return int(nxt)
'''
There were and still are many problem in CW about palindrome numbers and palindrome
strings. We suposse that you know which kind of numbers they are. If not, you may
search about them... |
import model_eval.eval_batch
|
name = input("enter your name: ")
lst = ['a','e','i','o','u']
#using lambda
print(len(list(filter(lambda x:x in lst,name))))
print(list(filter(lambda x:x in lst,name)))
#using for
c=0
for n in name:
if n in lst:
c+=1
print(c)
|
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'news', views.NewsVeiwSet)
|
'''
go列为多个GO,分号间隔;每个都需要查询得到term
gene_swiss_GO.id
'''
input_file1 = open("gene_swiss_GO.id")
input_file2 = open("go_term_class.tab")
out_file = open("gene_GOterm.out","w")
id_term_dict = {}
for line in input_file2:
line = line.strip()
GO_id = line.split("\t")[0]
GO_term = line.split("\t")[1]
id_term_d... |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from image_util import show_image
from util import y_indicator, classification_rate
from util import pca_find_n_components, pca_transform
from logistic import Logistic
def get_data(nrows=None):... |
from datetime import datetime
import json
try:
# avataan tiedosto
file_handle = open("guestbook.json", "r")
# haetaan tiedoston sisältö
content = file_handle.read()
# suljetaan tiedosto
file_handle.close()
messages = json.loads(content)
read_or_write = str(input("Haluatko lukea vai ki... |
error_infos = {
'not_found':{'status':404,'message':'not found','data':''},
'forbidden':{'status':403,'message':'forbidden','data':''},
'gateway_timeout':{'status':504,'message':'gateway timeout','data':''},
'internal_server_error':{'status':500,'message':'internal server error','data':''}
}
rpc_infos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.