text stringlengths 38 1.54M |
|---|
print('i can only go to two countries now. QAQ')
conutries = ['American','Beww','Chian',]
conutries[2] = 'Dean'
conutries.insert(0,'Eeew')
conutries.insert(2,'Ftef')
conutries.append('Gdgb')
print(conutries)
print(conutries.pop(0) + ' Sorry, i am not going yet')
print(conutries.pop(1) + ' Sorry, i am not going yet')
pr... |
"""
@author: Kostas Hatalis
"""
import numpy as np
def set_coverage(experiment):
"""
Formulates the tau level to create equally spaced quantiles (0,1)
Arguments:
experiment(dict): n_PI number of PIs to calculate
Returns:
experiment(dict): N_tau (num of taus), and taus
"""
N_P... |
"""Beam search implementation in PyTorch."""
#
#
# hyp1#-hyp1---hyp1 -hyp1
# \ /
# hyp2 \-hyp2 /-hyp2#hyp2
# / \
# hyp3#-hyp3---hyp3 -hyp3
# ========================
#
# Takes care of beams, back pointers, and scores.
# Code... |
#! -*- coding: utf-8 -*-
'''
Created on Aug 22, 2011
@author: flyxian
'''
import transmissionrpc
import globals
#globals.init_configs("test_config.yaml")
#print globals.trconfig
tc = None
#create rpc connection to transmission
def connect():
global tc
tc = transmissionrpc.Client(globa... |
import os
import argparse
from typing import Dict
from alarm import Alarm
import httplib2
import dateutil.parser
import datetime
from googleapiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import tzlocal
scopes = 'https://www.googleapis.com... |
from rest_framework.response import Response
from rest_framework import status
#centralized responces for all the APIs for this app (users)
#is used for internationalization of responses
def getResponce(*args):
responces = {
"en" : {
"login_invalid_credentials" : Response({'error': "Invalid credential... |
import os
import numpy as np
import pandas as pd
def out_result(predicted_list, gt_lst, path="./result/testset_result.csv"):
"""
output a result file
:param predicted_list:
:param gt_lst:
:param path:
:return:
"""
col = ['predicted', 'groundtruth']
arr = np.array([list(predicted_li... |
import requests
from bs4 import BeautifulSoup
import json
# The main function of this .py document is to crawl and scrap data from WWF website
# Ideally, you may need to wait for about 30s- 1min for all html information being scrapped into local file
# You only need to run this .py document once, and you can move to... |
import tushare as ts
from .StockTicket import *
class StockData(object):
def __init__(self, data):
print('StockData:',data)
ts.set_token('2a7e5987596b91c995bfaa15b9b0de0c3947ee7fd76d6dbc06e577d8')
self.tick_ = StockTicket('300073',0,0,'','')
self.proj_ = ts.pro_api()
... |
import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
import plotly.graph_objects as go
import plotly.express as px
## Datasets
crime = pd.read_csv('data/crime_cleaned.csv')
victim_donut_data = pd.read_csv('data/victims_donut_data.csv', index_col = 0)
pop_area_count = pd.read_csv('data/... |
#conversor de Fahrenheit para Celsius
temperaturaFahrenheit = input("Insira a temperatura em Fahrenheit: ")
temperaturaCelsisus = 5 * (float(temperaturaFahrenheit) - 32) / 9
print(" Temperatura em Celsius:", temperaturaCelsisus)
|
#!/usr/bin/env python
# coding: utf-8
# In[10]:
fibonacci = [1, 1] # Desinated first 2 item of the Serial
[fibonacci.append(fibonacci[i] + fibonacci[i+1]) for i in range(8)] # Change the number 8 to see more item in Serial
print(fibonacci)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.ActivityConsultInfo import ActivityConsultInfo
class AlipayMarketingCampaignUserVoucherConsultResponse(AlipayResponse):
def __init__(self):
super(AlipayM... |
import glob
from .. import nptipsyreader
import numpy as np
import pdb
import matplotlib.pyplot as plt
import matplotlib as mpl
def averageden():
gtpfiles = glob.glob('*.gtp')
gtpfiles.sort()
avgden = np.zeros(len(gtpfiles), dtype='float')
medianden = np.zeros(len(gtpfiles), dtype='float')
a = np.z... |
# Solution of;
# Project Euler Problem 489: Common factors between two sequences
# https://projecteuler.net/problem=489
#
# Let G(a, b) be the smallest non-negative integer n for which gcd(n3 + b, (n
# + a)3 + b) is maximized. For example, G(1, 1) = 5 because gcd(n3 + 1, (n +
# 1)3 + 1) reaches its maximum value of ... |
#set module language
import wrap_py
from wrap_py import _transl
_transl.set_lang("ru_RU")
# translator for module strings
from wrap_py._transl import translator as _
#translate window title
wrap_py.app.set_title(_(wrap_py.app.get_title()))
#configure wrap_py
wrap_py.make_nice_errors()
#prepare data source
import w... |
from sys import stdin,stdout
import heapq
def dijk(grid,costs):
r = len(grid)
c = len(grid[0])
dirs = [(0,1),(1,0),(-1,0),(0,-1)]
pq = [(grid[y][0],0,y) for y in range(r)]
for y in range(r):
costs[y][0] = grid[y][0]
heapq.heapify(pq)
while pq:
cur_cost,cur_x,cur_y = heapq.heappop(pq)
# print(cur_x,cur_y,cur... |
from numpy import cos, sin, sqrt, arctan, array
import cv2 as cv
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
self.round_point()
def distance(self, point):
return sqrt((self.x - point.x)**2 + (self.y - point.y)**2)
def translate_x(self, x):
self.x ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MemberDataUI.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MemberData(object):
def setupUi(self, MemberDat... |
from __future__ import print_function
from xml.dom import minidom
import json
import jsonpickle
import sys
class Point:
x = 0
y = 0
def __init__(self, x, y):
self.x = x
self.y = y
class Rect:
x = 0
y = 0
w = 0
h = 0
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
cla... |
# Generated by Django 2.0.5 on 2018-05-30 18:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('board', '0004_board_team'),
]
operations = [
migrations.RemoveField(
model_name='sprint',
name='duration',
),
]
|
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# In[2]:
data1 = pd.read_csv("deliveries.csv")
data2 = pd.read_csv("matches.csv")
# In[3]:
data1.head()
data1.columns
# In[4]:
data1.shape
# In[5]:
data2.head()
# In[6]:
data2.s... |
import random
class Color:
Red = 0
Yellow = 1
Blue = 2
Green = 3
Wild = 4
Str = ["R", "Y", "B", "G", "W"]
class Card:
def __init__(self, number, color):
self.number = number
self.color = color
def matches(self, check):
return self.number == check.number \
... |
from distutils.core import setup, Extension
from Cython.Distutils import build_ext
import numpy
import subprocess
import os
python_root = subprocess.Popen("which python", shell=True, stdout=subprocess.PIPE
).stdout.read().decode().strip()
print(python_root)
python_root = os.pa... |
# if_sampple07.py
num = input('正の整数を入力してください:')
num = int(num)
if num > 0:
if num % 2 == 0:
print('正の偶数')
else:
print('正の奇数')
print('処理を終了します')
else:
print('正の数を入力してください')
|
from django.conf.urls import url
from django.urls import path, re_path
from . import views
app_name = 'pitanja'
urlpatterns = [
# /index/
path('', views.ObjavaView, name='pitanja'),
]
|
'''statSaukip_1.0
Updates:
- range of rows is automatic
Problems:
- не достаточно доступа для забора файлов с сервера этой прогой; тогда сначала нужно перенести интересующий год к себе на комп
'''
from csv import reader
from openpyxl import load_workbook, Workbook
from os import getcwd, listdir, chdir, remove, ... |
import json
d='''{"Name":"Ram",
"Class":"IV",
"Age":9 }'''
python_string=json.loads(d)
print(python_string) |
#gerar 16 sub-chaves de tamanho 48
def GenerateSubkeys(k):
firstperm=InitialPermutation(k) #permutação inicial das chaves
l,r=DivideKey(firstperm) #dividir chave principal em duas com metade do tamanho
key_pairs=[]
key_pairs=InitialShift(l,r) #fazer o shift inicial
keys=[]
for a,b in key_pairs:
keys.append(Fina... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 17:52:55 2021
@author: zijie
"""
import gurobipy as gp
from gurobipy import GRB
m = gp.Model("mip1")
x = m.addVar(vtype=GRB.BINARY, name="x")
y = m.addVar(vtype=GRB.BINARY, name="y")
z = m.addVar(vtype=GRB.BINARY, name="z")
m.setObjective(x +... |
"""
There is a problem with your keyboard: it randomly writes symbols when you are typing a text. You need to clean
up the text by removing all symbols.
Task:
Take a text that includes some random symbols and translate it into a text that has none of them. The resulting
text should only include letters and numbe... |
'''
Created on Nov 27, 2020
@author: ian
'''
from Piece import Piece
from Square import Color
def createPieces(color):
pieces = []
# 1
points = [(0,0)]
w = 1
h = 1
p = Piece(points, w, h, color)
#p.addSymmetry(Symmetry.HORIZONTAL)
#p.addSymmetry(Symmetry.VERTICAL)
#p.addS... |
# 1
# 3
# A 10
# B 7
# C 5
T = int(input())
#숫자입력받기
for t in range(1, T+1):
N = int(input())
doc = ''
for j in range(N):
Ci, Ki = input().split()
#알파벳 Ci와 알파벳의 연속된 개수 Ki를 .split()으로 공백을 기준으로 나눠준다
Ki = int(Ki)
while True:
if Ki <= 0:
break
... |
from __future__ import print_function
import unittest
from pytraj import io as mdio
from pytraj.utils import eq, aa_eq
class Test(unittest.TestCase):
def test_0(self):
from pytraj.core import mass_atomic_number_dict, mass_element_dict
top = mdio.load_topology("./data/tz2.parm7")
mass_list... |
from importlib import import_module
from django.apps import AppConfig as BaseAppConfig
class AppConfig(BaseAppConfig):
name = "neuronit"
def ready(self):
import_module("neuronit.receivers")
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-11-10 04:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('subject', '0005_topic_ifshow'),
]
operations = [
migrations.AlterModelOpti... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 4 16:45:25 2019
@author: danie
"""
from consolemenu import *
from consolemenu.items import *
lista_tipos= []
lista_juegos = []
def mainMenu():
# Create the menu
menu = ConsoleMenu("Tienda de Videojuegos", "Menu")
imprimir = FunctionItem("Inventario", imprim... |
# -*- coding: ISO-8859-1 -*-
#
# generated by wxGlade 0.9.3 on Thu Jun 27 21:45:40 2019
#
import sys
import traceback
import wx
import wx.ribbon as RB
from About import About
from Adjustments import Adjustments
from Alignment import Alignment
from BufferView import BufferView
from CameraInteface impor... |
# 자물쇠와 열쇠
#
# https://programmers.co.kr/learn/courses/30/lessons/60059
# 풀이 실패
from copy import deepcopy
def rotate_key(key):
M = len(key)
ret = [ [0] * M for _ in range(M) ]
offset = [ [ (M - 1 - r - c, r - c) for c in range(M)] for r in range(M)]
for r in range(M):
for c in range(M):
... |
"""Tests with explicit examples.
"""
import numpy as onp
from hypothesis import given, settings
from hypothesis import strategies as st
from utils import assert_arrays_close, assert_transforms_close, sample_transform
import jaxlie
@settings(deadline=None)
@given(_random_module=st.random_module())
def test_se2_tran... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
from builtins import str
from builtins import range
from builtins import object
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.uic import *
from qgis.core import *
from qgis.utils import *
from qgis.gui import *
from ProjektImport import *
from o... |
STATES = {
1: {
'title': 'Base task',
'descr': 'Simple task'
},
2: {
'title': 'Subtask',
'descr': 'Sub task, visible only in subtask menu.'
}
}
|
from django.shortcuts import render, redirect
from .models import Reflection, Submission, Question, QuestionSubmission, User
from django.utils import timezone, dateformat
from datetime import datetime
from django.contrib.auth.models import User
def home(request):
user = request.user
try:
reflection = ... |
import discord;
from discord.ext import commands;
import json;
#LEVELING SYSTEM
#CONFIG
with open(r"C:\Users\antho\Desktop\Saitama\Config.json", "r") as f:
config = json.load(f);
class LevelSystem(commands.Cog):
def __init__(self, client):
self.client = client;
@commands.command(pass_context = T... |
N = int(raw_input())
array = list(map(int,raw_input().split(' ')))
negative = 0
positive = 0
zeros = 0
for i in range(N):
if array[i] < 0:
negative += 1
elif array[i] > 0:
positive += 1
else:
zeros += 1
print '%.6f' % (positive/float(N))
print '%.6f' % (negative/float(N))
pri... |
from math import exp
import math
# PLCOm2012 model (Tammemagi,NEJM,2013)
# Author Kevin ten Haaf
# Organization Erasmus Medical Center Rotterdam
# Last adjusted: April 25, 2017
def execute(info):
#age,edLevel,bmi,copd,hxLungCancer,famHxCanc,race,smokerStatus,cigsPerDay,smokDurat,yrsQuit)
age = int... |
import math
import os
# pip install PyGithub. Lib operates on remote github to get issues
from github import Github
import re
import argparse
# pip install GitPython. Lib operates on local repo to get commits
import git as local_git
from google.cloud import translate
CHINESE_CHAR_PATTERN = re.compile("[\u4e00-\u9f... |
#import numpy
import numpy as np
from scipy import signal
def process():
#"""
__all__ = ['octavefilter', 'getansifrequencies', 'normalizedfreq']
def _buttersosfilter(freq, freq_d, freq_u, fs, order, factor, show=0):
# Initialize coefficients matrix
sos = [[[]] for i in range(len(freq)... |
from ascii_table import Table
from qasm.bridge.config.QuantumComputerConfig import QuantumComputerConfig
from qasm.helpers.Util import SortedDictionary
from qasm.commands.Command import Command
class Show(Command):
def run(self):
"""
Return method for config show command
:return: (None)... |
#!/usr/bin/python3
"""1-pack_web_static module"""
from os.path import isfile
from datetime import datetime
from fabric.api import local
def do_pack():
"""Generates a .tgz archive from the contents of web_static folder of
AriBnB Clone repo
Returns: Archive path, otherwise False
"""
ct = datetime.no... |
# coding: utf-8
# flake8: noqa
"""
SevOne API Documentation
Supported endpoints by the new RESTful API # noqa: E501
OpenAPI spec version: 2.1.18, Hash: db562e6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# import apis into sdk ... |
from jinja2_htmltemplate.template import Template
from nose.tools import eq_
def test_jinja_template():
t = Template('<title><TMPL_VAR NAME="foo"></title>')
eq_(t.render(foo="Hello World!"), "<title>Hello World!</title>")
def test_jinja_loop():
t = Template('''
<TMPL_LOOP NAME="loop">
Item: <TMPL_VAR ... |
# Copyright (c) 2017 Ruud de Jong
# This file is part of the SlipLib project which is released under the MIT license.
# See https://github.com/rhjdjong/SlipLib for details.
__version__ = '0.3.0'
|
from typing import List
import os
import json
import pandas as pd
def get_config() -> dict:
config_path = os.path.join(os.path.split(os.path.dirname(__file__))[0], "config.json")
config = json.load(open(config_path, 'r'))
return config
def get_root_path() -> str:
""" Read root path from config.json ... |
from django.urls import include, path
from .views import classroom, students, professors, coordinators, planners, sutdadmin
urlpatterns = [
path('', classroom.home, name='home'),
path('403', classroom.ForbiddenView.as_view(), name='403'),
path('icsconvert', classroom.ICSConverterView.as_view(), name="ics... |
from flask import request
from flask_templates import app
from functools import wraps
def support_jsonp(f):
"""Wraps JSONified output for JSONP"""
@wraps(f)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
content = str(callba... |
import pdb
import os
import pandas as pd
import numpy as np
from pymatbridge import Matlab
from utilities import prepare_markov_data, introduce_inhibs, score_network, score_predictions
def network_hill(panel, prior_graph=[], lambdas=[], max_indegree=3, reg_mode='full', stdise=1, silent=0, maxtime=120):
'''
ru... |
#!flask/bin/python
from flask import Flask
import flask
from flask import Flask, jsonify, abort, request, make_response, url_for
import json_unpacker
import matching_model
from user import User
from team import Team
import user
import json
import clustering as clst
def extract_users(req):
exper_data,users = ([],[])
... |
#
# @lc app=leetcode id=140 lang=python3
#
# [140] Word Break II
#
from typing import List
# @lc code=start
class Solution:
def __init__(self):
self.hashMap = {}
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
if s in self.hashMap:
return self.hashMap[s]
if no... |
#Problem 355. Design Twitter
'''
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:
postTweet(userId, tweetId): Compose a new tweet.
getNewsFeed(userId):... |
def calc(x,y):
# z = x + y, x - y, x / y, x * y
# return z
return x + y, x - y, x / y, x * y
# s = calc(4,5)
# print(s[0], s[1])
a,b,c,d = calc(4,5)
print(a,b,c,d) |
import sys
_module = sys.modules[__name__]
del sys
config = _module
dataset = _module
preprocess_images = _module
train = _module
train_blend = _module
utils = _module
config = _module
dataset = _module
train = _module
utils = _module
config = _module
dataset = _module
extract_images_from_csv = _module
train = _module
... |
from interaction.chatbots.chat_bot_structure import ChatBotStucture
from interaction.chatbots.identifier import Identifier, IdentifierType
from utils.minuteur import Minuteur
import time
class MinuteurChatBot(ChatBotStucture):
def __init__(self, services, find_number=False):
super().__init__(services, ... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
HTTP T... |
import time
import subprocess
import utils
from utils import assignOrder
from utils import assertEqual
from utils import assertContains
from utils import randomString
import threading
import queue
import random
from collections import OrderedDict
import logging
import pprint
import configparser
import json
import rando... |
from models.base_model import BaseModel
import peewee as pw
from models.user import User
from models.disease import Disease
class UserDisease(BaseModel):
user = pw.ForeignKeyField(User, on_delete="CASCADE")
disease = pw.ForeignKeyField(Disease, on_delete="CASCADE") |
import os, sys, string
import arcpy
from arcpy import env
from arcpy.sa import *
import glob
import string
from sets import Set
import math
import time
print "Setting local parameters and inputs"
#Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")
env.overwriteOutput = True
b... |
from typing import List
import pandas as pd
from dataframes_extracted import DataFramesExtracted
class Transformer:
@classmethod
def get_df(cls, dfs: List[pd.DataFrame]) -> pd.DataFrame:
dfs = DataFramesExtracted(dfs)
result_df = cls._merge_dfs(dfs)
result_df = cls._get_df_remove_nul... |
#!/usr/bin/python
from pychartdir import *
# The data for the chart
data = [50, 55, 47, 34, 42, 49, 63, 62, 73, 59, 56, 50, 64, 60, 67, 67, 58, 59, 73, 77, 84, 82, 80,
84, 89]
# The error data representing the error band around the data points
errData = [5, 6, 5.1, 6.5, 6.6, 8, 5.4, 5.1, 4.6, 5.0, 5.2, 6.0, 4.9, ... |
import json
import boto3
from botocore.exceptions import ClientError
from django.conf import settings
from .settings import DJANGO_SLOOP_SETTINGS
from .models import AbstractSNSDevice
class SNSHandler(object):
client = None
def __init__(self, device):
self.device = device
self.client = se... |
import cv2
face_detect=cv2.CascadeClassifier('C:\\Users\\OCAC\\Desktop\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml')
video=cv2.VideoCapture(0)
while True:
check,frame=video.read()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
face=face_detect.detectMultiScale(gray,scaleFact... |
# Created by Leon Hunter at 2:07 PM 11/30/2020
# Assign a radius
radius = 20.0
# compute area
area = radius * radius * 3.14159
integer = 1
# display results
output = "The area of the circle with radius {} is {}; Third argument is {}"
formattedOutput = output.format(radius, area, "third argument"... |
# Generated by Django 3.2.7 on 2021-09-27 18:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mainApp', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Log',
new_name='AccountUser',
),
]... |
"""
This file holds the anonymizer API service
which exposes an RESTful API for inquering
anonymization tasks of a user.
"""
from flask import Flask, request
from flask_restful import reqparse, abort, Resource, Api
import anonymizer
import sys
import string
import random
import json
import redis... |
# -*- coding:utf-8 -*-
import random,math
import numpy as np
"""
CLASS: Person
PROPERTY:
id:Person ID(unique value).
spouse: The ID of person's spouse(-1 refer to no spouse).
spouse_num: The rank of spouse in love list.
change_num: The times of change spouse of person.
accepted_threshold: The worst sp... |
class Solution:
def processQueries(self, queries, m: int) :
P = [i+1 for i in range(m)]
ret = []
for i in queries:
idx = P.index(i)
ret.append(idx)
t = P.pop(idx)
P = [t] + P
return ret
sol = Solution()
queries = [3,1,2,1]
m = 5
print... |
# H.H. Oct 2017
# Augmenting and creating LMDB for NYU-V2
import os
import glob
import random
import numpy as np
import sys
caffe_root = '/home/carrot/caffe/'
sys.path.insert(0, caffe_root + 'python')
import cv2
import caffe
from caffe.proto import caffe_pb2
import lmdb
import skimage.io as io
import h5py
# data pa... |
# !usr/bin/python3.4
# -*- coding:utf-8 -*-
import json
# import grequests
import requests
import re
import time
from tool.jfile.file import *
def exception_handler(request, exception):
print('连接错误...')
# def geturl(urls):
# header = {'User-Agent':
# 'Mozilla/5.0 (Windows NT 10.0; WOW64; ... |
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
from django_plotly_dash import DjangoDash
from sympy import latex, sympify, integrate, Symbol
import math
from numpy import linspace
import dash_defer_js_import as dji
externa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class BcBusinessUserInfo(object):
def __init__(self):
self._logo = None
self._name = None
self._open_id = None
self._uid = None
@property
def logo(self):
... |
# Discord Bot
import logging
import os
import sys
import discord
import logbook
import yaml
from discord.ext import commands
from discord.ext.commands import Bot
from logbook import Logger
from logbook import StreamHandler
from logbook.compat import redirect_logging
extensions = ["casca.cogs.mathematics"]
Whiteliste... |
def readFile():
datalist = []
datafile = open("./data/day#data.txt", "r")
for aline in datafile:
transactions.append(int(aline))
datafile.close()
return datalist
def part1():
return ('part1')
def part2():
return ("part2")
def test():
test_input = []
assert part1(te... |
A = int(input())
B = int(input())
C = int(input())
mul = A * B * C
mul_list = list(str(mul)) # ['1', '8', '6', '0', '8', '6', '7']
print(mul_list.count('0'))
print(mul_list.count('1'))
print(mul_list.count('2'))
print(mul_list.count('3'))
print(mul_list.count('4'))
print(mul_list.count('5'))
print(mul_list.count('6')... |
from django.test import SimpleTestCase, Client
from django.conf import settings
import asyncio
import uvloop
import requests
import json
from .repository.get_api_data import ApiHandler
from .data_processor.data_processor import Processor
from .views import HomeView
home = HomeView()
processor = Processor()
api_handle... |
from django import forms
from clubkit.clubs.models import ClubInfo, Team, Pitch, ClubPosts, ClubMemberships, ClubPackages
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
# Form to update/change club information
class ClubInfoForm(forms.ModelForm):
club_add... |
import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.model_selection import train_test_split
import joblib #jbolib模块
overwrite = False
# 选取前一百个特征 100例AutoML得到的pipeline
# NOTE: Make sure that the outcome column is labeled 'target' in the data file
medical =... |
import dlib
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QMainWindow
from identity.pass_login import Ui_MainWindow
import logging.config
import logging.config
import winsound
import time
from gui import *
from datetime import datetime
# 找不到已训练的人脸数据文件
class TrainingDataNotFoundError(FileNotFoundError):
... |
class PowerSupply:
def __init__(self, data):
self.vertexes = set()
self.edges = data
self.edges.sort(key=lambda x: x[2])
self.make_vertexes()
def make_vertexes(self):
for edge in self.edges:
self.vertexes.add(edge[0])
self.vertexes.add(edge[2])
... |
"""
- Merge all the different data-sets into one: WGA + NGA + WikiArt
- Also save all the model data -> Split into: Training, Validation, & Testing sets
"""
import pandas as pd
import unicodedata
from sklearn.model_selection import train_test_split
from PIL import Image
import os
import numpy as np
FILE_PATH = os.path... |
"""An example program that uses the elsapy module"""
from elsapy.elsclient import ElsClient
from elsapy.elsprofile import ElsAuthor, ElsAffil
from elsapy.elsdoc import FullDoc, AbsDoc
from elsapy.elssearch import ElsSearch
from xml.dom.minidom import parseString
import json, re
import xml.etree.cElementTree as ET
impo... |
# Copyright 2020 The FedLearner Authors. 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 applica... |
import digitalio, board, busio, adafruit_rfm9x
import time
RADIO_FREQ_MHZ = 868.
CS = digitalio.DigitalInOut( board.CE1)
RESET = digitalio.DigitalInOut( board.D25)
spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
radio = adafruit_rfm9x.RFM9x( spi, CS, RESET, RADIO_FREQ_MHZ)
counter = 0;
t0 = time.perf_c... |
ML_DATA_QUERY = '''
SELECT
(Atlas_of_surveillance_20201007.State || \' \' || Atlas_of_Surveillance_20201007.County),
acs2015_county_data.Black,
acs2015_county_data.TotalPop,
acs2015_county_data.Poverty,
... |
tempo = int(input("Tempo: "))
veloc = int(input("Velocidade: "))
dist = veloc * tempo
litro = dist / 12
print(f"Litros = {litro}") |
"""
CP1404/CP5632 Practical
Practice and Extension Work
Converting parallel lists to a dictionary
Sample list input:
> Date: (8, 4, 2019)
> Names: ["Jack", "Jill", "Harry", "John", "Garry"]
> DOB: [(12, 4, 1999), (1, 1, 2000), (27, 3, 1982), (1, 2, 1979), (20, 11, 1992)]
"""
# Get inputs
current_year = input("What is... |
# Copyright 2018 The Batfish Open Source Project
#
# 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 applicab... |
# 54. Spiral Matrix
'''
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
'''
#Array
class Solution(object):
de... |
from pyjak.convert import (
BinaryError, BinarySizeMismatch,
parse_int8, parse_uint8, parse_int16, parse_uint16, parse_int32,
parse_uint32, parse_int64, parse_uint64, parse_float32, parse_float64,
parse_bool, dump_int8, dump_uint8, dump_int16, dump_uint16, dump_int32,
dump_uint32, dump_int64, dump_u... |
from django.conf.urls import patterns, url
from accounts import views
from django.conf import settings
from django.conf.urls.static import static
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
url(r'^$', lambda x: HttpResponseRedirect('/a/my_account')),
url(r'^my_account/$', views.my... |
import conducto as co
def main() -> co.Serial:
with co.Serial(image=co.Image(copy_repo=True)) as node:
node["hello"] = co.Exec("ls")
return node
co.main(default=main)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.