index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
998,500
e2602f4e588ae2ab5c122859952db6ad5c3b14f0
from django.shortcuts import render import requests from geopy.geocoders import Nominatim from .forms import CityForm from .models import City from django.views.generic import DeleteView, TemplateView from django.urls import reverse_lazy import datetime import json class IndexView(TemplateView): template_name = '...
998,501
ef1112baa8bd2bb3f58eaaef043e3154185ead9b
# coding=utf-8 # Загружает список кортежей (id, date, status) из csv-файла class CycloneCsvFileReader: def __init__(self): pass def read(self, file): for line in file.readlines(): parts = line.rstrip().split(',') # Уберем завершающие переносы строк. Правда rstrip еще и пробелы уд...
998,502
dde7dc221cf8003029858e808364d73306510e6a
import csv class Reader(object): """ Generic Reader class for processing input. Should be subclassed instead of used directly. """ def __init__(self, filename): self.filename = filename return self.process() def process(self): # Override in subclass. pass
998,503
9b4659399eae71e48bd2f4bea88766550f65506f
#!/usr/bin/python numbers = [12, 45, 78, 20] sum = 0 for number in numbers: sum += number print "The sum is:", sum sum_while = 0 index = len(numbers) while index > 0: index -= 1 sum_while += numbers[index] print "The sum_while is:", sum_while
998,504
4716fe2cdd05028a50dd27df735109477d2206a5
from sklearn import svm from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score import numpy as np import sys from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import MLPClassifier def prediction(train, test): feature_num = parse_feature_num(train,0) f...
998,505
5ba1b6bf8bfb9cdde177ba5df87f309605ddf7d4
# Даны два целых числа m и n (m≤n). Напишите программу, которая выводит все числа от mm до nn включительно. m = int(input()) n = int(input()) for i in range(m, n + 1): print(i)
998,506
de2a370a6d69ed38e449c48e8201a4c4d9185f5f
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
998,507
1e95c6c80fbb22f49582f8956b9debb9f1c7deb8
class Unit: MINUTE = "minute" HOUR = "hour" SECONDS = { MINUTE: 60, HOUR: 3600, } @classmethod def seconds(cls, unit): return cls.SECONDS[unit]
998,508
d2903b0943f54d1eaeb6e5bf35823749fd349103
"""request_tracker Revision ID: 86d8aca36208 Revises: 40015e4aa4f5 Create Date: 2022-04-25 14:55:03.076474 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '86d8aca36208' down_revision = '40015e4aa4f5' branch_labels = None depends_on = None def upgrade(): #...
998,509
a0a562a1ccd2fd1dd8d58d6caefc6bc0f9ff406c
# 给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。 # # 按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下: # # "123" # "132" # "213" # "231" # "312" # "321" # 给定 n 和 k,返回第 k 个排列。 # # 说明: # 给定 n 的范围是 [1, 9]。 # 给定 k 的范围是[1, n!]。 # DEMO: # 输入: n = 3, k = 3 # 输出: "213" # 示例 2: # # 输入: n = 4, k = 9 # 输出: "2314" import math class Solution: def ...
998,510
5aace31734df412e86f59b824ea914201918d8a3
from typing import List import ghidra.program.model.address import ghidra.program.model.data import ghidra.program.model.listing import ghidra.program.model.mem import java.lang class MSDataTypeUtils(object): """ An abstract class containing static utility methods for creating structure data types. """ ...
998,511
bf97395ead523744e6fb03ff3b5305f86e744b3f
import sys fname = sys.argv[1] outfname = sys.argv[2] fin = open(fname) fout = open(outfname, 'w') for line in fin: # A9:ALA:CB A7:VAL:CB 8.45181 bufferline = line.split() res1 = bufferline[0].split(':')[0] res2 = bufferline[1].split(':')[0] if res1 == res2: # meaningless to define linkage with self continue #...
998,512
123a65ee9a30318b4f101dc5c2fbd8b9e6b51b26
from django.conf.urls import patterns, include, url urlpatterns = patterns('cursom.apps.home.views', url(r'^$', 'index', name="index"), url(r'^agregar/', 'agregar', name="agregar"), url(r'^actualizar/(?P<id_p>.*)/$','actualizar', name="actualizar"), )
998,513
766972e47671acd58e86aec8d20446060d2f1ea7
# -*- coding: utf-8 -*- """ CPP文件简单封装,用于生成cpp文件. """ from os import path as op from time import time, localtime, strftime class CppFile(object): def __init__(self, fpath, author='Unknown author', ver='1.0', doc='', include_macro_prefix=None): self.__fpath = fpath self.__author = author se...
998,514
032bacb26f207cf152333ce99c1516fecd503cc2
# Generated by Django 3.0 on 2019-12-22 21:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('drive', '0006_auto_20191222_2029'), ] operations = [ migrations.AlterField( model_name='file', name='storage_name', ...
998,515
12b77e6e199c11ceced48d649e13bdb4c37857d1
import scrapy from scrapy.loader import ItemLoader from ..items import CmbmcItem from itemloaders.processors import TakeFirst class CmbmcSpider(scrapy.Spider): name = 'cmbmc' start_urls = ['https://www.cmb.mc/en/our-latest-news/'] def parse(self, response): post_links = response.xpath('//a[text()="Read more"]/...
998,516
bb83b28d28a09be2cc85f6c4c0cae981d5937b23
class Solution: def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ res = [-1,-1] n = len(nums) if target in nums: res[0] = nums.index(target) res[1] = n-nums[::-1].index(target...
998,517
0a0d551283dff0eb6019180a6568fa263c9d6c71
from django.contrib import admin from .models import * # Register your models here. admin.site.register(Department) admin.site.register(Employee) admin.site.register(DeptEmp) admin.site.register(Title) admin.site.register(Salary) admin.site.register(DeptManager) admin.site.register(logs)
998,518
9575bb6514814996595a1d2698d6dab356616461
def city_country(city,country,population=0): message=city+","+country if population: message+= '-population '+str(population) return message
998,519
0aa3b1be198bc0c1a9b92230fcd532f7bb880346
import commands import string class sshSessions: def __init__(self): self.netgroups = [] self.processes = [] def getComputers(self): temp = [] linuxLogin = commands.getoutput("netgrouplist linux-login-sys") csServer = commands.getoutput("netgrouplist cs-server-sys") ...
998,520
415801d8f46095b5850a2ec51b0dec2a8f734330
# Generated by Django 3.2.6 on 2021-08-31 08:36 from django.db import migrations, models import tinymce.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Banner', fields=[ ('i...
998,521
81e9528bfa94ceb82bc210f1d8322d67e1298b63
## Chapter about files and exceptions with open('pi_digits.txt') as file_object: # The keyword with closes the file once access to it is no longer needed contents = file_object.read() line = contents.rstrip # rstrip prevents from printing a blank line ## "with open('text_files/filename.txt') as file_object:" i...
998,522
d40f7c5a7cb29938d13522a0c5693c23f8e72721
#2단에서 9단까지 for y in range(2,10): print("%d단" % y) for x in range(1,10): print("{} X {} : {}".format(y, x, y*x)) print("") #홀수단짝수 num = int(input("1을 입력하면 홀수단이, 2를 입력하면 짝수단이 출력됩니다 :")) if(num == 1): for y in range(2,10): if y%2 == 0: continue for x in range(1,10): ...
998,523
d33b0926ba0b6463d6b2b6106a63020859a02484
# Lab 6 Softmax Classifier import tensorflow as tf import numpy as np from neural_network import NeuralNetwork from nntype import NNType from neural_network_one_hot import NeuralNetworkOneHot class XXX (NeuralNetworkOneHot): def init_network(self): self.set_placeholder(16, 1) self.target_to_one_h...
998,524
ce1d0a13f4816b543570d0adde77b0dae1b209eb
with open('input.txt', 'r') as f: moves = f.read() sx = sy = 0 rx = ry = 0 grid = {(0, 0): 2} directions = {'^': (0, 1), 'v': (0, -1), '>': (1, 0), '<': (-1, 0)} def compute_location(x, y): location = (x, y) if location not in grid: grid[location] = 1 ...
998,525
2aae4bfd954fdb2c9349acb5155d78290eb76683
from .settings_base import * DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] STATICFILES_DIRS =[BASE_DIR/'react/dist'] CORS_ALLOWED_ORIGINS = ( 'http://localhost:3000', "http://127.0.0.1:8000", "http://localhost:8000", "http://localhost:8000", "http://0.0.0.0:8000", ) DATABASES = { 'default': ...
998,526
beabefe45f4e9efdcc9c4cec2c99c6d80af04b9a
[ 'acorn squash', 'alfalfa sprouts', 'anchovies', 'apple', 'apples', 'artichoke', 'arugula', 'asparagus', 'aubergine', 'avocado', 'bacon', 'baking powder', 'baking soda', 'baking sugar', 'bar sugar', 'basil', 'beans', 'bell peppers', 'blackberr...
998,527
be61320a11a459807ff1b2badd995ef6597beeb6
# Generated by Django 2.0.2 on 2019-02-01 01:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('store', '0007_pub_name'), ] operations = [ migrations.AlterModelOptions( name='contact', options={'verbose_name': 'Contact',...
998,528
0b0d1d2bf463f0c99621b26c47c7c5734ad03628
import matplotlib import matplotlib.pyplot as plt import chess import chess.svg import chess.pgn #from IPython.display import SVG pgn = open("C:/Users/Aryan Anand/Documents/12323.pgn") # n = 1 # print(n) for i in range(1, 3): act_game = chess.pgn.read_game(pgn) print(act_game.headers["Event"] + " | " + act...
998,529
ec4b04a4f129abe5ce95691cbfe0d60fd48632d2
from __future__ import unicode_literals def test_push(session): # We use a temporary created RAG widget if you need to re-record # this: # # Set GECKO_RECORD_MODE=once and GECKO_API_KEY to a valid api key # # Remove the tests/casettes/test_session.test_push.json casette # # Set widget ...
998,530
5473130c423bf6fd0274a2481bdd0bd0114fa3d5
#!/usr/bin/python3 from PySide2 import QtCore, QtGui, QtWidgets from loadconfigs import getStyle from reimplemented import Buttons, HOVER, DEFAULT from menu import MyMenu class Interface(QtWidgets.QWidget): STYLE: str = getStyle() XX: int = 0 def __init__(self) -> None: super(Interface, self)._...
998,531
50bd94618d2e2b359dd4ab79cf3b3539ff2c049d
# # @lc app=leetcode id=905 lang=python3 # # [905] Sort Array By Parity # # @lc code=start class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: odd = [] even = [] for ele in A: if ele & 1: odd.append(ele) else: even....
998,532
539e4e378a35db41b97b31b4f97650d8bb9120f6
import time import utils.encryption from utils.encryption import AESCipher class DbBeaconAPI(): def __init__(self, mongo_db_connector): self.mongo_db_connector = mongo_db_connector self.config_comparison_fields = self.get_field("config comparison") self.maintenance_field = self.get_fi...
998,533
a4472737ed5d65eb67b89c2d4e49534ae643976d
#! /usr/bin/python ''' This script takes the tables of miRNAs identified with miRBase and puts them into one long list and also makes a fasta file out of them that can be used to align/compare with. This script collapses samples (output has no duplicates) and numbers of reads are converted into percentages (from the c...
998,534
1e86f2bd3f9df376c49b0f7de469b86283080c7e
# # Copyright (c) 2004-2006 # Andreas Kloeckner # # Permission to use, copy, modify, distribute and sell this software # and its documentation for any purpose is hereby granted without fee, # provided that the above copyright notice appear in all copies and # that both that copyright notice and this permission no...
998,535
73b2fc4d39095506acc1af5248359ceeee29ad23
if __name__ == '__main__': print('Review your code') else: print('Your are not in the correct folder location to run this test')
998,536
cf52d7f295629ea28009ae9f5ee98f8375979718
import math import sys import Image import ImageOps import ImageChops import matplotlib import numpy as np import matplotlib.pyplot as plt import numpy.fft as fft from numpy import cos from pylab import imshow from matplotlib.gridspec import GridSpec from global_contrast import * from histogram_equalize import * d...
998,537
049969593ac3dc3cc10db5ac27a50a937645183c
from pulp import * import time budget = int(input("Введите Ваш бюджет на рекламу:\n")) # 10000 бюджет на рекламу minuteTV = int(input("Сколько стоит минута рекламы на ТВ?\n")) # 90 д.е. минута рекламы на ТВ minuteRad = int(input("Сколько стоит минута рекламы на радио?\n")) # 5 д.е. минута рекламы на радио effect = int...
998,538
be63e1f44a67706210ab667b70dfe5eeb7536880
from pyspark.sql import SparkSession from pyspark.sql.functions import col from pyspark.sql.types import BooleanType # create spark session spark = SparkSession.builder\ .appName("Github push counter")\ .master("local[*]")\ .getOrCreate() # spark context sc = spark.sparkContext # load json file filePa...
998,539
5d9fdd13cca9a2e5119727bdeb8a4b60236f5c81
print('Content-Type:text/html \n\n') print("hell word")
998,540
cbc324755363028d8737c00b2f4a4e7374812dea
#!/usr/bin/env python3 # # (c) Yoichi Tanibayashi # """ ytbg.py """ __author__ = 'Yoichi Tanibayashi' __date__ = '2020/05' from ytBackgammonServer import ytBackgammonServer from flask import Flask, request from flask_socketio import SocketIO import json from MyLogger import get_logger import click CONTEXT_SETTINGS =...
998,541
b8275d37ff12e34d7a64b3f7cf4fc241ccd19070
import numpy as np import sys N,M =(map(lambda x : int(x),sys.argv[1:])) while not(N>=3 and 0<=M<=7): if N<3 : print '\'n\' must be Greater than or equal to 3' if 0>M or M>7: print '\'m\' must be between 0-7' print '\ninput n and m again' N=input("n = ") M=input("m = ") print "\n---------------------------...
998,542
2669d64ab7bf0dc2b7f5a0cf14128fa98bc58ac8
from flask import Flask, render_template, flash, redirect, Response, request, session, abort, url_for from ast import literal_eval from base64 import urlsafe_b64encode as encode from base64 import urlsafe_b64decode as decode import ldap import sys, json, ast, crypt import os import re import itertools from flask import...
998,543
22b6f4aca38722a00e641dbce7a3630fd3b51a53
A=input("nantwat na nan") print(A)
998,544
c41990ae36297184e41d5c35c085c0d135f240f9
__author__ = 'gustavo' x = 2 if x > 2: print 'Maior que 2' else: print 'Nao eh maior que 2' if x == 2: print 'Igual a 2' else: print 'Diferente de 2'
998,545
de37d707487e37047b51683e82bb4b2c3bcc6775
# Challenge 1: Name the variable types of the following variables. Print them out into console in the format "Variable: Variable Type" (might have to google "how to print variables in python") integer = 3 string = "Mr. Mortensen" character = 'f' float = 0.4 print(integer, ": Variable Type", type(integer)) print(string...
998,546
6ca5d8f13b6c6a2fe49f39f9ab8db4bb99540f18
#!/usr/bin/python # # $Id: reader_hicom300.py,v 1.6 2012-02-24 20:53:25 sshevtsov Exp $ # # Este script es utilizado para levantar los datos del puerto serie # al cual esta conectada la central hicom300. # # La configuracion del pueto esta definida en y explicada en el archivo # serial_conf.py # # Las demas confi...
998,547
84d8b37758940194cf2615cf38ca6d51e3ab7169
""" author: Zituo Yan description: this starts the verification part date: 3/2/2020 """ from gedcom_app.control.child_birth import birth_before_marriage from gedcom_app.control.US0203 import birth_b_marriage_us02, birth_b_death_us03 from gedcom_app.control.US1217 import parents_not_too_old_us12, no_marriag...
998,548
8a6c46ba5ead05c59515879560ae500bec45639a
import requests import json #The URL to be used the base baseUrl = "http://fasttrack.herokuapp.com" #The main function to make the calls to the x amount of pages def fetch(link): headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} r = requests.get(link, headers=headers) jsonRespon...
998,549
d527323f8f2056174d4841eaa6f888663727afbc
# -*- coding: utf-8 -*- import unittest from ..utils.Helper_validate import Validate, RegType class ValidateHelperTestCase(unittest.TestCase): def test_validate_check_APP(self): self.assertTrue(Validate.check("app", reg_type=RegType.APP)) self.assertFalse(Validate.check("abpp", reg_type=RegType.A...
998,550
192091870c9d3b228fd61bc1522f8c7838d81724
#Solve the same problems with enumerate and numpy import numpy as np def gc_skew(seq): skew_dict = {'A': 0, 'T': 0, 'C': -1, 'G': 1} skew_list = [0] #Define first value as 0 for pos, val in enumerate(seq): skew_list.append(skew_list[pos] + skew_dict[val]) return skew_list def minimum_gc_skew(...
998,551
c98dca771cc6088f3cdf41a2b6cd1bb710afdc73
# Generated by Django 2.0.3 on 2019-03-04 19:49 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('banners', '0016_auto_20190304_1924'), ] operations = [ migrations.RenameField( model_name='bannerupdate', old_name='message'...
998,552
63bf545ab8d57ac8c71e2c204c3f5830ddb0d41c
import eliminacaoGaussPivoParcial as ep def matriz(x, grau): matriz = [] vet = [] n = len(x) for j in range(0, n): for i in range(0, (grau+1)): vet.append(x[j]**i) matriz.append(vet) vet = [] return matriz def main(): #Valores de Entrada x = [0.1, 0...
998,553
e439fd3063738ee84f06ecf6fc6b6d16a8c416a6
from cctpy import * if __name__ == "__main__": DL2 = 2.1162209 GAP3 = 0.1978111 QS3_LEN = 0.2382791 QS3_GRADIENT = -7.3733 QS3_SECOND_GRADIENT = -45.31 * 2.0 QS3_APERTURE = 60 * MM big_r_part2 = 0.95 CCT_APERTURE = 80 * MM small_r_gap = 15 * MM small_r_innerest = 83 * MM ag...
998,554
7a96c2a1eafcd19a1d5235860a501f0330ec49d5
from common import * imgsz=(2048,)*2 r,a=meshgrid_polar(imgsz) im=np.float32(np.uint8(np.log(1+r)*4%2)^np.uint8(np.sin(a*16)>0)) im2=im def draw(t=0, **kwargs): # fast box blur: for n in (19,): for axis in range(2): im2=sum(np.roll(im2,i,axis) for i in range(-n//2,(n+1)//2)) im2/=...
998,555
afa1bfe136d84fbd9978b35f9e03c246922afff3
# You are given a 2d matrix and int (maxSum). You need to return the size of maximum square possible in this 2d array whose sum of all elements is less than equal to maxSum. # Eg: # input array: # 1 2 3 4 5 # 8 9 9 9 7 # 6 1 2 1 8 # 1 1 1 1 9 # 9 1 1 1 20 # input maxSum = 10 # output = 3. # Explaination; following ...
998,556
9b6505178f363060c0beea36dd1aabe7d64c88ce
#Code to write bash script that generates grids based off of the input files made by grid_in.py method = 'TICA' #clustering method dock = 'SP' #docking method with open('gen_grids.sh','w') as newfile: for num in range(10): newfile.write('$SCHRODINGER/glide /scratch/jegan/GLIDE_'+dock+'_core_docking/'+met...
998,557
fd5e0d4939b7e0fe813577190b5861a02b51ec3a
from flask import Flask, render_template, redirect, request, jsonify, url_for, flash from database import Base, User, Book from sqlalchemy import create_engine, asc from sqlalchemy.orm import sessionmaker #Imports for anti-forgery state token from flask import session as login_session import random import string fro...
998,558
049b1a371324e15ec5d164188abe5b632f3bfcb6
R = Recipe() R.name("Flapjack") R.ingredient(200, "g", "margarine") R.ingredient(200, "g", "brown sugar") R.ingredient(2, "tablespoons", "golden syrup") R.ingredient(1.5, "teaspoons", "ginger") R.ingredient(280, "g", "oats") R.do("Heat everything apart from the oats in a pan.") R.do("Add oats to the melted ingredie...
998,559
4ea4d6043677c3983bcadada11f47d026759ddc5
# -*- coding: utf-8 -*- """ 使用者上传的资源 """ import image import richtext_image import document
998,560
8a59ae2a5905386552843adb266be7fb830165fc
import os import sys class File_Handler(object): """docstring for File_Handler.""" def __init__(self): super(File_Handler, self).__init__() def mainloop(self): print("\nFile Handling application. What do you want to do?") print("1. Create file\n2. Read file\n3. Write to f...
998,561
00cebf8c873c9bfe118d80b5957367e02e7a3aa6
# -*- coding: utf-8 -*- import math #define PI 3.1415 #复数类 class complex: def __init__(self): self.real = 0.0 self.image = 0.0 #复数乘法 def mul_ee(complex0, complex1): complex_ret = complex() complex_ret.real = complex0.real * complex1.real - complex0.image * complex1.image complex_r...
998,562
cfb8c5f1c0778047db026b97702d6b0702875934
# -*- coding: utf-8 -*- """ Created on Wed Jan 15 21:00:08 2020 @author: erfan pakdamanian """ # STEP1----------------- # Importing the libraries------------ #------------------------------------------------------------- import os import numpy as np import matplotlib.pyplot as plt import pandas as pd impor...
998,563
43aba4225cd8441c7c0b609cc956beb1e87a4c80
from rest_framework import serializers from battles.models import Battle class BattleSerializer(serializers.ModelSerializer): class Meta: model = Battle fields = '__all__'
998,564
69d308b006181ca95f42ce74d1037fc5517715e4
from django.shortcuts import render from .models import Employee from .forms import EmployeeForm def form_view(request): form = EmployeeForm() if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): form.save() return render(request,'GitApp/g...
998,565
c4a994bdc335290ca85cee0798799069588e257f
import cv2 from LBP import LocalBinaryPatterns import os import pickle from sklearn.model_selection import train_test_split import numpy as np from matplotlib import pyplot as plt from tqdm import tqdm from matplotlib.patches import Rectangle def get_features(paths, dataset_faces, desc): data = [] num_paths =...
998,566
03c2435746b4f16a87a81fda575cbdfab95b072a
from keras.applications import ResNet50 from keras.preprocessing.image import img_to_array from keras.applications import imagenet_utils from PIL import Image import numpy as np from io import BytesIO import os import requests model = ResNet50(weights="imagenet") layers = dict([(layer.name, layer.output) for layer in...
998,567
50fe996ffcfbfc924e0bf6d0e0ed082cc2dc4015
import datetime as dt from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator from airflow.utils.dates import days_ago def start(): import time def initializing(): time.sleep(5) print("Done") initializi...
998,568
fc73c2a25b76950c4a32cc0929ed654bffd9b391
import argparse import os import decryption_impl class Decrypter: def __init__(self, logs, key_file, code_book): self.key_file = key_file self.code_book = code_book self.logs = logs @staticmethod def read_file(logs) -> str: with open(logs) as file_contents: __...
998,569
76cbdac6016df5b005bbe86a1134bae8cfe6fe65
""" Auto Encoder. """ import torch.nn as nn class Model(nn.Module): """ Classify genres. """ def __init__(self, config): super().__init__() (genre_size, hid_dim, drop_rate) = (config['args']['genre_size'], config['args']['hid_dim'], ...
998,570
9dd31c4eb1992ec0d92bf42c206d09f76c223faa
from subtitle.generic import Style class WebVTTWriter(object): def write(self, captions, f): f.write('WEBVTT\n') for c in captions: f.write('\n{} --> {}\n'.format(c.start, c.end)) f.writelines(['{}\n'.format(l) for l in c.lines]) class SRTWriter(object): def write(s...
998,571
123b2f97dec08c275b383502b01f8473afa34c8c
# edx analytics fetcher import sys import json import math import urllib import requests import pandas as pd import dns import copy import time import datetime from http.cookies import SimpleCookie from pymongo import MongoClient from datetime import datetime # NOTE -- # -> You will need to sometimes update the foll...
998,572
b7393c1d2ea22b31f5e08970857cd9125498e1af
t = int(input()) for _ in range(t): n, k = map(int, input().split()) mx = 0 stair = (k**2 + k) // 2 for i in range(1, n + 1): if i**2 > n: break if n % i: continue for d in (i, n // i): if stair * d <= n: mx = max(mx, d) if ...
998,573
094d94bc078b617fd0a3751eacac47c6ab3e7087
import difflib from nltk.tokenize import word_tokenize def handle_taxpayer(result): txt=result[result.lower().find('taxpayer ')+9:] tokens=word_tokenize(txt) name="" used=[] names=[] skip=0 for token in tokens: i=0 while i < skip: i+=1 continue ...
998,574
0747a732af6a54a1d18b1b9f8ecbebfcc9820c74
# Generated by Django 2.0.7 on 2018-08-18 01:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('clients', '0002_auto_20180817_1526'), ] operations = [ migrations.RenameField( model_name='branch', old_name='...
998,575
3cebf901889f06bb616d63cfcc384b1384c816b8
#https://developers.google.com/edu/python/regular-expressions import re #find the pattern start word with Anu str1 = "Anubaig" match = re.search(r'^Anu\w+',str1) print match.group() str2 = 'Anumogal' match = re.search(r'^Anu\w+',str2) print match.group() str2 = 'numogal' match = re.search(r'^Anu\w+',str2) if match:...
998,576
0d2346fa931a75c794bd9008f61ec6c1be10ad59
symbol_table = None temp_var_set = set() counter = 0 curr_class = None members = [] func_members = []
998,577
fc3890d8bc0375aa901396cf5efc6248bb3df674
''' Created on 2016. 3. 3. @author: jayjl ''' from Parser.models import XpathData, XpathInfo, EtfInfo, EtfData from Parser.util.htmlParser import htmlParser def convert(val): lookup = {'K': 1000, 'M': 1000000, 'B': 1000000000} unit = val[-1] try: number = float(val[:-1]) except Va...
998,578
0c4917eb14ed4400818350ad4f621d7e0ee25190
from app.community import community_blueprint from app.community.forms import NewCommunityForm, UpdateCommunityForm from app import db from app.models import Community, CommunityParticipant from flask import render_template, redirect, url_for, flash, abort from flask_login import login_required, current_user from app.c...
998,579
fef864d818e8ffdc8a0ae913e608abbfd953a27a
""" Check if a given binary tree is perfect or not """ class Node: def __init__(self, val): self.val = val self.left = None self.right = None def find_depth(node): d = 0 while node: d += 1 node = node.left return d def is_perfect_util(roo...
998,580
aa5c8212e5a387713392fd12ed3eae71e9feefbc
from django.urls import path from . import views urlpatterns = [path('', views.homepage,name="homepage"), path('canceled/',views.canceled, name="canceled"), path('place-order/',views.order_create, name="order"), path('<url_generator>/link/<link>', views.link, name='...
998,581
abc1e3365ac30bd4c6739afabb2f47431288397d
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: chirpstack-api/as_pb/external/api/deviceProfile.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf imp...
998,582
c8469c324b7b65f8bfcaf02ea14948f13e77546d
import time import cv2 as cv import numpy as np from main import Main class CreateRectange(): def __init__(self, imagePath, windowName, imread_method=-1, save=False): self.imagePath = imagePath self.windowName = windowName self.x_array = [] self.y_array = [] self.count =...
998,583
e0974752ef36086abc6149729494bec357d3e308
import torch import numpy as np from typing import List from collections import namedtuple from rlpyt.utils.seed import make_seed from rlpyt.utils.quick_args import save__init__args from reward_poisoned_drl.utils import list_to_norm, flatten_lists ServerOptInfo = namedtuple("ServerOptInfo", ["numValidGrads", "meanG...
998,584
5047122f4c37a988fb1ba490eb69dd5bf28cc711
#!/usr/bin/env python # encoding=utf8 """Personal BGG Ratings.""" import argparse import re import sys from datetime import date from functools import cmp_to_key from operator import itemgetter import requests import requests_cache import xmltodict import pandas from dateutil.relativedelta import relativedelta sys....
998,585
746b496ffc541d5f7e45065d76a2c4f7fdba2a49
#!/usr/local/bin/python import clusters blog,words,data=clusters.readfile('blogdata.txt') coordinates = clusters.scaledown(data) clusters.draw2d(coordinates, blog, jpeg='blogs.jpg')
998,586
dfa3f3b033f360bd2c4e5b76e28405941aee72f7
from django.shortcuts import render import spotipy from spotipy.oauth2 import SpotifyClientCredentials # Create your views here. def index(request): if request.method=='POST': artist_uri=request.POST.get('uri') spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(client_id='...
998,587
86308b443fd428fa5ea431b9f0d8c10d0051e704
import matplotlib.pyplot as plt import matplotlib.path as mpath import matplotlib.patches as mpatch import numpy as np import string file = open('data.txt','r') x = [] y = [] while 1: line = file.readline() if not line: break data = string.split(line) x.append(string.atof(data[0])) y.append(string.atof(d...
998,588
6d3bd26aae00e05edd4e9d60864b87cdeef3045b
#!/usr/bin/env python import numpy as np import logging import itertools keys=[ "Length:", "Trace:", "Norm_1", "Norm_Frobenius", "Norm_Infinity", "Memory:", "Memory_Relaxation_icntl14", "Nonzeros:", "NonzerosAfterAnalysis_20", "NonzerosAfterFactorization_29",...
998,589
f780e8ccbeb616f7a58b4386ec4141f82dbfd2c3
# This example show how to use inline keyboards and process button presses import telebot import time import emoji import mysql.connector import requests from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton TELEGRAM_TOKEN = '1607683994:AAGotYV7rp5cixLimS33rr0P1ir3-BBm6es' db = mysql.connector.connect(h...
998,590
5d1bafb0b905e33c86ed6e5dabbd063c6ef61c10
import smtplib from email.message import EmailMessage email_content = '''Dear Sir/Madam, I am sending you an e-mail with Python. I hope you like it. Kind regards, David ''' email = EmailMessage() email['Subject'] = 'Test email' email['From'] = 'dcorvaisier8@gmail.com' email['To'] = 'dcorvaisier8@gmail.com' email.s...
998,591
e926e6c13731028dc48f90531477d1ffbcc9d7aa
class CanaryMiddleware: def __init__(self, app): self.app = app def __call__(self, environ, start_response): environ['repoze.debug.canary'] = Canary() return self.app(environ, start_response) class Canary(object): pass def make_middleware(app, global_conf): """ Paste filter-ap...
998,592
f0fd4b1f8b21ba0abaf5875ffe62d796da8a92e4
# code: utf-8 # python2 import mysql.connector, os, tarfile, shutil, quick_clone.util as util def execute(user, password, host, port, database, dir, tables): # ensure path contains forward slash if dir[-1:] != "/": dir += "/" if not os.path.isdir(dir): print "ERROR: File Location does no...
998,593
22c984cd081d5f57da24aae5d9be777f4ed585d4
import unittest import os from src.disjoint_set import DisjointSet class disjoint_set_tests(unittest.TestCase): def test_not_connected_when_set_is_empty(self): s = DisjointSet() self.assertFalse(s.is_connected(1, 2)) self.assertFalse(s.is_connected(2, 3)) def test_not_connected_when_...
998,594
82bb8ca46eb1a08baf68ee81bf63723f1f5a355f
from onegov.onboarding.models import Assistant def test_assistant(): class FooAssistant(Assistant): @Assistant.step() def first_step(self, request): return {'step': 1} @Assistant.step() def second_step(self, request): return {'step': 2} @Assistan...
998,595
319a2c4831c9c76e29bc153f6b15db21bf9ad64b
from django.apps import AppConfig class TicktockConfig(AppConfig): name = 'ticktock'
998,596
e88f50a3d9f2adc515f7fa75c4e8532a45948f54
class SampleClass: @classmethod def shout(cls): print("I was called!")
998,597
d21e188cfdf19adab2861264139c3534550cd1a0
import tkinter as tk import tkinter.ttk as ttk from tkinter.scrolledtext import ScrolledText from src.UnoServer import UnoServer from src.ChatServer import ChatServer from src.PingServer import PingServer import threading RECV_BUFFER = 1024 # Main part of the app. Handles transition from the connection window to the ...
998,598
cd455ac72651af481f2048aec0498f863305e7b2
import torch from torch.autograd import Variable import torch.nn as nn import math import numpy as np import torch.nn.functional as F class MultiBatchNorm(nn.Module): def __init__(self, dim, types, num_features, momentum=None): assert isinstance(types, list) and len(types) > 1 assert 'base' in type...
998,599
cee2e72e424ec03385791f58376e15eba580f9a6
from collections import defaultdict n = input() a = map(int, raw_input().split()) cnt = defaultdict(int) for x in a: cnt[x] += 1 res = 0 for i in xrange(11): if i == 0: res += cnt[i] * (cnt[i] - 1) / 2 else: res += cnt[i] * cnt[-i] print res