text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
def encrypt(x):
a = x >> 32
a ^= 0xffc2bdec
a += 0xffc2bdec
a &= 0xffffffff
b = x & 0xffffffff
b ^= 0xffc2bdec
b += 0xffc2bdec
b &= 0xffffffff
c = ((b << 32) | a)&0xffffffffffffffff
d = ((c & 0x7f) << 57)&0xffffffffffffffff
return ((c >> 7) | d) & 0x... |
from collections import defaultdict
infile = "input"
is_contained_by = defaultdict(set)
def parse(s):
if "no other" in s:
return
a =s.replace(" bags contain ", ",").replace(" bags.", "").replace(" bag.", "").replace(" bags", ",").replace(" bag", ",").replace(".", "").replace(", ", ",").replace(",,", "... |
import tkinter as tk
from restaurants import RestaurantList, RestaurantMenu
class Start(tk.Frame):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
self.pack()
self.makeWidgets()
def makeWidgets(self):
self.title = tk.Label(self, text="Get In My Belly", font=("Helv... |
from flask import Flask, render_template, Response
import cv2
import get_ip
import threading
import numpy as np
import time
import sys
from logger import logger
class VideoCamera(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
# 通过opencv获取实时视频流
self.video = cv2.VideoC... |
'''
Aluna: Polyana Bezerra da Costa
Essa classe representa o Dataset do sistema, que guarda informações sobre o nome do banco de imagens, a descrição e URL
do mesmo (se houver) e o caminho onde as imagens que fazem parte do dataset estão armazenadas. Essa classe também guarda
todas as anotações que foram salvas, bem c... |
"""
802. Sudoku Solver
https://www.lintcode.com/problem/sudoku-solver/description
"""
class Solution:
"""
@param board: the sudoku puzzle
@return: nothing
"""
def solveSudoku(self, board):
# write your code here
self.dfs(0, board)
def dfs(self, index, board):
if index ==... |
guestBook = "guestBook.txt"
with open(guestBook, "a") as file_object:
file_object.write(f"Book of people invited:")
while True:
guestName = input("You're invited to the party! Insert you name please (\"quit\" to quit): ")
if guestName.lower() != "quit":
file_object.write(f"\n\t{gue... |
from __future__ import unicode_literals, print_function
from django import forms
from django.test import TestCase
from django_auxilium.forms.range import RangeSelector
class RangeSelector_Test(TestCase):
"""
Test the rangeconfig selector validation
"""
@classmethod
def setUpClass(cls):
cl... |
#!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with... |
from django.contrib import admin
from django.urls import path
import wordcount.views
import blog.views
import myapp.views
urlpatterns = [
path('admin/', admin.site.urls),
path('', wordcount.views.home, name="home"),
path('about/', wordcount.views.about, name="about"),
path('result/', wordcount.views.r... |
from django import forms
from .models import Accounts
class AccountsForm(forms.ModelForm):
class Meta:
model = Accounts
fields =['email','title','display','category','owner','address','number','desc','imageone'] |
import pytest
@pytest.fixture(autouse=True)#将open方法自动应用到所有的案例中
def open():
print("打开浏览器")
def test_search1():
print("test_search1")
raise NameError
pass
def test_search2():
print("test_search2")
pass
def test_search3():
print("test_search3")
pass
if __name__ == '__main__':
pytes... |
# -*- coding: utf-8 -*-
import base64
from odoo import api, fields, models, tools, modules
class Recipe(models.Model):
_name = 'jecuisine.recipe'
_description = 'Model for recipe app'
name = fields.Char(string='Nom de la recette', required=True)
description = fields.Text(string='Description')
# ... |
import random
class Board:
"""A designated playing surface. The responsibility of Board is to keep track of the pieces in play.
Stereotype:
Information Holder
Attributes:
_piles (list): The number of piles of stones.
"""
def __init__(self):
"""The class constructor.
... |
#!/usr/bin/env python
import socket,sys, errno
class PulseGenerator81160A:
def __init__(self, ip, port=5025, BUFFER_SIZE = 1024):
self.BUFFER_SIZE = BUFFER_SIZE
self.name= "Agilent"
self.ip=ip
self.port=port
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREA... |
input = open("input", "r")
inputLines = input.readlines()
input.close()
def doOperation(num1, num2, operator):
if operator == "*":
return num1 * num2
if operator == "+":
return num1 + num2
print ("Invalid Operator: " + operator)
return 0
def evaluateExpression(expr):
runningTot... |
#!/usr/bin/env python3
# coding: utf-8
# Author:Laure Berti-Equille
import warnings
import time
import numpy as np
import pandas as pd
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.simplefilter('ignore', category=ImportWarning)
warnings.simplefilter('ignore', category=DeprecationWarning)
class ... |
#!/usr/bin/env python3
import argparse
import datetime
import glob
import logging
import multiprocessing
import os
import os.path
import queue
import re
import subprocess
import sys
import shutil
import threading
import time
LOG_FORMAT="[{levelname}] {message}"
log = logging.getLogger()
PIN_LOG = 'pin.log'
class Log... |
import pandas as pd
import numpy as np
from sklearn.metrics import f1_score
from sklearn.model_selection import KFold, StratifiedKFold
from code.util.base_util import timer
import os
from code import base_data_process
import tensorflow as tf
from code.util import base_util
log = base_util.get_logger()
ID_COLUMN_NAME... |
#!/usr/bin/python3
"""A module for evaluting 2d arrays"""
def island_perimeter(grid):
"""A simple function that counts border tiles in a 0, 1 matrix"""
if not grid:
return 0
perim = 0
for x in range(len(grid)):
for y in range(len(grid[x])):
if grid[x][y] is 1:
... |
import pytest
from invoke import Exit
from rellu.version import Version
def test_version():
for release in ('1.0', '10.9.2017'):
for preview in (None, 'a1', 'b2', 'rc3'):
version = release + (preview or '')
v = Version(version)
assert v.version == version
... |
from app import app
import sqlite3
import os
if not os.path.exists('urls.db'):
conn = sqlite3.connect("urls.db")
c = conn.cursor()
c.execute("""CREATE TABLE if not exists urls
(id integer primary key, normal_url text,
alias text unique, timestamp text, ip text)""")
c... |
# Generated by Django 3.0.2 on 2020-05-10 18:12
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('orders', '0004_auto_2020... |
#!/bin/python3
# https://www.hackerrank.com/test/61sq9qfa63d/questions/472ni48r5qi
import math
import os
import random
import re
import sys
# Complete the getMinimumCost function below.
# if things are 7
# 1 2 3 5 7 9
# first we can sort the list
# so we can do someting like this
# alternate the sides or rota... |
from pulp import *
from math import *
from numpy import *
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
# this is the circle partition plot code for algorithm 8.1
# initialize the constant for this algorithm
alpha = 2
b1 = 1
b2 = 0.5
rho = 1
epsilon = 0.2
# initialize the nod... |
x = 5
y = 10
print(x+y) #Toplar sonucu verir.
a = "5"
b = "10"
print(x+y) # Birleştirir.
c = 5.3 #Float değeri
d = 2
print(c*d)
print(type(c*d)) # İşlem sonucunun tipini verir.
e = 5
f = 2
g = e/f
print(g) #Sonuç float değer verir.
print(type(g))
|
# Generated by Django 3.0.3 on 2020-03-02 15:26
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0002_auto_20200227_0638'),
]
operations = [
migrations.RenameField(
model_name='card',... |
# System Dependencies
import os
# External Dependencies
import minerl
path = input("Path to download dataset (default 'git_root/raw_data/'):")
path = path.strip()
if not path:
git_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")
path = os.path.join(git_path, 'raw_data')
if not os.pa... |
import pandas as pd
import numpy as np
import random
import sys
##메뉴
#길이
length=['15cm','30cm','15센치','30센치','15센티','30센티']
#샌드위치
sandwich=['페퍼로니 피자썹', '이탈리안 비엠티', '에그마요', '스테이크 치즈',
'써브웨이 클럽','로티세리 바비큐 치킨','햄', '참치', '미트볼',
'풀드 포그 바비큐','치킨 데리야끼', '스파이시 이탈리안','쉬림프'
,'베지', '터키','비엘티','페퍼 ... |
s, d, m, w = str(), dict(), 0, str()
with open("dataset_3378_3.txt", "r", encoding='utf-8') as file:
s = file.read().lower().strip().split()
print(s)
s.sort()
print(type(s))
print(s)
for word in s:
if word in d:
d[word] += 1
else:
d[word] = 1
for word in d:
if d[word] > m:
... |
from django.db import models
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
phone_num = models.CharField(max_length=14, verbose_name='手机号')
|
# adapted from ODE function implementation: https://github.com/rtqichen/ffjord
import torch
import torch.nn as nn
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, x):
shape = torch.prod(torch.tensor(x.shape[1:])).item()
return x.view(-1,... |
#!/usr/bin/python
import sys
def compute(prey, otherHunter, dist):
temp0 = prey[0] - dist
temp1 = max( dist , otherHunter[0] )
temp1 = temp1 - temp1
if otherHunter[1] != 0:
temp0 = otherHunter[1] / otherHunter[1]
else:
temp0 = otherHunter[1]
temp1 = max( prey[0] , otherHunter[1] )
temp2 = -1 * dist
temp0 =... |
__author__ = 'Tomer'
import common
import numpy as np
import BilexiconUtil as BU
import pyximport
pyximport.install(setup_args={'include_dirs':[np.get_include()]})
from cyMatching import cy_ApproxMatch, cy_min_submatrix, cy_min_submatrix2, cy_getGraphMinDist
import munkres # https://github.com/jfrelinger/cython-munkr... |
#!/usr/bin/env python3
#Python_05 question 5
alpaca_all= open ("../alpaca_all_genes.tsv", "r")
alpaca_pigm= open ("../alpaca_pigmentation_genes.tsv", "r")
alpaca_sc= open ("../alpaca_stemcellproliferation_genes.tsv", "r")
all= alpaca_all.read().split('\n')[1:]
all_set = set(all)
#print(all_set)
pigm= alpaca_pigm.re... |
import simpy as sim
import numpy as np
import math
from typing import Union
import matplotlib.pyplot as plt
# Global variables
T_GUARD = 60
P_DELAY = 0.1
U_DELAY = 500
U_TURNAROUND = 45*60
SIM_TIME = 1*24*60*60 # simulate for 1 day
inter_arrivals = []
time_inter_arrival = []
landing_queue = []
time_landing_queu... |
#!python2
# Tui Popenoe
# challenge120E.py - Log Throughput Counter
def log_throughput_counter(log):
def main():
if __name__ == '__main__':
main() |
#!/usr/bin/python
# coding=utf-8
import httplib
import json
import urllib
import xml.etree.ElementTree as etree
FIRST_BACKEND = {"host": "bus62.ru", "url": "/tomsk/php/%s.php"}
SECOND_BACKEND = {"host": "83.222.106.126", "url": "/bus/common/map6/%s.php"}
def _send_request(backend, method, params=None):
if not pa... |
# Convolutional Neural Network
# Part 1 - Building the CNN
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initialising the CNN
c... |
#!/usr/bin/env python3
import math
from typing import List, Tuple
import numpy as np
from util import load, as_int
def arrival_after(time: int, bus: int) -> int:
after = ((earliest // bus) + 1) * bus
return after - earliest
def part1(busses: List[int]):
print('--- Part 1 ---')
found_time = earlies... |
from flask import Flask, request, jsonify
from flask_socketio import SocketIO
from flask_cors import CORS, cross_origin
from Modules import crypt
from Modules.DeviceService import SaveDeviceData, get_last_temperature, SendToDevice, get_last_valve
app = Flask(__name__)
CORS(app = app)
key = crypt.Crpyt(text = 'proj... |
import pika
import time
import json
import sys
from configobj import ConfigObj
import logging
import ast
class RabbitQueue():
def __init__(self, path_config):
self.name_queue = None
self.exchange = None
self.config = ConfigObj(path_config)
amqp_url = 'amqp://%s:%s@%s:%s/%s' % (
... |
import os
import sys
def get_current_dir():
return os.path.dirname(os.path.abspath(__file__))
#src_path = os.path.join(get_parent_dir(1),'2_Training','src')
utils_path = os.path.join(get_current_dir(),'Utils')
src_path = os.path.join(get_current_dir(),'src')
sys.path.append(src_path)
sys.path.append(utils_path)... |
lis = [1,2,4]
d = {'name': 'Max','age' : 20}
#print(d.items())
for k,v in d.items():
print (k,v) |
from flask_marshmallow import Marshmallow
ma = Marshmallow()
#Esquema de producto
class ProductoSchema(ma.Schema):
class Meta:
fields = ('id','name','amount')
producto_schema = ProductoSchema()
productos_schema = ProductoSchema(many=True) |
from __future__ import division
import sys
if sys.version_info > (3,0):
import builtins
else:
import __builtin__ as builtins
try:
import dill
HAS_DILL = True
except:
HAS_DILL = False
import pickle as dill
import os
from astropy.io import fits
from astropy.table import Table
from astropy.tests.he... |
#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
from db import session_scope
from models import FeedVote
class FeedVoteProvider(object):
@staticmethod
def vote_is_exist(fid, uid):
with session_scope() as session:
count = session.query(FeedVote).filter(FeedVote.fid == fid, FeedVote.uid == ui... |
#共有n个台阶,每次只能上1个台阶或者2个台阶,共有多少种方法爬完台阶。
#共有n页书,每次只能翻1页或者2页书,共有多少种方法翻完全书。
#当n不大于2时,只有两种方法
#可以理解为当翻到n-2书页或走到n-2楼梯 时,只有两种方法n=1 or n=2
#类推可得 斐波那契数列
#实现代码
def A(n):
if n == 1 :
return 1
if n == 2 :
return 2
if n > 2:
return A(n-1)+A(n-2)
print(A(10))
#ps:1.使用了递归
# 2.时间复杂度为指数级
# 3.斐波那契数列指... |
def recursive_punc_find(full_doc, row_index, char_index, sentence, direction, recurslevel):
for i in full_doc[row_index][::direction][char_index:]:
sentence.append(i)
if i == '.':
#print(i)
return sentence[::direction]
#print(sentence)
if recurslevel < 2:
ret... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 22 13:49:18 2018
@author: PeterLee
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn import tree
#from sklearn.tree import DecisionTreeRegressor
#from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import AdaBoostClassifier
import scik... |
import re
def remove_emoji(string):
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
... |
#!/usr/bin/env python
import struct
import numpy
from optparse import OptionParser
import sys
op = OptionParser()
op.add_option("-l", dest="size", type="int", default=1024)
op.add_option("-s", dest="step", type="float", default=0.1)
op.add_option("-n", dest="noise_level", type="float", default=10.0)
op.add_option("-o"... |
from linebot import LineBotApi
from linebot.models import TextSendMessage
import time
lineBotApi = LineBotApi('MgXDbs7VLmkhQ/7KJsP9280yct33lfXYylQs3wKKZHKkZ3BYjvgSZd1axKmTR1Ir6hIx0CnpFyO4j9KeoZ8zZDMEiapuNgkusME3gd0GrmANajlO2C/dCqVK870fnOUB08AamQUn9N5WBxaJIJtKlwdB04t89/1O/w1cDnyilFU=')
def addingTimestamp(text):
t... |
# Задание 6-1
# **************************************************************************************
from time import sleep
class TrafficLight:
__color = ['Красный', 'Желтый', 'Зеленый']
def running(self):
i = 0
while i < 3:
print(f'Светофор переключается \n '
... |
from flask import Flask, render_template, request, flash, redirect
from flask_heroku import Heroku
from forms import SubmitForm
import sqlite3
app = Flask(__name__)
app.config.from_object("config.Test")
# app.config.from_object("config.Production")
heroku = Heroku(app)
def helper_submit_score(username, score):
''... |
# Copyright 2015 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... |
import logging
from pathlib import Path
from typing import Any
import tabula
from django.conf import settings
from django.core.management import BaseCommand
from django.db import transaction
from associations.models import Association
from base import http, logic, parsing
from base.middleware import env
from base.mod... |
import cv2
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import os
def truncate_2(x):
neg = ((x + 2) + abs(x + 2)) / 2 - 2
return -(-neg + 2 + abs(- neg + 2)) / 2 + 2
def NoiseMap(image):
q = [4.0, 12.0, 2.0]
filter1 = [[0, 0, 0, 0, 0],
[0, -1, ... |
from bert_api import SegmentedInstance
from alignment import MatrixScorerIF
from typing import List
import numpy as np
from alignment.data_structure.matrix_scorer_if import ContributionSummary
class EnsembleScorer(MatrixScorerIF):
def __init__(self, solver_list: List[MatrixScorerIF], weight_list: List[float] = N... |
from django.db import models
from organizations.models import Organization
from projects.models import Project
class RACI(models.Model):
name = models.CharField(max_length=50, null=True)
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
project = models.ForeignKey(Project, null=True... |
def zig_zag_traversal(root):
out=[]
direction=True
temp=[]
if not root:
return out
curr=[root,None]
while curr:
node= curr.pop(0)
if node:
if direction:
temp.append(node.val)
else:
temp=[node.val]+temp
else:
out.append(temp)
temp=[]
if len(curr)>0:
curr.append(None)
direction... |
# coding: utf-8
from . import __version__
DEFAULT_EXT_README = 'ext/readme.md'
DEFAULT_LIB_README = 'lib/readme.md'
DEFAULT_REQUIREMENTS_TXT = 'requirements.txt'
DEFAULT_REQUIREMENTS_JSON = DEFAULT_REQUIREMENTS_TXT[:-4] + '.json'
def main(args=None):
import argparse
parser = argparse.ArgumentParser('mvt', de... |
# 02_print.py
# 此示例示意标准输出函数print的用法
print(1, 2, 3, 4) # 1 2 3 4
print('===以下是给定sep="#"的打印方式')
print(1, 2, 3, 4, sep="#") # 1#2#3#4
print('以下关键字参数end="\n\n\n\n\n"来换五行新行')
print(1, 2, 3, 4, end="\n\n\n\n\n") # 换5行
print(6789, end="") # 不换行
print("我是程序的最后一句")
|
# main.py
# 5/29/19
# Xiaoyu Yan (xy97)
# Monitors the communications b/w the Feather's UART and
# Wattnode's RS-485 by keeping a thread for each.
# Initializes the Wattnode meter with meter settings.
# Logs any errors resulting in crashes.
import meter_func
import threading
import time
import sys
import subprocess
i... |
PARTITION_MOUNTPOINT = lambda partition: f"/media/dts/{partition}"
DISK_DEVICE = lambda device, partition_id: f"{device}p{partition_id}"
FILE_PLACEHOLDER_SIGNATURE = "DT_DUCKIETOWN_PLACEHOLDER_"
TMP_WORKDIR = "/tmp/duckietown/dts/disk_image"
DISK_IMAGE_STATS_LOCATION = "data/stats/disk_image/build.json"
DATA_STORAGE_DI... |
import unittest
import FizzBuzz
class FizzBuzzTestCases(unittest.TestCase):
def test1(self):
for x in range(1, 101):
self.assertEqual(type(FizzBuzz.FizzBuzz(x)),str)
def test2(self):
for x in range(1, 101):
if x%3 == 0 and x%5 != 0:
se... |
'''VGG11/13/16/19 in Pytorch.'''
import torch
import torch.nn as nn
from torch.nn import Parameter
cfg = {
'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG16': [64, 64, 'M', 128, 128, 'M', 25... |
'''
This files just prints out all the 52cards in deck as list of tuples.
for (a,b) in the list, a represents the card type and b represents the cardvalue (1 to 10).
Value for ace is set to A, a value of 1 or 11 can be assigned later.
'''
suitlist = ['♣','♦','♥','♠']
jkq = ['J','K','Q']
numrange = list(range(2,11))
c... |
""" Get Files from AWS S3 """
import os
import random
import string
import boto3
from botocore.exceptions import ClientError
class S3File:
""" Description : Used for S3 file Operations"""
def get_boto_session(self, access_key=None, secret_key=None):
""" Parameteres : s3 bucket details captured from ... |
import socket
from threading import Thread
import logging
from traitlets import Unicode
from textwrap import dedent
from jupyterhub.spawner import Spawner
from mesos_spawner.scheduler import JupyterHubScheduler
class MesosSpawner(Spawner):
_scheduler = None
_scheduler_thread = None
_count = None
mes... |
import plotly.graph_objects as go # or plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
df = pd.read_csv('play.csv')
opts = [{'label' : 'TEST', 'value' : 'TEST'}]
graphs={}
for i in df['PlaylistNam... |
dici1 = {'chave1': 10, 'chave2': 20, 'chave3': 30}
dici2 = {'chave4': 40, 'chave5': 50, 'chave6': 60}
#for i in dici2:
# dici1[i] = dici2[i]
dici1.update(dici2)
print(dici1)
dici3 = {i: '9' + str(dici1[i]) for i in dici1}
print(dici3)
dici3 = {i: 9 + dici1[i] for i in dici1}
print(dici3)
|
from django.db import models
# Create your models here.
class State(models.Model):
statesname=models.CharField(max_length=100)
# district=models.CharField(max_length=100)
def __str__(self):
return str(self.statesname)
|
from django.db import models
from list import constants
# Create your models here.
class TaskModel(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(max_length=400,null=True,blank=True)
completion_date = models.DateTimeField()
priority = models.CharField(max_length=1... |
#-*- coding:utf-8 -*-
"""
Created on Wed May 8 17:19:38 2019
@author: loktarjason
"""
import requests as rqs #导入requests包
import numpy as np
from lxml import etree #wandoujia用lxml爬取较为方便
import time,csv,random,re
with open('wandoujiat.csv','w',newline='',encoding='utf-8-sig') as f: #open函数记得加上encoding='utf-8'
... |
# 곱하기 혹은 더하기
# 나눗셈 등의 더 다양한 연산이 있을 때 일반적인 해법이 되는 내 풀이
# O(2^N)
def search(digit, num = 0, i = 0):
ret = num
if i == len(digit):
return ret
ret = max( ret, search(digit, num + digit[i], i + 1) )
ret = max( ret, search(digit, num * digit[i], i + 1) )
return ret
num_str = '02984'
# 576... |
#------------------------------------------------------------------------------#
#--------------------------------plot_angles.py--------------------------------#
#------------------------------------------------------------------------------#
#--------------------------Created by Nick DeFilippis------------------------... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.select_room, name='select_room'),
url(r'^frontdesk/$', views.frontdesk, name='frontdesk'),
url(r'^concierge/$', views.concierge, name='concierge'),
url(r'^activitiesdesk/$', views.activitiesdesk, name='activiti... |
# Generated by Django 2.1.7 on 2019-07-07 18:44
import bpp.models.cache
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
replaces = [('bpp', '0165_cache_punktacja_autora_cache_punktacja_dyscypliny'), ('bpp', '0166_auto_20190702_1200'), ('bpp', '016... |
# functools.partial的作用就是,
# 把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。
def int2(x, base=2):
return int(x, base)
print(int2('111'))
import functools
int8 = functools.partial(int, base=8)
print(int8('71')) |
#!/usr/bin/python
#HW 3.5
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
print line |
# Generated by Django 3.2.3 on 2021-06-02 17:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Caja',
fields=[
... |
import cv2
import numpy
import pylab
from repeated_timer import repeatedTimer
from Tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
def VideoPlot():
frame = video.read(0)[1]
axis1.imshow(frame)
canvas1.show()
canvas1.get_tk_widget()... |
# Copyright (c) 2014, The MITRE Corporation. All rights reserved.
# For license information, see the LICENSE.txt file
from django.db import models
from django.contrib.auth.models import User
from dateutil.tz import tzutc
import datetime
MAX_ID_LEN = 128
MAX_TITLE_LEN = 128
class ProtocolBindingId(models.Mode... |
#!/usr/bin/env python3
#
# This file is part of the GROMACS molecular simulation package.
#
# Copyright (c) 2014,2015,2016,2018,2019, by the GROMACS development team, led by
# Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
# and including many others, as listed in the AUTHORS file in the
# top-level so... |
"""
rex.widget.map
==============
:copyright: 2015, Prometheus Research, LLC
"""
from cached_property import cached_property
from webob.exc import HTTPUnauthorized, HTTPBadRequest
from rex.urlmap import Map
from rex.core import Error, StrVal, MapVal, BoolVal
from rex.web import authorize, confine, Path... |
"""
Tracks iPhones by sending a udp message to port 5353.
An entry in the arp cache is then made and checked.
device_tracker:
- platform: iphonedetect
hosts:
host_one: 192.168.2.12
host_two: 192.168.2.25
"""
import logging
import subprocess
import sys
from datetime import timedelta
import socket
imp... |
import grass.script as grass
import os
lista_clumps=grass.mlist_grouped ('rast', pattern='*orig_clump_mata_limpa_AreaHA') ['PERMANENT']
#lista_clumps=lista_clumps[0:2]
#listaold=['1000','120','180','240','30','350','440','500','60','720','840','90']
#cont_listold=0
#for i in lista_clumps:
##print i
#formato=... |
#71200663
#Wisnu Aryo Jatmiko
a = int(input("Masuka Bilangan Yang Akan Di-Check: "))
if a > 1:
for i in range (2,a):
if (a % i) == 0:
print("Bilangan Tersebut Bukan Merupakan Bilangan Prima")
break
else:
print("Bilangan Tersebut Merupakan Bilangan Prima")
else... |
from django.contrib.auth import authenticate, login, logout
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from django.utils.html import escape
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render, redirect
from posts... |
from django.shortcuts import render,get_object_or_404,redirect
from django.views import View
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from .models import Post
from django.core.paginator import Paginator
# Create your views here.
def home(request):
return render(r... |
from django.db import models
from django.utils import timezone
from django.core.validators import URLValidator
from hashids import Hashids
from django.conf import settings
from encrypted_model_fields.fields import EncryptedCharField
hashids = Hashids(salt=settings.SALT_KEY, min_length=8)
class UrlShrinked(models.Mode... |
# A. PizzaForces
for _ in range(int(input())):
n = int(input())
# Solution is based on https://codeforces.com/contest/1555/submission/124369094
ans = max(6, (n + 1)) // 2 * 5
print(ans)
|
import pyglet
import argparse
import uuid
import os
from google.cloud.dialogflowcx_v3beta1.services.agents import AgentsClient
from google.cloud.dialogflowcx_v3beta1.services.sessions import SessionsClient
from google.cloud.dialogflowcx_v3beta1.types import session
from sentiment import analyze_sentiment, find_emotio... |
test_case = int(input())
for i in range(test_case):
number = int(input())
if number % 2 == 0: print(0)
else: print(1)
|
from airflow.operators.sensors import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
from airflow.models import Variable
def get_cluster_status(emr, cluster_id):
response = emr.describe_cluster(ClusterId=cluster_id)
return response['Cluster']['Status']['State']
class ClusterCheckSensor... |
from functools import partial
from typing import Any, Callable, Dict, List, Optional, Union
from tartiflette.coercers.outputs.compute import get_output_coercer
from tartiflette.resolver.default import default_field_resolver
from tartiflette.resolver.factory import resolve_field
from tartiflette.types.helpers.get_direc... |
#basic functions for ML
#updated from basic.py 22nd September
#IMPORTS
from collections import defaultdict as ddict, OrderedDict as odict
from typing import Any, Dict, List
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from rdkit.Chem import PandasTools, AllChem as Chem, ... |
import automat
import attr
import cbor
import types
import zope
from twisted.protocols.basic import Int32StringReceiver
from twisted.internet.protocol import Factory
from nacl.signing import VerifyKey
from envelopes import SecretHandshakeEnvelopeFactory, Curve25519KeyPair, Ed25519KeyPair
from util import is_32bytes... |
# Задание 1
# Дан список учеников, нужно посчитать количество повторений каждого имени ученика.
students = [
{'first_name': 'Вася'},
{'first_name': 'Петя'},
{'first_name': 'Маша'},
{'first_name': 'Маша'},
{'first_name': 'Петя'},
]
# Пример вывода:
# Вася: 1
# Маша: 2
# Петя: 2
names = []
for item in students... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.