text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class SalePlanInfo(object):
def __init__(self):
self._custom_price_desc = None
self._main_ps_id = None
self._price_desc = None
self._price_type = None
self._ps_i... |
#!/usr/bin/env python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
ringwidth = 3
data = pd.read_csv('thickness.txt',delim_whitespace=True,usecols=(1,2),names=['ring','thickness'])
data['ring'] = data['ring'] * ringwidth
sns.lineplot(x='ring',y='thickness',data=data,er... |
from django.db import models
from django.conf import settings
from django.urls import reverse
import datetime
# Create your models here.
class Order(models.Model):
CATEGORY=(
('COMPUTER','COMPUTER'),
('FURNITURE','FURNITURE'),
('OFFICE_EQUIPMENT','OFFICE EQUIPMENT'),
('LINK_EQUIPMENTS','LINK_EQUIPMENTS'),
... |
#!/usr/bin/env python
import subprocess
from cloudify import ctx
from cloudify.exceptions import NonRecoverableError
import re
@operation
def start(**kwargs):
package_manager = ctx.node.properties['package_manager']
ctx.logger.info('Installing ntp')
install_proc = subprocess.Popen(['sudo', package_manager... |
import requests
import datetime
import time
from collections import namedtuple
from enum import Enum
class Rarity(Enum):
COMMON = 1
UNCOMMON = 2
RARE = 3
VERY_RARE = 4
ULTRA_RARE = 5
class Team(Enum):
MYSTIC=1
VALOR=2
INSTINCT=3
TEAM_NAMES = {
0: 'Uncontested',
1: 'Mystic',
... |
import uuid
from datetime import timedelta
from django.core.exceptions import ValidationError
from django.db import models
from accounts.models import UserModel
from ntnui.utils.send_email import send_email
from django.utils import timezone
from django.utils.translation import gettext as _
class ResetPassword(mode... |
#!/usr/local/bin/python
#-------------------------------------------------------------------------------
# Name: delete_layerInfo
# Purpose:
#
# Author: Gerald Perkins
#
# Created: 19/01/2016
# Copyright: (c) Entiro Systems Ltd. 2016
# Licence: <your licence>
#-------------------------------------... |
import numpy as np
from pampy import match
class Horse:
death_reason = ['996工作', '未知原因', '突发恶疾', '马腿抽筋', '精疲力尽']
death_icon = '\N{skull and crossbones}'
running_icon = '\N{horse}'
@staticmethod
def _limiter(data: float, lower: float, upper: float) -> float:
if data < lower:
ret... |
import base64
from io import BytesIO
from PIL import Image
def convert_and_save(b64_string):
with open("imageToSave.jpg", "wb") as fh:
fh.write(base64.decodebytes(b64_string.encode()))
def save_captured_image(file, image_name):
starter = file.find(',')
image_data = file[starter+1:]
... |
"""The main module for statistics sending package."""
import logging
from argparse import ArgumentParser
from datetime import datetime, timedelta
from json import dump, dumps, load
from os import getenv
try:
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
except ImportEr... |
# -*- coding: utf-8 -*-
import os
from pathlib import Path
import click
import nbformat
from . import __version__
@click.command(name="nbtouch")
@click.version_option(version=__version__)
@click.argument("file", nargs=-1)
@click.pass_context
def touch(ctx, *args, **kwargs):
"""Update the access and modificatio... |
#!/usr/bin/env python3
import os
import subprocess
import sys
import threading
import time
loc = os.path.dirname(os.path.abspath(__file__))
asp_path = os.path.join(loc,'asp')
def handlestderr(inhandle,outfile):
with open(outfile,'w') as outhandle:
for line in inhandle:
print(time.time(),':',l... |
print('This program will check if the two lines typed in are anagrams!\n')
print('Type "help" if you need more information about anagrams,\n\nand "No, thanks" to start!\n')
answer=input()
if(answer=='help'):
print('\nOk, let me tell you about what anagram is.\n')
input()
print('If you say the two lines a... |
# -*- coding: utf-8 -*-
class SynDictionary:
def __init__(self):
self.map = {}
self.load()
def load(self):
"builds reverse index syn_word -> root_word from table root_word: sw1, sw2, ... swN"
t = """POS пос
АД декларация, алкаш
обмен репликация
"""
... |
# Generated by Django 3.2.3 on 2021-06-19 23:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='servicio',
fields=[
('idservicio', models.I... |
# Copyright 2021 Tampere University and VTT Technical Research Centre of Finland
# This software was developed as a part of the ProCemPlus project: https://www.senecc.fi/projects/procemplus
# This source code is licensed under the MIT license. See LICENSE in the repository root directory.
# Author(s): Amir Safdarian <a... |
"""Utility functions for interacting with the Relay service"""
from __future__ import annotations
import asyncio
import base64
import dataclasses
import datetime
import functools
import inspect
import json
import signal
import weakref
from typing import (Any, Awaitable, Callable, Iterable, Mapping, Optional,
... |
import pytest
from sack import sackint
def test_gcd():
assert sackint.gcd(0, 0) == 0
assert sackint.gcd(0, 1) == 1
assert sackint.gcd(1, 0) == 1
assert sackint.gcd(1, 2) == 1
assert sackint.gcd(4, 5) == 1
assert sackint.gcd(4, 6) == 2
assert sackint.gcd(1296,1728) == 432
assert sackin... |
import pandas as ps
import json
def readFiles():
player_details = ps.read_csv(filepath_or_buffer='D:/Semester1/VisualAnalytics/Project/indian-premier-league-csv-dataset/Player.csv',sep=',')
return player_details
def getDetails(player_details,player_id):
detailshash = {}
detailshash['name'] = player_d... |
from django.apps import AppConfig
class MydbDataLayerConfig(AppConfig):
name = 'mydb_data_layer'
|
from flask import render_template, Blueprint, jsonify
pages = Blueprint('pages', __name__)
@pages.route('/', methods=['GET'])
def pre_ship():
try:
return render_template('index.html')
except:
return jsonify(**{'message': 'Unexpected Error'}), ErrorCode_ServerError |
# import os
class Foo:
def __init__(self, bar, ):
self.bar = bar
self.baz = baz
def main():
foo = Foo('qux', 1)
someFunction('Matt')
def someFunction(name):
print('Hello, ' + name)
if __name__ == "__main__":
main()
|
"""
1012. 数字分类 (20)
时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue
给定一系列正整数,请按要求对数字进行分类,并输出以下5个数字:
A1 = 能被5整除的数字中所有偶数的和;
A2 = 将被5除后余1的数字按给出顺序进行交错求和,即计算n1-n2+n3-n4...;
A3 = 被5除后余2的数字的个数;
A4 = 被5除后余3的数字的平均数,精确到小数点后1位;
A5 = 被5除后余4的数字中最大数字。
输入格式:
每个输入包含1个测试用例。每个测试用例先给出一个不超过1000的正整数N,随后给出N个不超过1000的待分类的正整... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class DatadigitalFincloudGeneralsaasFaceVerificationInitializeResponse(AlipayResponse):
def __init__(self):
super(DatadigitalFincloudGeneralsaasFaceVerificationInitializeResponse, ... |
from django.db import models
from django.core.validators import URLValidator
from redactor.fields import RedactorField
# Create your models here.
class Linea_de_servicio(models.Model):
nombre = models.CharField(max_length=80)
imagen = models.ImageField(upload_to='uploads', default='imagen/default.png')
imagen_inte... |
from dsg.Configuration import Configuration, FilterType
import numpy as np
from typing import List, Tuple
generator = np.random.default_rng()
def coefficient(z: np.ndarray, refractive_indices: np.ndarray, wavelength) -> float:
k_air = refractive_indices[0] * 2.0 * np.pi / wavelength
k_2 = k_air
m = np.i... |
import sys
import os
import hashlib
import json
import time
init_time = time.clock()
try:
fd = open('output.json', 'w')
except Exception as E:
print 'generic exception raised'
print str(E)
def hash_md5(file):
m = hashlib.md5()
try:
fd = open(file, 'rb').read()
except Exception as E:
... |
import tensorflow as tf
def generator(z, feature_depth, hidden_sizes=[128, 256, 256]):
h = z
for i, hidden_size in enumerate(hidden_sizes):
h = tf.layers.dense(
inputs=h,
units=hidden_size,
activation=tf.nn.leaky_relu,
name="dense_%i" % i
)
g... |
import cv2
import time
from threading import *
class BuildinCamera(Thread):
def __init__(self):
Thread.__init__(self)
self.camera = None
self.conf = None
self.stream = None
self.consumer = None
self.log = None
self.plugins = []
self.socket = None
self.setfname = None
self.state = 'init'
self.... |
#!/usr/bin/env python
# coding: utf-8
# In[142]:
import numpy as np
import os
import pandas as pd
import time
from datetime import datetime
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import linear_model
import statsmodels.api as sm
import scipy.stats as stats
get_ipython().run_line_mag... |
import sys
import math
a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])
delta = (b*b) - 4*a*c
if(delta == 0):
x1 = -b/2*a
print("1")
print(format(x1))
elif(delta > 0):
x1 = (-b + math.sqrt(delta))/2*a
x2 = (-b - math.sqrt(delta))/2*a
print("2")
print(format(x1) + " " + form... |
# Generated by Django 2.1.7 on 2019-03-12 14:55
import ckeditor.fields
import django.core.files.storage
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blog', '0014_auto_20190312_1707'),
]
operations = [
... |
# Exercicio 18
print("Verificação de uma data")
dia = int(input("Digite o dia no formato dd: "))
mes = int(input("Digite o mês no formato mm: "))
ano = int(input("Digite o dia no formato aaaa: "))
validacao = False
if mes == 1 or mes == 3 or mes == 5 or mes == 7 or mes == 8 or mes == 10 or mes == 12:
if 31 >= di... |
# encoding:utf-8
import xlrd
class GetRowAndColNumber():
def getRowAndColNumber(self,excel_path,sheet_name,key):
"""该函数的作用:通过参数sheet_name和key,去返回一个该key所在行号和列号的列表"""
row_col_list=[]
data=xlrd.open_workbook(excel_path)
table=data.sheet_by_name(sheet_name)
rows=table.nrows
... |
import math
x = float('nan')
math.isnan(x)
True
f = open("lista.txt", "r")
l = []
for x in f:
s = x.split(" ")
if(len(s)>1):
a =''
for k in s:
a+= k.strip() + " "
l.append(a+"\n")
""" for x in f:
s = x.split(" ")
#print(s)
if(len(s)>1):
for el in range(le... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes for making multiple regex replacements."""
import sys
import regex as re
__author__ = 'Victoria Morris'
__license__ = 'MIT License'
__version__ = '1.0.0'
__status__ = '4 - Beta Development'
class MultiRegex(object):
simple = False
r... |
class Student(object):
def __init__(self):
self.name = 'xiaozhi'
def __getattr__(self, attr):
if attr=='score':
return 95
stu = Student()
print((stu.name))
print((stu.score))
|
import pymysql
def get_connection():
conn = pymysql.connect(host='127.0.0.1', user='root', password='1234', db='flaskdb1', charset='utf8')
return conn
# 동물 정보 저장하는 함수
def add_animal_info(animal_type, animal_name, animal_age, animal_weight):
conn = get_connection()
sql = '''
insert into a... |
# Generated by Django 3.2 on 2021-04-15 16:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0003_car'),
]
operations = [
migrations.CreateModel(
name='Members',
fields=[
('id', models.Bi... |
weight = float(input("How much do you weigh?"))
Mercury = weight * 0.38
Venus = weight * 0.91
Mars = weight * 0.39
Jupiter = weight * 2.34
Saturn = weight * 1.06
Uranus = weight * 0.92
Pluto = weight *0.06
print(f"On Earth, you weigh {weight}. On other planets, you would weigh..."
, "\n Mercury: ",Mercury, "\n Venus... |
from __future__ import print_function
import sys
import os
import shelve
import datetime
import time
import bs4
nir_stations_url = "http://www.journeycheck.com/nirailways/route?from=GVA&to=CLA&action=search&savedRoute="
nir_departures_url_template = "http://www.journeycheck.com/nirailways/route?from=%(src)s&to=%(dst... |
import proj1_helpers as utils
import numpy as np
import algorithms as ML_alg
import preprocessing_functions as prf
from joblib import Parallel, delayed
def main():
(y, x, event_ids) = utils.load_csv_data("../data/train.csv")
x_nan_to_mean = prf.put_nan_to_mean(x, y)
y_bin = prf.pass_data_to_zero_one(y).r... |
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
import tkinter as tk
from PIL import Image
def onclick(event):
if event.xdata != None and event.ydata != None :
print(event.xdata, event.ydata)
def clickfun(img):
im=Image.open(img)
ax = plt.gca()
fig = plt.gcf()
implot = ax.imshow... |
a=list(input().split(" "))
c=0
m=0
for i in a:
for k in range(1+c,len(a)):
t=int(i)&int(a[k])
if t>m :
m=t
c=c+1
print(m) |
def Healt_calc(age, apples, cig):
health = (100-age) + apples*2 - (cig*2.8)
print(health)
Healt_calc(22,5,7)
venkat_data = [22,5,7]
Healt_calc(venkat_data[0],venkat_data[1],venkat_data[2])
Healt_calc(*venkat_data) # UNPACKING ARGUMENT |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cloned from https://github.com/YieldNull/freeproxy.git
"""
from gevent import monkey
monkey.patch_socket()
import gevent
import re
import requests
import random
from time import time, sleep, localtime, strftime
from gevent.pool import Pool
from util.spider.freeproxy... |
#-*-coding:utf-8*-
from lxml import etree
import sys
import pytz
import datetime
#评论页解析json数据
class reviews_analysis():
def process(self,text,url):
tz = pytz.timezone('Asia/Shanghai')
last_update_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
if text == '' or text == 'None'... |
import os
from flask import Flask, redirect, url_for, request, render_template, jsonify
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient(os.environ['DB_PORT_27017_TCP_ADDR'], 27017)
db = client.telemetrydb
@app.route('/api/v1.0/telemetry', methods=['GET'])
def get_all_telemetry():
tele... |
from .models import Resource
from django import forms
class NewResourceForm(forms.ModelForm):
class Meta:
model = Resource
fields = ['title', 'description', 'cost', 'subject', 'pdf_file']
class UpdateResourceForm(forms.ModelForm):
class Meta:
model = Resource
fields = ['title', 'description', 'cost'] |
# ua = "Mozilla%252F5.0%2B%28iPhone%253B%2BCPU%2BiPhone%2BOS%2B12_2%2Blike%2BMac%2BOS%2BX%29%2BAppleWebKit%252F605.1.15%2B%28KHTML%2C%2Blike%2BGecko%29%2BVersion%252F13.0%2BMobile%252F15E148%2BSafari%252F604.1"
# browser(url = "test", ua = ua)
import asyncio
import pyppeteer
import random
import time
import json
imp... |
# https://www.hackerrank.com/challenges/s10-standard-deviation/problem
"""
Objective
In this challenge, we practice calculating standard deviation.
Task
Given an array, X, of N integers, calculate and print the standard deviation. Your answer should be in decimal form, rounded to a scale of 1 decimal place.
An error ... |
import collections
from typing import Tuple
import jwt
from django.conf import settings
from rest_framework import status, serializers
from rest_framework.views import APIView
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_fram... |
# Jeopardy!
# Ranges $100
print("Ranges $100")
for i in range(4):
print(i)
# Ranges $200
print("Ranges $200")
for j in range(0,4):
print(j)
# Ranges $300
print("Ranges $300")
for ji in range(1,3):
print(ji)
# Ranges $400
print("Ranges $400")
for var in range(2,3):
print(var)
# Ranges $500
print("Ranges ... |
#!/usr/bin/env python3
from tkinter import *
from tkinter import filedialog
from bs4 import BeautifulSoup
import requests
import re
from fpdf import FPDF
from PIL import Image
# HTML link to save images from
html_link = "https://manganelo.com/chapter/ranma_12/chapter_1"
# Select where to save images
# root = Tk()
#... |
#!/usr/bin/env python
# --!-- coding: utf8 --!--
import re
import noteflow.functions as F
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class TagCollector(QObject):
tagsChanged = pyqtSignal()
def __init__(self):
QObject.__init__(self)
self._tags = []
def addTag(self... |
# -*- coding: utf-8 -*-
# coding = utf-8
import datetime
from django.contrib import admin
from django.db.models.aggregates import Sum
from django.utils.translation import ugettext_lazy as _
from basedata.models import ExtraParam
from common import generic
from selfhelp.models import WorkOrder, WOExtraValue, WOItem, ... |
# Generated by Django 2.1.7 on 2019-04-01 18:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hubble', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='subtitle',
fiel... |
"""This script contains code for the Goverment class and it's inherited properties
"""
import logging
from src.eda.parent import Parent
import streamlit as st
import pickle
import pandas as pd
from src.helper import create_logger
from src.eda.graphs import Graph
logger = create_logger('process', 'logs/Government.log'... |
from google.appengine.ext import db
class StoryModeStats(db.Model):
"""Models a story mode stats entity with a device ID, nickname, score and a timestamp"""
deviceID = db.StringProperty(required=True)
nickname = db.StringProperty(required=True)
score = db.IntegerProperty(required = True)
timestamp = db.StringPr... |
# Generated by Django 2.1.7 on 2019-05-10 09:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0043_auto_20190424_1029'),
]
operations = [
migrations.RemoveField(
model_name='statetransition',
name='stat... |
def is_pair(sym1, sym2):
if sym1 == "(" and sym2 == ")":
return True
if sym1 == "{" and sym2 == "}":
return True
if sym1 == "[" and sym2 == "]":
return True
return False
def check(string):
if string == "":
return "yes"
stack = []
for char in string:
... |
#! /usr/bin/python2.7
import requests
def getTaskSize():
data = requests.get('https://trouble.physics.byu.edu/api/tasks').json()
ids = [x['id'] for x in data]
return len(ids)
print(getTaskSize())
|
from rest_framework import serializers
from board import models
from .item_serializers import CommentAuthorSerializer
class GroupSerializer(serializers.ModelSerializer):
members = CommentAuthorSerializer(many=True, read_only=True, required=False)
class Meta:
model = models.Group
fields = ['me... |
from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
class Todo(db.Model):
id = db.Column(db.Integer,primary_key = True)
... |
"""
(C) Copyright 2018-2023 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import time
from ior_test_base import IorTestBase
from telemetry_test_base import TestWithTelemetry
# Pretty print constant
RESULT_OK = "[\033[32m OK\033[0m]"
RESULT_NOK = "[\033[31mNOK\033[0m]"
# It should take as m... |
#!/usr/bin/env python
# coding: utf-8
# In[45]:
#sol_1
n = int(input())
if n > 30:
print("n must be less than 30")
print("try again")
else:
for i in range(1, n+1):
if i % 10 == 3 or i % 10 == 6 or i % 10 == 9:
print("X", end = " ")
else:
print(i, end = " ")
# In... |
#Q4
#Valor inicial: R$ 10000
#Rendimento por período (%): 0.54
#Aporte a cada período: R$ 1000
#Total de períodos: 120
import matplotlib.pyplot as plt
valor_inicial = float(input("Valor de Investimento Inicial R$ "))
rendimento_periodo = float(input("Taxa de Juros % "))
aporte = float(input("Valor Mensal R$ "))
mês =... |
# Generated by Django 3.0.7 on 2020-07-28 04:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('discussions', '0032_auto_20200727_1243'),
]
operations = [
migrations.AddField(
model_name='groupmember',
name='adde... |
from flask import Flask, make_response, request, render_template
app = Flask(__name__)
@app.route('/00-test')
def test_views():
return "这是测试的地址"
@app.route('/01-setcookie')
def setcookie():
# 通过make_response构建响应对象
resp = make_response('保存cookies成功')
#1.保存名称为uname值为Maria的cookie,存期为1年
resp.set_cook... |
class Tree:
def __init__(self, key, data):
"Create a new Tree object with empty L & R subtrees."
self.key = key
self.data = data
self.left = self.right = None
def insert(self, key, data):
"Insert a new element into the tree in the correct position."
if key < self.... |
import streamlit as st
import numpy as np
from skimage.io import imread
from skimage.transform import resize
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import numpy as np
import pickle
st.title('TOMATO DISEASE PREDICTION AND PREVENTION APP')
st.write('This is a toma... |
# -*- coding: utf-8 -*-
# @Time : 2021/9/6 8:21
# @File : ninwen.py
# @Author : Rocky C@www.30daydo.com
# 宁稳网
import json
import os
import random
import time
from parsel import Selector
import requests
import warnings
import datetime
import re
import pandas as pd
import validate_key
import pickle
import loguru
warnin... |
__author__ = 'arkilic'
import numpy as np
def import_image():
pass
def convert_to_npArray():
pass |
#coding:utf-8
from scripts.handler import dbhandler
from scripts.utils.views import *
# data type
DT_Pay = 1
DT_ConsumeGold = 2
DT_DailyActive = 3
DT_CsmGoldByAct = 4
DT_DailyCreate = 5
DT_VipLevel = 6
DT_Subsistence = 7
DT_ItemSol... |
import logging
from functools import wraps
from .utils import redirect_to_terms, is_eligible_to_redirect
logger = logging.getLogger(__name__)
def terms_checker(view_func):
@wraps(view_func)
def _wrapped_view(view, request, *args, **kwargs):
if is_eligible_to_redirect(request):
return re... |
import random
# Soldier
class Soldier:
def __init__(self, health, strength):
self.health = health
self.strength = strength
def attack(self):
return self.strength
def receiveDamage(self, the_damage):
self.health = self.health - the_damage
# Viking
class Viking(Sol... |
from django.db.models import Q
from django.forms.widgets import SelectMultiple, CheckboxSelectMultiple
import django_filters
from mptt.forms import TreeNodeChoiceField, TreeNodeMultipleChoiceField
from .models import Framework
#TODO: Move this somewhere else (forms)
class FrameworkFilter(django_filters.FilterSet):
... |
import torch
import oscillation
def get_pde_res(h_val: torch.Tensor, input: torch.Tensor, device=oscillation.DEVICE):
ones = torch.unsqueeze(torch.ones(len(input), dtype=oscillation.DTYPE, device=device), 1)
predicted_h_d = torch.autograd.grad(
h_val,
input,
create_graph=True,
... |
from flask import Blueprint, Response, request
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from database.users import User
from flask_bcrypt import generate_password_hash, check_password_hash
import datetime
import json
user_blueprint = Blueprint('users', __name__)
@user_bluepri... |
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
#initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
rawCapture = PiRGBArray(camera)
#allow camera to warmup
time.sleep(0.1)
#grab an image from camera
camera.capture(rawCapture, format = ... |
"""Module only used for the follow part of the script"""
from .actions import Actions
from .time_util import sleep
from selenium.webdriver.common.keys import Keys
def follow_from_recommended(browser, amount):
"""Follows given amount of users from the who to follow list"""
followed = 0
last_length = 0
#Click ... |
import mmcv
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import normal_init, bias_init_with_prob, ConvModule,constant_init
from mmdet.core import multi_apply, bbox2roi, matrix_nms
from ..builder import HEADS, build_loss, build_head
from scipy import ndimage
import pdb
import matplotl... |
import json as json_mod
import os
import sys
import click
from leapp.tool.utils import find_project_basedir, load_all_from, get_project_name
from leapp.models import get_models
from leapp.actors import get_actors, get_actor_metadata
from leapp.channels import get_channels
def is_local(base_dir, cls):
return os.... |
class Solution:
def replaceDigits(self, s: str) -> str:
result = ''
even_char = ''
for index, value in enumerate(s):
if index % 2 == 0:
even_char = value
result += value
else:
# Unicode のコードポイントを進める
resu... |
from dolfin import *
from block import block_mat, block_vec, block_transpose
from block.iterative import MinRes
from block.algebraic.petsc import AMG
import rigid_motions
# Optimization options for the form compiler
parameters["form_compiler"]["cpp_optimize"] = True
parameters["form_compiler"]["representation"] = "ufl... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 5 18:28:30 2019
@author: Theo
"""
from sklearn.decomposition import PCA
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
tracks = pd.read_csv('dataframe.csv',sep=',',encoding='latin1')
tracks_numerical=tracks.drop(['Artist',... |
import re
grid_of_lights = []
for i in range(1000):
new = []
for j in range(1000):
new.append(False)
grid_of_lights.append(new)
def turn_on(x1, y1, x2, y2):
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
grid_of_lights[x][y] = True
def turn_off(x1, y1, x2, y2):
... |
from __future__ import print_function
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sys
from sklearn.model_selection import train_test_split
from sklearn import linear_model, ensemble, metrics, gaussian_process
from dataClean import *
from sklearn.svm import SVC
from sklearn import metri... |
# Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк.
seconds = int(input("Введите время в секундах "))
hour = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds = int((seconds % 3600) % 60)
time = f"{hour:0... |
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
# With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
# Looping Through a String
# ... |
from django import template
register = template.Library()
def include_js(context,jsname,path='assets/studytribe/js/'):
return {'jsname':jsname,
'STATIC_URL':context['STATIC_URL'],
'debug':('debug' in context),
'path':path}
def include_css(context,cssname,path='assets/studytrib... |
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.views.generic.base import TemplateView
urlpatterns = [
path('', views.homepageView, name="homepage"),
path('login/', views.loginView, name="l... |
import os
os.system("echo hello")
os.system("echo $HOME")
os.system("echo Before $MY_TEST")
os.environ['MY_TEST'] = 'qqrq'
os.system("echo After $MY_TEST")
|
"""Restaurant rating lister."""
def ratings_dict(filename):
restaurant_ratings = open(filename,"r")
ratings_dict = {}
for line in restaurant_ratings:
name, rating = line.rstrip().split(":")
ratings_dict[name] = rating
sorted_keys = sorted(ratings_dict.keys())
# for key in sorted_keys:
# print("{} is... |
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
return self.plusOneHelper(digits)
def plusOneHelper(self, digits):
result = list(digits)
last_number = result[-1]
if last_number < 9:
... |
from django.shortcuts import render
from .models import Listing
def index(request):
return render(request , 'listings/listings.html')
|
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
import os
client = commands.Bot(command_prefix = '?')
@client.event
async def on_ready():
print("BitBot is up and ready")
await client.change_presence(activity=discord.Game(name='With Yo Girl'))
@client.event
asy... |
import logging
import os
import tempfile
import tarfile
import shutil
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
from pytorch_pretrained_bert.modeling import BertModel, BertPredictionHeadTransform, BertConfig, \
BertLayerNorm, PRETRAINED_MODEL_ARCHIVE_MAP, BERT_CONFIG_NAME,... |
# version 0.82 seconds on n = 100
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 15 13:55:39 2017
@author: sdorai000
"""
#### ACTIVE EDIT ####
import sys
import time
result_count = 0
stairs = []
input_list = []
result_list = []
def answer(n):
found_count = 0
remaining_stairs = 0
... |
"""
## Sequence naming on the scanner console
Sequence names on the scanner must follow this specification to avoid manual
conversion/handling:
[PREFIX:][WIP ]<seqtype[-label]>[_ses-<SESID>][_task-<TASKID>][_acq-<ACQLABEL>][_run-<RUNID>][_dir-<DIR>][<more BIDS>][__<custom>]
where
[PREFIX:] - leading capital le... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.