index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
986,200
1a1f5be20af628624a553756f0786c13231eb796
import threading import os from subprocess import Popen, PIPE class MPG123Player(threading.Thread): daemon = True # added to make Ctrl-C and Ctrl-D work when running python -i player.py def __init__(self, music=''): self.music = music self.working = False threading.Thread.__init__(se...
986,201
8fff857b35a469df6cab51578eda2cb532edb32a
from __future__ import print_function import torch import torch.optim as optim import numpy as np import math def add_sparse_args(parser): # hyperparameters for Zero-Cost Neuroregeneration parser.add_argument('--growth', type=str, default='random', help='Growth mode. Choose from: momentum, random, and momentum...
986,202
22c0a8ee40982deb49dd3684a9a19ea09f07e9d9
num = input() tako = [] for i in range(num): tako.append(input()) print min(tako)
986,203
7a31f2093253d8dd0a31f1089c690ec53e8c32f7
import json from collections import defaultdict # def format_date(s): # return output = defaultdict(list) nyc_stations = ["NY CITY CENTRAL PARK NY US", "STATEN ISLAND 1.4 SE NY US", "LA GUARDIA AIRPORT NY US", "STATEN ISLAND 4.5 SSE NY US", "JFK INTERNATIONAL AIRPORT NY US"] with open("weather.csv") as f: next(f) ...
986,204
97bb62eb8cf291710b9747a3596043c07d29ac0e
from hospital_pricing.models import Hospital, Pricing, DRGCode from api.serializers import HospitalSerializer, PricingSerializer from rest_framework import generics, permissions, status, viewsets from rest_framework.response import Response class PricingViewSet(viewsets.ModelViewSet): """ This ViewSet provides both...
986,205
0634856b07562b96ef2da8a4113197fcd3852744
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Schedule, Comment admin.site.register(Schedule) admin.site.register(Comment)
986,206
abc93ff3730229724865ce467de1057d41c71536
from django.shortcuts import render from django.http import HttpResponse, HttpResponseNotFound from .models import SadrzajProjekatPodkategorije, Prijava, Istaknuto, Projekat, ProjekatPodkategorija, Aktuelnost, ClanTima, Fotografija, Partner, PressClanak, Publikacija, IstorijskaTura, VideoKlip, Izlozba, ArhivskiMaterija...
986,207
df6b6ff8b50159b0e2f6564a7f93d78689bf763c
import pathlib import os import tensorflow as tf import numpy as np import model import losses import dataset_helpers DATA_PATH = os.path.realpath(os.path.join(__file__, '../../data')) SHAPE_BASIS_PATH = os.path.join(DATA_PATH, "shape_basis.npy") SHAPE_MEAN_PATH = os.path.join(DATA_PATH, "shape_mean.npy") EXPR_BASIS_...
986,208
a2ef62a56613b935245c69a81e8ad9cd36c364f2
# STATUS builds, need sample class jansson: name = __name__ home = "http://www.digip.org/jansson/" scmOrigin = "git clone https://github.com/akheron/jansson {destination}" dataTypes = [ "json" ] target = "test/bin/json_process" targetParam = "" aflFuzzParam = "" clean = [...
986,209
676b4eb2f036c5379c5367528429cd124facc5b0
# Carlos Badillo García # Programa que lee el valor de cada uno de los lados de un triangulo e indica el tipo de triángulo que es def indicarTipoTriangulo(lado1, lado2, lado3): #Indicar que tipo de triángulo es dependiendo el valor de sus lados if lado1 == lado2 == lado3: return "El triángulo es equ...
986,210
8f8fd4350909cb7069324d348f7eb3a0112ad4ae
""" Helper moduel to handle temporary files as well as provide a clean call to interface with Tango server for submissions. """ import time from subprocess import run def submit(user, user_file): """ Funtion to alter the a string in order to make the appropriate funtion call in order to submit a job to ...
986,211
d19669d0181a164fd36d635f0fb020c51345357a
import re import json import pandas as pd import pickle import random import numpy as np import operator import gensim.models from gensim.test.utils import datapath from gensim import utils from gensim.parsing.preprocessing import preprocess_string, strip_tags, strip_punctuation, strip_multiple_whitespaces, \ strip...
986,212
9853d8eef5834e9f0062e3a80a55c400ff48fd00
from selenium.webdriver.common.by import By from base.base_page import BasePage from pages.home.navigation_page import NavigationPage import utilities.custom_logger as cl class LoginPage(BasePage): log = cl.custom_logger() def __init__(self, driver): super().__init__(driver) self.driver = dr...
986,213
b5eb51f5ff2448b94e40a0637f2009afb3bd1af2
def check_string(some_string, valid_strings_start, valid_strings_end): end_matches = 0 start_matches = 0 unit_len = len(valid_strings_start[0]) if len(some_string) % unit_len != 0: return False if some_string[:unit_len] in valid_strings_start: start_matches += 1 else: ret...
986,214
108ba09b3ab967abf0b2ba2bf7724138d36fef5e
# prob 1302 from https://www.acmicpc.net/problem/1302 # if 'top' > 'toz': # print('top') # else: # print('toz') # dic = {'top':4, 'kimtop':2} # if 'toz' in dic: # print(dic['top']) # else: # print('fault') N = int(input()) dic = {} tilteList = [] for x in range(N): tmp = inpu...
986,215
092ff56924a35c4139fff34f88d24b5bbe986bab
import pymysql def printCursor(cursor): for x in cursor: print(x) mydb = pymysql.connect(host="localhost", user="root",password="" ,database="locofi") mycursor = mydb.cursor()
986,216
c880fd89e1d8b1ec2c806433c090ee06eb4f22a4
# Program No : 17 # program to create a histogram from a given list of integers def Histogram(lis,sym) : for i in lis : for j in range(i) : print(sym,end=" ") print(end="\n") Histogram([2,5,3,2,1],'9') #Program to concatenate all elements in a list into a string and return it def Concate(llist) : ...
986,217
eb68b0661045ab402750ec76996e6c3a517b1778
# -*- coding: utf-8 -*- """ Created on Fri Jan 23 11:01:24 2015 @author: Mathew Topper """ """ TBC """ # Set up logging import logging module_logger = logging.getLogger(__name__) import abc import socket import contextlib from sqlalchemy import create_engine, MetaData, Table from sqlalchemy.ext.declarative import...
986,218
3fe0ae4b13d7a7ad87bf7b756a2ac9f5e5691528
#!/usr/bin/python """ v.0.1 User's Command Lines v.0.1 \033[1mDESCRIPTION\033[0m Based on blast result files (concatenated), this program creates a protein similarity profile among various species. Proteins for a given species was blasted (blastp) against several ...
986,219
9b4ad66f0f0bc336dd9eae532b23ccb0e1d43971
import math import cmath a=float(input("Enter a:")) b=float(input("Enter b:")) c=float(input("Enter c:")) disc=b**2-4*a*c if disc<0: print("Imaginary roots") realp=float(-b/2*a) imagp=cmath.sqrt(abs(disc))/(2.0*a) print("realp:",realp) print("imagp:",imagp) elif disc==0: print("...
986,220
9d40aaddd5c7b11d90bd77879b78c9720158bbaf
import pickle import numpy as np # linear algebra import sklearn as sk # machine learning from sklearn import linear_model from sklearn.metrics import mean_squared_error, r2_score from sklearn import preprocessing # for standardizing the data import pandas as pd import seaborn as sns # visualization...
986,221
be857acd646bd32c18284ced575de49eb1f9a24f
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class Poincare(nn.Module): """docstring f...
986,222
91daa199709fa48802e23c1eeeb9ce6c7ece5f5d
str1=input() str2="" res=[] for h in str1: if h>='a' and h<='z': str2+=h elif h=='B': str2=str2[0:len(str2)-1] elif h=='P': res.append(str2) def search(res,x,y): count=0 x=x-1 y=y-1 str1=res[x] str2=res[y] for x in range(0,len(str2)-len(str1)+1): if st...
986,223
e9c2f91ec723de657360532ec442043eb4763275
# https://www.acmicpc.net/problem/2033 문제 제목 : 반올림 , 언어 : Python, 날짜 : 2020-01-03, 결과 : 실패 # 오늘은 하루종일 밖이라 코딩을 못한다.. # 왜 스트링으로 푼건 틀리는지 모르겟다. 반례도 못찾겠다... import sys from collections import deque N = deque(sys.stdin.readline()[:-1])#list(map(int, list(sys.stdin.readline()))) len_N = len(N) lesser = 10 point = 2 def re_new...
986,224
dc223e8176ae62f5e83f9745bf758a3850fa6df5
#syntax errors ---the errors which occur invalid syntax are called syntax errors #Runtime errors ----The errors which occur while execution of the programm.. # once all syntax errors are corrected then only program execution starts #runtime errors also call it as exceptions----while execution of the program something g...
986,225
8ab4b1751295f6c9867cf855ba0d2104404772df
# -*- encoding:utf-8 -*- ''' @time: 2019/12/21 8:28 下午 @author: huguimin @email: 718400742@qq.com 一个doc表示一个样本 ''' import math import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from layers.dynamic_rnn import DynamicLSTM from layers.attention import Attention class GraphConvolution(n...
986,226
09faf370a23cc1f20f1f9a730f93da93082484af
from os import path from heapq import heappush, heappop #!python % < ../A-small-practice.in # in_file = '../B-small-practice.in' in_file = '../B-large-practice.in' # in_file = '../sample.in' out_file = '.'.join([path.splitext(path.basename(in_file))[0], 'out']) def solution(fin, fout): def tstr2int(tstr): thour, t...
986,227
fe411b7bd44b08744937355d4cfe4fe85522c871
""" asset_manager_pre_export_dialog ========================================== Dialog that asks wether or not the current scene should be saved before export begins. Offers the possibility to remember your choice. ----------------------- **Author:** `Timm Wagener <mailto:wagenertimm@gmail.com>`_ """ #Import...
986,228
aabc8e5e504642ca8cfb4920d0a96dbb7f03e7e1
# Generated by Django 2.2 on 2020-04-27 14:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('users', '0026_auto_20200427_1439'), ] operations = [ migrations.RemoveField( model_...
986,229
03a71601b77416cd0d9ea7540cc61c5f13bbc2d6
from django.contrib import admin from.models import Post,Action # Register your models here. class ActionAdmin(admin.TabularInline): model = Action class PostAdminModel(admin.ModelAdmin): inlines = [ActionAdmin] admin.site.register(Post,PostAdminModel)
986,230
9d394200da6e6ebf7c9fd7d47b2c666fddd656b9
# -*- coding: utf-8 -*- from django.contrib import admin from django.contrib.admin.sites import AlreadyRegistered def admin_register(model, user_admin): try: admin.site.register(model, user_admin) except AlreadyRegistered: admin.site.unregister(model) admin.site.register(model, user_adm...
986,231
c4b5c389c7bf550db45cdcb8824eec948cd7d251
from django.shortcuts import render, redirect from .models import UserAccount,Inbox,Outbox def user_view(request): if request.method == 'GET': return render(request, "user.html", {}) elif request.method == 'POST': user = UserAccount() user.name = request.POST.get('user_name'...
986,232
50b496c811f6b2c771862ac407df199449c55795
import subprocess import cv2 import numpy as np from matplotlib import pyplot as plt # # img = cv2.imread('lena.jpg',0) # edges = cv2.Canny(img,225,225) # # plt.subplot(121),plt.imshow(img,cmap = 'gray') # plt.title('Original Image'), plt.xticks([]), plt.yticks([]) # plt.subplot(122),plt.imshow(edges,cmap = 'gray') # ...
986,233
a4152ecd2bd7eef8754703b425b38fbab01bf1ab
import sys def flip_str1(s): for i in range(len(s)): sys.stdout.write(s[-i-1]) sys.stdout.write('\n') def flip_str2(s): for i in range(len(s)): print(s[-i-1]), print('\n') s=raw_input('Enter string:') flip_str1(s) flip_str2(s)
986,234
ea907cdd4e7d9feed846384c1ef5c8d72edbe5ee
# Tree iteration module # # A finite tree whose nodes childs are totally ordered from, say, # left to right, can be iterated depth-first, see Wikipedia. # To be able to reconstruct the tree-structure after iteration, # one may pass either the current depth or the change in depth from # the previous node (called step...
986,235
4c370d77f2e8c8ec9ff0d2a3f5f5a0e27c0f7f3e
import sys s, n = sys.stdin.readline().split() s = int(s) n_length = len(n) width, height = s + 2, 2 * s + 3 total_width = width * n_length matrix = [[] for _ in range(height)] for index in range(n_length): number = int(n[index]) inner_matrix = [[' ' for _ in range(width)] for _ in range(height)] mid_he...
986,236
25885be7d5d4755e3c80d52fd85c60067d512235
from interfaces.prediction_network import PredictionNetwork from TicTacToe.tick_tack_toe_state import TickTackToeState import torch from alpha_network.alpha_network import AlphaNetwork class TickTackToePredictionNetwork(PredictionNetwork): def __init__(self, network): self._network = network def p...
986,237
c3e06f23510cf992a638f080966b5aa6b1f60ba6
import unittest from filter import * class TestCases(unittest.TestCase): def test_positive_t_1(self): self.assertAlmostEqual(are_positive([-1,10,-30,20,0]),[10,20]) def test_positive_t_2(self): self.assertAlmostEqual(are_positive([-1,10,-30,20,0]),[10,20]) def test_are_greater_than_n_1(se...
986,238
b9ca3c041d550867722e6262b2021ab24f268058
from django.core.mail import send_mail from django.template.loader import render_to_string from rest_framework.permissions import AllowAny from rest_framework.views import APIView from rest_framework.response import Response from mail.api.serializers import SendMyMailSerializer from mail.models import MyMailConfig, MyM...
986,239
20ed92d3fcdd0787f980710b87db38b6d5925158
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] ...
986,240
93380859be49e6f1755fff927a57579bd2402b34
import stripe stripe.api_key = 'zGG4QHGhMlBElVBCioobCucrHJdaoeFP' def post_to_stripe(order_data): ''' Takes order data dict, extracts necessary data, and passes it to stripe for processing. ''' token = order_data['token'] sub_total = order_data['subtotal'] tax = order_data['tax'] tota...
986,241
27385c92b54429caa6bef058bfd71ba649559e1b
from subprocess import check_output from bs4 import BeautifulSoup from pprint import pprint import sqlite3 import re if __name__ == "__main__": html = lambda link: check_output("curl -s %s" % link, shell=True).decode("utf-8") # http://tamilnation.co/literature/kural/kavi...
986,242
8e6a05750706a43d5f2824912a18098e18195856
# Given two strings, check to see if they are anagrams. # An anagram is when the two strings can be written using the exact same # letters (so you can just rearrange the letters to get a different phrase or word). # For example: # "public relations" is an anagram of "crap built on lies." # "clint eastwood" is an a...
986,243
4e9c25955c1c7046434e23aeb68bdfffcac78cdf
# -*- coding: utf-8 -*- import sys,os import math import re import argparse import json import ast import copy from subprocess import Popen, PIPE from operator import itemgetter from abc import ABCMeta,abstractmethod from emap import EMAP sys.path.append(os.path.join(os.path.dirname(__file__), '../utils...
986,244
d0eaaf750257d6e1bfc8515d931b24e9d67a1d01
# filter_16_T # Like filter_16 with prescribed duration # 16 bit/sample from math import cos, pi import pyaudio import struct # Fs : Sampling frequency (samples/second) Fs = 8000 # Also try Fs = 16000 and Fs = 32000 T = 2 # T : Duration of audio to play (seconds) N = T*Fs # N : Number of samples to play #...
986,245
93b11a12f50d1ac59220e7a08ec6ef5a2df5dc79
from tokenization import BasicTokenizer import spacy from spacy.tokens import Doc line='The switches between clarity and intoxication gave me a headache, but at least the silver-haired faery’s explanation of the queens’ “gifts” helped me understand why I could want to wrap my legs around a creature who terrified me.' ...
986,246
eae9de8046ff085cbdf537808438415fc72191a3
import random import collections from PIL import Image, ImageFilter, ImageOps import numpy as np import cv2 import torch import scipy.sparse from sklearn import svm import torchvision as tv from torchvision.transforms import functional as F import albumentations as albu image_size = (336,336) class CropFaceParts(...
986,247
1d39e9ef564236927755decd997b899a5feb81de
from flask import render_template from mysite import app @app.route('/') @app.route('/index') def index(): title = 'mysite' user = { 'username': 'foosinn', } return render_template('index.html', title=title, user=user) @app.route('/conditionals') def conditionals(): logged_in = True ...
986,248
8d07752c569dd372e6f8c2db6bf74494410b9b5d
import sqlite3 books_file = 'books.txt' def create_book_table(): connection = sqlite3.connect('data.db') cursor = connection.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS books(name text primary key, author text, read integer)') connection.commit() connection.close() de...
986,249
c95d959fa498d389bc389c7bdc12e79a8e4d20b0
import nmap from pprint import pprint import time try: nm = nmap.PortScanner() result = None while True: tmp = nm.scan(hosts='192.168.4.0/24', arguments='--exclude 192.168.4.1') # print(tmp) if result == tmp['scan']: print("Nothing new") continue prin...
986,250
6c02d1a214efb0d649c1a43dd1affc899e8225dc
#!/usr/bin/env python import itertools from pathlib import Path import spacy import pandas as pd import pathlib from pathlib import Path from spacy.tokens import Doc, Token nlp = spacy.load('en') def safe_list_get (l, idx, default=0): try: return l[idx] except IndexError: return [0,0, 0] def bert_list_tes...
986,251
2a96320716faa96e2c34f0711d89e542b1765751
# -*- coding: utf-8 -*- """ Created on Thu Feb 12 14:48:31 2015 @author: timothy """ from __future__ import division import os, sys import numpy as np import pandas as pd from pandas.util.testing import assert_frame_equal, assert_almost_equal import pyideas # set working directory on super folder def test_multid...
986,252
706773e9681cfd5d3224d738c69bb80eaebdaaba
"""literaturetrackercadlab URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='ho...
986,253
2895e642917af717275b97f6f7971431e611d00f
import os import random # files FILE_TRAIN = "dataset/NLSPARQL.train.data" FILE_TEST = "dataset/NLSPARQL.test.data" TRAIN_FEATS = "dataset/NLSPARQL.train.feats.txt" TEST_FEATS = "dataset/NLSPARQL.test.feats.txt" #variables #base list word_list = [] iob_list = [] line_list = [] sentence_list = [] # lemma, pos list lp...
986,254
c24d02f3b3b389eb62d58e207d219db914060bc2
""" 修改changelog为特定格式 """ import re htmlextends = ['html', 'page', 'uientity', 'application'] clazzextends = ['java'] configextends = ['bo', 'svpkg', 'cmpt', 'xml'] def read_changelog(filename): file = open(filename, mode='r', encoding='utf-8') lines = file.readlines() reg = re.compile(r'\W*[AM]\W*(/.*\....
986,255
4650a3fe4d9fd3304f4475681b21267f41768fa3
import skimage import matplotlib.pyplot as plt import matplotlib import numpy as np import model def readImage(dir = None): # image = skimage.io.imread(dir) # 读取指定路径的图片 image = skimage.data.chelsea() # 对skimage自带的图片 image = skimage.color.rgb2gray(image) # 将彩色图片转为为灰度图片 return image dir = './cat.jpg' # im...
986,256
e453bfa8824aa7c4362abc3b1a9a946bc018d632
import re from dataclasses import dataclass ############# # Constants # ############# # allows to parse proc maps files _RE_MAPS = re.compile( r'^([0-9a-f]+)-([0-9a-f]+) ([rwxsp-]{4}) ([0-9a-f]+) ([^ ]+) (\d+)\s*([^ $]*?)$', flags=re.MULTILINE ) ########### # Classes # ########### @dataclass class Mappi...
986,257
9935d3878eb536e997c1c1a93cad8e01ad328c24
from django import forms # ?from apps.webscrapper.models import data from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.db import models from apps.webscrapper.models import Text,Image,Title,Index_Name,BackgroundImg class get_Title(forms.ModelForm): ...
986,258
c1e3da5e2dd9172f18dd25a83eca8839f2593e73
from tkinter import * import tkinter.font from gpiozero import LED import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) #define pins redled = LED(17) blueled = LED(18) greenled = LED(27) #define Gui win = Tk() win.title("Control LED Lights") myfont = tkinter.font.Font(family = 'Helvetica', size = 12, weight = "bold") #fun...
986,259
9ddcabe60877c04b5e3a0a2a33d69d9d0144e1a9
def incrementByOne(arr): ''' given an array of integers, increment each integer by 1 ''' for i in range(len(arr)): arr[i] += 1 return arr
986,260
c48776fde49553794c4921f94626173c1780839e
# 安装 # geoip2==2.5.0 # official MaxMind geoip2 package # https://geoip2.readthedocs.io/en/latest/#database-example import os import geoip2.database # 项目根目录 Base_DIR = os.path.dirname(os.path.abspath(__file__)) Base_DIR1 = os.path.dirname(__file__) print (Base_DIR) print (Base_DIR1) geoip_reader = geoip2.databas...
986,261
e175eadc17e24d085abbb7eb9a624d1d5383c605
def double(lst): '''1. a''' return [i * 2 for i in lst] def double(lst): '''1. b''' if not lst: return [] return [lst[0] * 2] + double(lst[1:]) def double(lst): '''1. c''' return list(map(lambda x: x * 2, lst)) def flatten(lst): '''2. a''' return [item for sub_lst in lst for item in...
986,262
e58f6d9c19b0a47ee9ddc0a5fb42efee12060e8d
############# # DEVELOPMENT ############# # where pictures are stored # DATA_FOLDER = '../data/' # # where SQL database containing users is # SNAPCAT_DB = DATA_FOLDER + 'snapcat.db' ############# # PRODUCTION ############# DATA_FOLDER = '/data/' SNAPCAT_DB = DATA_FOLDER + 'snapcat.db'
986,263
326736ba5b170f5b61f53b11660c22712fd9a9d1
from google.appengine.api import users from ferris import Controller, route_with, messages, add_authorizations, route from app.models.user.user import User from app.services.user_svc import UserSvc from protorpc import protojson import logging class Main(Controller): @route_with(template='/') def index(self)...
986,264
4e5ba40d10352dc39a0321da41419e24cb98cd74
from acky.api import ( AwsCollection, AwsApiClient, make_filters, ) from itertools import chain class EC2ApiClient(AwsApiClient): service_name = "ec2" class EC2(EC2ApiClient): def regions(self, continent='us', include_gov=False): # returns (string, ...) # DescribeRegions ...
986,265
4888780c69026df513d1cca0c412166505231bc1
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Ui_FabryPerot.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainW...
986,266
3289f2965a35980591595690d2006869d77925fe
N, K = map(int, input().split()) A_ans = [1 for i in range(N)] for i in range(K): d = int(input()) if d > 1 : A = list(map(int, input().split())) for j in range(len(A)): if A_ans[A[j]-1] == 1 : A_ans[A[j]-1] = 0 else: A = int(input()) if A_ans[A-1]...
986,267
d440925d58112c03b0ea2f84008462a40fbc95ce
# Import custom modules import ballot import keys import geth # Output a list of all the saved ballots def allBallots(showIndexes=False, showBallotDetail=True): # Get the saved ballots savedBallots = ballot.savedBallots(); # Check if there are any saved ballots if len(savedBallots) < 1: # No...
986,268
fa16c64ee21a4a7702243374b6969dfe44e52c38
import re instructions = [(line.split(" ")[0], line.strip().split(" ", 1)[1].split(", ")) for line in open('input.txt')] registers = {'a' : 0, 'b' : 0} i = 0 def execute(instruction, args, regs): global i if instruction == "hlf": regs[args[0]] /= 2 elif instruction == "tpl": regs[args[0]] *= 3 elif instructi...
986,269
de2f6b9f269a67e605f2be2e3d63851c8349201b
# from user import User #This is my attempt in inheriting from User class Customer(): def __init__(self, customerid, firstname, lastname): # User.__init__(userid, firstname, lastname, phonenumber) self.customerid=customerid self.customername=firstname + ' ' + lastname def getC...
986,270
971bc1c8ed92ff2428e071d04615ea4153f8f875
import os import sys import signal import threading import argparse import atexit from wsgiref.simple_server import make_server from gitgrapher import make_app HERE = os.path.dirname(os.path.abspath(__file__)) @atexit.register def goodbye(): sys.stdout.write('goodbye!\n') sys.stdout.flush() # args parser...
986,271
9029f614b6903eca2d238278bbac4a211f5fd503
# -*- coding: utf-8 -*- """ Created on Wed Apr 7 21:42:27 2021 @author: xl """ sA=input("sA:") sB=input("sB:") if sA in sB: print("子字串的判斷為:Yes") else: print("子字串的判斷為:No")
986,272
10a30a02ba90cc340bad36358d8d2cb0c315ce62
num = int(input('Enter the number upto which the sum is to be found:')) s=0 for i in range(1,num+1): s=s+i print('Sum of n integers') print(s)
986,273
4b8769ee8f10c7ed0aad590c741f73f48c59b26b
from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from PIL import Image import os import numpy as np import json import torch import torchvision.transforms as transforms from torchvision.utils import save_image from types import SimpleNamespace from ArtInspiredFashionHR.analysis....
986,274
21686a3adbe2ce1a019d160607f8fd6aca2bf623
from sys import argv, exit import cs50 # Check correct usage if len(argv) != 2: print("Usage: python roaster.py [house]") exit(1) # Open the database hogwarts_db = cs50.SQL("sqlite:///students.db") # Ask dbase for relevant info query = hogwarts_db.execute( """SELECT first, middle, last, birth FROM stude...
986,275
5afd0fcbfd5cd90701fd97c19bfe290f93473f14
"""Assumption - find mininum value in the tree def min(node): base -> if node is None: return float('inf') # Largest floating point infinite number generic-> leftmin = min (node.left) rightmin = min (node.right) return min(node.val, leftmin, rightmin) """ class BinaryTr...
986,276
2927a59b6ed06de174f1eaca8f846ff5f8e626f9
from django.db import models from api import file_upload_path_for_db # Create your models here. class Video(models.Model): videourl = models.CharField(max_length=1000, blank=True) title = models.CharField(max_length=200) threshold = models.CharField(max_length=20) tags = models.CharField(max_length=50...
986,277
4aceee264d7aeeebc1087da623a147576c09260d
#!/usr/bin/env python import rospy import numpy as np import cv2 as cv from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError class BlobsRellocation: def __init__(self): self.bridge = CvBridge() self.image_sub = rospy.Subscriber("/lepton_output", Image, self.callback) self.image_pub =...
986,278
ffd017d1d21b95441f7a1858ac24d1f5417e53e6
import mysql.connector from mysql.connector import Error try: myconn= mysql.connector.connect(host='localhost',user='root',password='H@ckmeifyoucan1',database='job_portal') mycur= myconn.cursor() mycur.execute("create table jobpost(application_id mediumint auto_increment not null PRIMARY KEY,role varchar(50),company...
986,279
2cb8efb1a857ee013bec2241ecd9b116a7673e27
digit = 1 #stringDig = "1" #count = 0 def nextDigit(): #global stringDig global digit #global count toReturn = "" #if not, increment digit, convert to a string and assign it to stringdig #if stringDig == None or len(stringDig) < 1: # digit = digit + 1 # stringDig = str(digit) ...
986,280
c2d54bee6b051d48b4da31dd85ea91d2693e2642
# Write a for loop which print "Hello!, " plus each name in the list. i.e.: "Hello!, Sam" lst=["Sam", "Lisa", "Micha", "Dave", "Wyatt", "Emma", "Sage"] for i in lst: print(f'Hello! {i}')
986,281
5b1cf02236c0b45f7aedb416cbaf8b0b976ebdd9
from django.urls import path from PendingWork.views import pendingwork_view,pendingwork_update_view urlpatterns = [ path('',pendingwork_view,name='add-pendingwork'), path('<int:id>/update',pendingwork_update_view,name='update-pendingwork'), ]
986,282
d93252b989f756657b2bdcdfa9970ca005028ea1
# -*- coding: utf-8 -*- class Masterpiece(): """Masterpiece is a collection of arts and reports generated by the artists using information about the model and the dataset Parameters: =========== artists: list list of :class:`Artist` objects model: :class:`Model` dataset: :class:`D...
986,283
7972df29091028119c58c58d030a94b30f84ee33
from datetime import datetime from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String, DateTime, Text from ._base import DeclarativeBase class Message(DeclarativeBase): __tablename__ = 'messages' id = Column(Integer, primary_key=True) world = Column(String(255)) message = Col...
986,284
2e6ac77e973e79d6735e4da774226aa37812f93f
import random import collections import numpy as np R, P, S = moves = range(3) move_idx = {"R": R, "P": P, "S": S} names = "RPS" beat = (P, S, R) beaten = (S, R, P) def react(my_loaded, opp_loaded, my_history, opp_history): if not opp_history: return random.randrange(0, 3) counts = [0, 0, 0] count...
986,285
86eb7114cd6611fce31580c349372ad9ba71d7e1
directions = [(0, -1), (1, 0), (0, 1), (-1, 0)] position = (12, 12) facing = 0 # directions index infected = set() with open('22.input', 'r') as handle: for i, line in enumerate(handle): for j, character in enumerate(line): if character == '#': infected.add((j, i)) count = 0 f...
986,286
f72dbb2e4ca703b96eb4b3d502c227a3d0125a0a
import uiautomation as automation from uiautomation import Win32API from uiautomation import WaitForExist, WaitForDisappear from PageObject import Notepad, Calculator import os from os.path import join, isfile import re current_dir = os.getcwd() def openProgramViaRunDialog(program): Win32API.SendKeys("{LWIN}{R}")...
986,287
924c95a82a7d7830229e4d7e22f222da9c97951e
#Exercício Python 14: Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit. c = float(input('Informe a temperatura em ºC: ')) f = ((9 * c) / 5) + 32 print(f'A temperatura de {c}ºc corresponde a {f}ºf')
986,288
c5149db7da989a978e309544e02cb99ff035716f
# Jianming Wang aka Yonner Ming from tkinter import * import math import random import time from nchoosekvisualization import nChooseKVisualization as vis # first level functions def init(data): data.cursor = 0 data.inputNames = ["Number of People", "Size of Subcommittee"] data.inputs = [8, 3] data.m...
986,289
6467a0823d4cf6e2745ca448c89ee4d2481b5688
''' 1. 完成一下步骤: (1) 在任意位置创建一个目录,如'~/小练习' (2) 在此目录下创建一个文件Blowing in the wind.txt      将以下内容写入文件 Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. (3) 在文件头部插入标题“The Zen of Python”...
986,290
82b6d0178ab9cfb191bffc98e71a77f1d161376a
from pushbullet import PushBullet, errors def push_to_iOS(title, body, pb_key): pb = PushBullet(pb_key) pb.push_note(title, body)
986,291
baa1d7a3730355051b077c44e488927b30897777
from os import environ BANANO_HTTP_PROVIDER_URI = environ.get( "BANANO_HTTP_PROVIDER_URI", "https://api-beta.banano.cc" ) PORT = environ.get("PORT", 7072) print(f"Using {BANANO_HTTP_PROVIDER_URI} as API provider on port {PORT}")
986,292
1ae40b276cad640c4e7bbc1eceb806e08ffee23a
# -*- coding: utf-8 -*- """ Created on Sun Nov 15 23:17:45 2015 @author: Maximus Pulling data from Youtube """ import json import urllib # https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Q5mHPo2yDG8&key=YOUR_API_KEY api_key = "AIzaSyCPGlBmzySKUuEId0C9GS0jrKZfArvSk6M" service_url = 'https://www.google...
986,293
e4ad1900c668b74d4777e46b74c060e94c13881a
from . import pos_voucher
986,294
a43635cf4ced232cfd049154642f4ae06c8afbbd
from src.module.deploy_utils import parse_war_path from commands import getoutput from log import LOG import utility def invoke(fingerengine, fingerprint, deployer): """ """ if fingerengine.service in ["jboss", "tomcat"]: return invoke_war(fingerengine, fingerprint) elif fingerengine.service...
986,295
147f4a99e5e5f874ba7303ea159ac0af362e9ba1
# Lint as: python3 # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
986,296
ba75ca97ad8cf44fd36879bd1d44d6a499a0bfbd
class Person: def __init__(self, name, age, contact, salary): self.name = name self.age = age self.contact = contact self.salary = salary def get_name(self): return self.name def get_salary(self): return self.salary jon = Person(name="Jon", age=24, contac...
986,297
af9415a06e117144255881b818b1123cb7bc3806
#!/usr/bin/env python from random import randint class Tile(object): def __init__(self, safe, rollagain): self.safe = safe self.rollagain = rollagain self.piece = 0 class Player(object): def __init__(self, player, path): self.player = player self.path = path se...
986,298
d6946b142be2b6b452d3693997913f34a06ab6ef
from .rdm_plot import show_rdm, show_rdm_panel, add_descriptor_x_labels, add_descriptor_y_labels from .mds_plot import mds, rdm_dimension_reduction from .model_plot import plot_model_comparison from .icon import Icon from .icon import icons_from_folder
986,299
f19d2b974904edfd508aa8bbe9bb47e19bb9ddf6
import RPi.GPIO as GPIO import io import logging import subprocess import shared_cfg MODE_SWITCH_SCRIPT = "/home/pi/switch-mode.sh" # TFT buttons; button 1 is left-most TFT_BUTTON_1_PIN = 11 # GPIO17 TFT_BUTTON_2_PIN = 15 # GPIO22 TFT_BUTTON_3_PIN = 16 # GPIO23 TFT_BUTTON_4_PIN = 13 # GPIO27 # Encoder inpu...