index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
984,200 | 6337656a9c8285bac898c1fb96a0b64cef68bb4e | # This file is generated by objective.metadata
#
# Last update: Thu Dec 15 21:00:16 2022
#
# flake8: noqa
import objc, sys
from typing import NewType
if sys.maxsize > 2**32:
def sel32or64(a, b):
return b
else:
def sel32or64(a, b):
return a
if objc.arch == "arm64":
def selAorI(a, b):
... |
984,201 | 6ecd64aa3b66928a3bd75e13a0248f6512dcefd2 | """
2027. 대각선 출력하기
주어진 텍스트를 그대로 출력하세요.
[Test]
입력
출력
#++++
+#+++
++#++
+++#+
++++#
"""
s = '#++++'
for i in range(5):
print(s[-i:]+s[:-i])
|
984,202 | b530cb321b42cefe19d71492094d54b65be42c93 | # mpi finds the sum of a list
from mpi4py import MPI
import random
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
def createList(size):
numList=[]
for element in (range(size)):
numList.append(random.randint(0, size))
print(numList)
return numList
def sumOfList(size):
result = 0
numLi... |
984,203 | acd9220838b8ed84ddba91324ccad2136d3d901e | import volar, pprint, ConfigParser, unittest
class TestThoroughBroadcast(unittest.TestCase):
"""
Tests the ability to connect to the CMS via, hopefully, valid credentials.
"""
def setUp(self):
# load settings
c = ConfigParser.ConfigParser()
c.read('sample.cfg') #note that this file is only for use with thi... |
984,204 | d35aef60d841d37795f5fa1d04b336d38ffda328 | def counter(lst,Dict):
if len(lst) == 0:
lst[str(lst)] = 1
return 0
for key in Dict:
if key.upper() == lst.upper():
Dict[key] += 1
return 0
Dict[str(lst)] = 1
def sorting(Dict):
List=list(Dict.items())
l=len(List)
for i in range(l-1):
f... |
984,205 | fe11e948c480e5a4264d37e41a3a23c480111e2c | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _u... |
984,206 | 8b0836a399f8c1866c5f6ee50edb1e5fda01d8de | import pygame
FLOOR = 0
BRICK = 1
tilemap = [
[BRICK, BRICK, BRICK, BRICK, BRICK, BRICK, BRICK, BRICK, BRICK, BRICK, BRICK, BRICK, BRICK, BRICK, BRICK],
[BRICK, FLOOR, FLOOR, FLOOR, FLOOR, FLOOR, FLOOR, FLOOR, FLOOR, FLOOR, FLOOR, FLOOR, FLOOR, FLOOR, BRICK],
[BRICK, FLOOR, BRICK, FLOOR, BRICK, FLOOR, BRI... |
984,207 | 40f8638ea933540f7a897c4e5547ca491de4abe0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# openvas.py
#
# Copyright (c) 2021 Simon Krenz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; Applies version 2 of the License... |
984,208 | 457cdc4f385bfce603ba23a8b3e8eaefab7e2e13 | '''
>>> b = Baralho()
>>> b[0]
<A de copas>
>>> b[:3]
[<A de copas>, <2 de copas>, <3 de copas>]
>>> b[-3:]
[<J de paus>, <Q de paus>, <K de paus>]
>>> for carta in b: # doctest:+ELLIPSIS
... print carta
<A de copas>
<2 de copas>
<3 de copa... |
984,209 | 90114fc0f6587707e443917467f430f74b8d3755 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 29 21:55:42 2019
@author: Administrator
"""
import os
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
from matplotlib import gridspec
alllines = []
path = "TT"
filelst = os.listdir(path)
for file in filelst:
... |
984,210 | 77f8188bd8fd21e94310d8d2e99a2d88500b0611 | import tensorflow as tf
class EuclideanDistanceMetric(tf.keras.metrics.Metric):
"""
A custom Keras metric to compute the euclidian distance
"""
def __init__(self, **kwargs):
if 'is_training' in kwargs:
if kwargs['is_training']:
super(EuclideanDistanceMetric, self).... |
984,211 | 4963012affb8f671bb7c5362d29ad8b46fc3551e | import math
import re
import time
from tqdm import trange
from .utils import get_soup
comments_url_form = 'https://movie.naver.com/movie/bi/mi/pointWriteFormList.nhn?code={}&order=newest&page={}&onlySpoilerPointYn=N' # idx, type, page
def scrap_comments(idx, limit=-1, sleep=0.05, last_time=None, i_movie=-1, n_total_... |
984,212 | 40fea4aa76cae49a4404be14458d5e611230e3f6 | from datetime import datetime as dt
"""
Queremos armazenar os seguintes dados:
* Nome
* Idade
* Altura
* Peso
* Tipo sanguíneo (se conhecido)
* Queixa no PS (se houver)
* Datas de consulta
Operações:
* Alterar idade
* Alterar peso
* Alterar queixa
* Adicionar uma data de consulta
"""
class Paciente:
##lista de a... |
984,213 | 051d96484bfba00ec747edcacc31c6f448103868 | # -*- coding: ISO-8859-1 -*-
from pathlib import Path
import csv
STRING_ENCODING = "utf_8_sig"
def get_columns_from_csv(file_path: Path) -> list:
with open(file_path, "r", ) as f:
reader = csv.DictReader(f)
row = next(reader)
return list(row.keys())
def csv_to_json(file_path: Path) -> ... |
984,214 | c2d129bfbe73244a9c6e028fc20d93d8cc5f5ee3 | from concurrent.futures import ThreadPoolExecutor
from functools import partial
from itertools import islice
import pytest
from future_map import FutureMap, future_map
@pytest.fixture(name="executor")
def fixture_executor():
return ThreadPoolExecutor(max_workers=1)
def double(value):
return value * 2
de... |
984,215 | 3cd2fb05a73da485ec4b5a236a8022cd310ed08d | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import NullFormatter
from operator import attrgetter
def compute_mean_error(list_boxes, attribute, component):
mean = np.mean([getattr(getattr(box, attribute), component) for box in list_boxes], axis=0)
std = np.std([getattr(getattr(bo... |
984,216 | df572f83b75d28192d4cb2dd70ceb8ae7c745097 | from django.apps import AppConfig
class PersonalAccountingConfig(AppConfig):
name = 'personal_accounting'
|
984,217 | 67766a97e4ab49c9a67705d0c0b32257946aa265 | import argparse
import os
import hack_parser as parser
import encode_binary as encoder
# take filename as an argument
ap = argparse.ArgumentParser()
ap.add_argument('filepath', metavar='fp', type=str, help='Path to the .asm file to process.')
args = ap.parse_args()
# create an output file stream
filename = os.path.sp... |
984,218 | 68649c77ccece11a2fb20c19b5a8f184c913ecc9 | # -*- coding: utf-8 -*-
# coding=utf-8
"""
create_author : zhangcl
create_time : 2018-11-05
program : *_* course exam question *_*
"""
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import xlwt
def writeExcelFile(filepath, sheet_datas):
"""
保存若干个sheet中的数据
:param filepath: excel文... |
984,219 | c9c369a9fe948aa361e14e2ea3fe8ff341614fce | # Generated by Django 2.2 on 2019-05-29 15:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sprawdziany', '0002_sprawdzian'),
]
operations = [
migrations.AddField(
model_name='sprawdzian',
name='klasa',
... |
984,220 | 34f971900d3365d6f8b6e6a6868f705ab8a3b125 | import os
import sys
import re
txtFile = sys.argv[1]
regFile = sys.argv[2]
with open(txtFile, 'r') as f1:
txtlines = f1.readlines()
with open(regFile, 'r') as f2:
regLines = f2.readlines()
for regLine in regLines:
tp_ls = regLine.split('\t')
p = re.compile(tp_ls[1])
tg_lines = list()
for... |
984,221 | cdd0f4b983c6dab7196f3c08156f9d7f177cee3c | import json
import numpy as np
import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer
data_path = "../data/json"
with open('%s/train.json' % (data_path)) as json_data:
train = json.load(json_data)
with open('%s/test.json' % (data_path)) as json_data:
test = json.load(json_data)
with open('%... |
984,222 | 3d66fc4059c5815c6199297b28deac3441a3ba07 | from django.conf.urls import include, url
from accounts import views
urlpatterns = [
url(r'^crear_transaccion/$', views.create_transaction, name='createTransaction'),
url(r'^crear_evento/$', views.new_event, name='newEvent'),
url(r'^crear_items/$', views.addItem, name='addItem'),
url(r'^crear_venta/$',... |
984,223 | 504d25bcae046e76ff0175cb0a649bd6fa143073 | import math
import numpy as np
import pylab as plt
k = 0.5
def f(t,x,u):
x1,x2,v1,v2,theta = x
u1,u2 = u
return np.array([v1,v2,u1*math.cos(theta)-k*v1,u1*math.sin(theta)-k*v2,u2])
def h(t,x,u):
x1,x2,v1,v2,theta = x
u1,u2 = u
return np.array([x1,x2,theta])
def u1(t):
re... |
984,224 | f2703a8f7b7064f5bf3de720031f2528b35a4e01 |
class Solution:
def findErrorNums(self, nums: List[int]) -> List[int]:
s = set(nums)
sum_set = sum(s)
sum_all = sum(nums)
dupl = sum_all-sum_set
return [dupl, (((1+len(nums))*len(nums))//2)-sum_set]
|
984,225 | 07e2ce29c4a7841bf1a9dc0f62f71f09ff639e59 | #!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Herald Bluetooth Message Implementation
:author: Luc Libralesso
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.0.3
:status: Alpha
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License... |
984,226 | 8d5762054909836bf04c2576602b13771d2e5c58 | import random
import math
import pyglet
from yaff.scene import Scene
from .player import Player
class GameScene(Scene):
KEY_MOVEMENT_MAPPING = {
pyglet.window.key.A: Player.DIRECTION_LEFT,
pyglet.window.key.D: Player.DIRECTION_RIGHT,
pyglet.window.key.W: Player.DIRECTION_UP,
pygle... |
984,227 | 0ac434f642d480fbe85d9f24c44276f5b1a8a38c | #!/usr/bin/python
import json
import logging
import sys
import common
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
if len(sys.argv) != 1:
print "usage: " + common.sarg(0)
sys.exit(1)
config_file = common.SYSTEM_CONFIG_FILE
config_stream = open(config_file)
config... |
984,228 | 428c7346d3ebaa806df04a4d918505e7e173f040 | # coding: utf-8
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
train_df = pd.read_csv('../data/train.csv')
sns.distplot(train_df['SalePrice'])
plt.show() |
984,229 | 45c532428373cb63c5a31b91b9450360b39c479f | from data_utils import PeMSD7M, describe_data, load_data
from model import SpatioTemporalConv
from model_updated import STGCN
from torch_geometric.nn import GCNConv
from torch_geometric.data import Data
import torch.nn as nn
import torch
from torch.utils.tensorboard import SummaryWriter
device = torch.device('cuda' i... |
984,230 | b9301297642ccea292ded110f5dd9a0ca70ddaf5 | from subprocess import call
from time import sleep
from pathlib import Path
import os
import zipfile
import json
formats = [".zip", ".rar"]
cwd = os.getcwd()
new_wd = None
def openStatJsonR():
try:
with open(str(os.path.dirname(os.path.abspath(__file__))) + r"\statistics.txt") as json_file:
s... |
984,231 | 76fa6943fbc1c960dab5fdf4a0fcb25866de1c46 | from translate import *
import numpy as np
import pickle
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
def evaluate_case(test_txt, test_labels, words, txt_lang, labels_lang, model, device, max_label_len, output_msg='', save_pred=None):
acc_ord = 0
acc_un = 0
predict... |
984,232 | a127231cbbc03ab3c43a37b2b16398bef0455eca | import cv2
import argparse
import numpy as np
import itertools
def repeat(f, N):
for _ in itertools.repeat(None, N): f()
# set up arg parser & read args
parser = argparse.ArgumentParser(description="EIASR 2015Z project")
parser.add_argument("-i", "--image", required=True,
help="Path to an inp... |
984,233 | 34f92bae7ec71bc80bd1b15becfef1bd6d7a211e | from flask import Flask, session, request, redirect, render_template, flash, url_for
from db.data_layer import get_show, create_user, login_user, get_user_by_id, create_like, get_user_likes, delete_like
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
app.secret_key = '8118d0875ad5b6b3ad830b956b111fb0'
csr... |
984,234 | 4cd8adb95886ed6dee4fd6a61da970d3ab72cb31 | import os
def setup_key(remote, port):
os.system('ssh %s@%s -p %d mkdir -p .ssh' % (user, remote, port))
cmd = "cat /home/ahagen/.ssh/id_rsa.pub | ssh %s@%s -p %d 'cat >> .ssh/authorized_keys'" % (user, remote, port)
print cmd
os.system(cmd)
# check if ~/.ssh/id_rsa.pub is there
# if not, run ssh-key... |
984,235 | ed507f910d0d19b54cca46bf416bf7ad0414c717 | from pandac.PandaModules import *
from toontown.toonbase import TTLocalizer
from toontown.toonbase import ToontownGlobals
ENDLESS_GAME = config.GetBool('endless-ring-game', 0)
NUM_RING_GROUPS = 16
MAX_TOONXZ = 15.0
MAX_LAT = 5
MAX_FIELD_SPAN = 135
CollisionRadius = 1.5
CollideMask = ToontownGlobals.CatchGameBitmask
TAR... |
984,236 | 112ec4f0712a04d3c71ebd2752680bd0228d0827 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ChildForm.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_ChildForm(object):
def setupUi(self, ChildForm):
ChildForm... |
984,237 | 8912602048121cf8b79517ec4013c284082e833b | from tkinter import filedialog
from tkinter import messagebox
from tkinter import *
from scrapy import spiderloader
from scrapy.utils import project
from scrapy.utils.log import configure_logging
from scrapy.crawler import CrawlerRunner
from twisted.internet import reactor
import threading
def get_spiders(... |
984,238 | 5ae06b7dc1de658fc836be9f8b33ad634bac15ab | # -*- coding: utf-8 -*-
a=int(input('Moeda a: '))
b=int(input('Moeda b: '))
c=int(input('Cédula: '))
qa=0
qb=0 |
984,239 | 57e43deb1bb4bfb534b4369673ec3d1409aa2432 | from sphinxcontrib.domaintools import custom_domain
def setup(app):
app.add_domain(custom_domain('VaggaOptions',
name = 'vagga',
label = "Vagga Yaml Options",
elements = dict(
opt = dict(
objname = "Yaml Option",
indextemplate = "option: %s... |
984,240 | f933123c6fa8cc1ba48f02910a3a595ca3b03d07 | from rest_framework import serializers
from datetime import datetime
class UserFetchCovDataSerializer(serializers.Serializer):
timeline = serializers.DateTimeField(required=False, allow_null=True, default=datetime.now())
country = serializers.CharField(required=False) |
984,241 | fd8475f3cf345290dcf55f1148a46212f49e00e5 | import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
reader = SimpleMFRC522.SimpleMFRC522(bus=0, device=1)
try:
print("Now place your tag to write the new key")
reader.modify_key()
finally:
GPIO.cleanup() |
984,242 | ec80678bf7b96d89f8fb4f8dd87a36c57ec2a869 | __author__ = "saeedamen" # Saeed Amen
#
# Copyright 2016 Cuemacro
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
984,243 | bb5ab5f9c0dadab655434ab446ac9e4a14941c41 | def getUserInput():
""" Function for money and cost input and
for computing the maximum amount of apples
that you can buy and the amount of your change"""
money_ = float(input('Enter the amount of your money: '))
cost_ = float(input('Enter the price of an apple: '))
apple_= int(money_/c... |
984,244 | 6ded1b4be5dc2e7e3a7846709d32f6dee80e80be | # -*- coding: utf-8 -*-
"""Console script for av_slice."""
import sys
import click
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.audio.io.AudioFileClip import AudioFileClip
from .audio import loud_sections
from .video import join_sections
@click.command()
@click.option('--output_file', defaul... |
984,245 | d404a6eaa7925dc26bdec858ffcc7743002cec32 | import json
player = {
'armor_type' : 1,
'armor_mod' : 1,
'armor_name' : 'Iron',
'weapon_type': 0,
'weapon_mod' : 3,
'weapon_name': 'Sword',
'hand_coeff' : 1
}
with open('data.txt', 'w') as outfile:
json.dump(player, outfile)
with open('data.txt') as json_file:
data = json.load(j... |
984,246 | ff1a82b3d9266cb411b039e405c158ba98da5eb3 | import numpy as np
import matplotlib.pyplot as plt
from utils import conversion_db_veces
from my_plots import plot_histograma
def mu_y(snr, n, sigma):
'''
Devuelve un arreglo numpy del primer sumando de la salida analogica.
'''
exponente = (n-1)/2
cociente_snr = np.asarray([(x/(x+1))**exponente f... |
984,247 | 36999f67bc5d6800d8c2e7284c20321138d989dd |
import tensorflow as tf
import numpy as np
from lib.Layer import Layer
from lib.ConvBlock import ConvBlock
from lib.ConvDWBlock import ConvDWBlock
from lib.UpSample import UpSample
class DecodeBlock(Layer):
def __init__(self, input_shape, filter_shape, ksize, init, name, load=None, train=True):
self.in... |
984,248 | 8139e7c31c945f1434ea1fda907e696172ff549e | from Core.DAO.FactorDao.FactorDao import FactorDao
from Core.DAO.TableMakerDao import TableMaker
from Core.Conf.DatabaseConf import Schemas
from Core.Error.Error import Error
import traceback
class Initializer(object):
"""
This class implement the interface of factor manager's initialization
"""
... |
984,249 | df07807082528d8e4fed67619d27dd12e1594666 | class GitDeployer:
pass |
984,250 | 92b4869236daf04128685c808ecc7dde8e197278 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import pandas as pd
import numpy as np
import os
import env
# creating a connection to connect to the Codeup Student Database
def get_connection(db, user=env.user, host=env.host, password=env.password):
return f'mysql+pymysql://{user}:{password}@{host}/{db}'
def ge... |
984,251 | 80b5990f252f2437c4fab719f7a8ae9aa6ef0598 | '''
Source: ACM Japan 2005.
IDs for online judges: POJ 2739, UVA 3399.
Some positive integers can be arrived at by adding consecutive primes.
Ex.
53 5 + 7 + 11 + 13 + 17 and 53
41 2 + 3 + 5 + 7 + 11 + 13, 11 + 13 + 17, and 41
3 3
but not
20 3 + 5 + 5 + 7 // 5 is repeated and hence not consecutive
Task
Write a progr... |
984,252 | 86a987befea4c4612a6d84773031579208b58614 |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.8'
_lr_method = 'LALR'
_lr_signature = '54820A6D8FB5AA5FA5E3D4961CD92D46'
_lr_action_items = {'$end':([1,2,3,4,],[-3,0,-1,-2,]),'NUM':([0,1,2,3,4,],[1,-3,1,-1,-2,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
f... |
984,253 | e9597de46e477870c479da4ef318b57aae9d31a1 | from django.test import TestCase
from .models import Item
class TestViews(TestCase):
def test_get_todo_list(self):
# To test the HTTP response of the view
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
# To confirm the view uses the correct template
... |
984,254 | c672bf1f1aa41769625df485c89ced8b9c84eee3 | """Tests bor bootstrap Transformers."""
|
984,255 | 078fec1243252387ef27b2d06a6b680ed2b4cb1b | #! /usr/bin/python
# Import the core Python modules for ROS and to implement ROS Actions:
import rospy
import actionlib
# Import all the necessary ROS message types:
from sensor_msgs.msg import LaserScan
# Import some other modules from within this package (copied from other package)
from move_tb3 import MoveTB3
# ... |
984,256 | 8386a556e7e45893a8edc639ea90c6f06191e173 | #!/usr/bin/env python3
import random
def start_game(min_num, max_num, try_to, random_num):
print("Passed args: %s %s %s %s" % (min_num, max_num, try_to, random_num))
min_num = 0
max_num = 100
try_to = 3
random_num = random.randrange(min_num, max_num)
print("Try to guess the number I think about. It's from {0} to ... |
984,257 | 742d367334179e3285e3c530a0e3b6967be66bf7 | import pynrc
import pynrc.reduce.ref_pixels
import numpy as np
from astropy.io import fits, ascii
import glob
import os
from os import listdir, getcwd
from subprocess import call
from shutil import copyfile
import yaml
import pdb
from copy import deepcopy
import make_syml
from multiprocessing import Pool
import warning... |
984,258 | bcca33d328de4a06764c9e0ca06b6a046983b48b | from __future__ import print_function
import unittest
import gevent
try:
from gevent.resolver.ares import Resolver
except ImportError as ex:
Resolver = None
from gevent import socket
import gevent.testing as greentest
from gevent.testing.sockets import udp_listener
@unittest.skipIf(
Resolver is None,
... |
984,259 | a5dce63a19e6d4da3aa2191070dd91a946ce9362 |
from sklearn import preprocessing
import numpy as np
def set_nan_to_zero(a):
where_are_NaNs = np.isnan(a)
a[where_are_NaNs] = 0
return a
def TSC_data_loader(dataset_path,dataset_name):
print("[INFO] {}".format(dataset_name))
Train_dataset = np.loadtxt(
dataset_path + '/' + dataset_name... |
984,260 | e40c5d864e78e56d018d7e5a886cb265ffd19fea | #-*- codeing = utf-8 -*-
#@Time : 2020/8/15 11:27\
#@Author : YJY
#@File : 测试代码.py
#@Software : PyCharm
import pandas
data = pandas.read_excel("E:/calc.xls",sheet_name=0,names=['s1','op','s2','s3'],dtype={'s1':str,'op':str,'s2':str,'s3':str},header=None)
data = data.values.tolist()
print(data) |
984,261 | 8f1a80d51a216e262f03a7e5288e5f8830666a0a | r"""
Tests for the :mod:`scglue.models.base` module
"""
import pytest
import torch
import scglue
def test_base():
model = scglue.models.Model()
with pytest.raises(RuntimeError):
_ = model.trainer
model.compile()
with pytest.raises(NotImplementedError):
model.fit([torch.randn(128, 10)... |
984,262 | 741870274835da2247891b2b76774f36158592ae | n = int(input())
k = int(input())
sset = []
for _ in range(n):
sset.append(int(input()))
sset = list(sorted(sset))
new = []
for idx in range(0, len(sset)-1):
new.append(abs(sset[idx]-sset[idx+1]))
# print(new)
import sys
smallest_sum, idx = sys.maxsize,0
new_k = k-1
for i, el in enumerate(new):
if i == (... |
984,263 | 8fa4e4936f56d6cf941afaccf72fb21a39fbfde6 |
# https://leetcode.com/problems/search-in-rotated-sorted-array/
# Time: O(Log N) | Space; O(1)
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if len(nums) == 0:
return -1
if len(nums) == 1:
... |
984,264 | c91adaf6753a9e6793dfbbb708bef76c5d46861c | from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render
from django.views import generic
from django.http import HttpResponseRedirect, JsonResponse, HttpResponse
from django.urls import reverse
from django.contrib import messages
from django.contrib.auth import authenticate, login, lo... |
984,265 | 23ce8ec75e5f61a15fc1988bf4811f68d2995c32 | import pygal
from chart_super_class import ChartSuperClass
class DiceHistogram(ChartSuperClass):
def __init__(self):
self.chart = pygal.Bar()
def set_style(self, style):
self.chart.style = style
|
984,266 | d543fcca4fa52b7a70897575a2626bffeeaf4721 | noun = input("Enter a noun: ")
verb = input("Enter a verb: ")
adjective = input("Enter an adjective: ")
adverb = input("Enter an adverb: ")
print(f"Do you {verb} your {adjective} {noun} {adverb}? That's hilarious!")
|
984,267 | 290968cf75e9c5b35808ad01fe020024c7f89d85 | from azureml.core import Dataset, Workspace
from dotnetcore2 import runtime
runtime.version = ("18", "04", "0")
runtime.dist = "ubuntu"
ws = Workspace.from_config()
default_ds = ws.get_default_datastore()
data_ref = default_ds.upload(src_dir='data',target_path='/data/files', overwrite=True, show_progress=True)
housin... |
984,268 | aa420d7893b4b678a33554bbff6e531816982f2c | #!/usr/bin/env python
# -*- coding:utf-8 -*-
##
# Copyright (C) 2018 All rights reserved.
#
import random
from CorpApi import *
from weConf import *
api = CorpApi(TestConf['CORP_ID'], TestConf["CONTACT_SYNC_SECRET"])
try :
##
response = api.httpCall(
CORP_API_TYPE['DEPARTMENT_LIST']
)
#... |
984,269 | 8f0d497e2e7c2e18d4b7c26c92c9060138ceca25 | #! /usr/bin/env python3
"""
Docblock
"""
# import built in modules
# import Third party
# import local
from DualTimer.Src.Config.App import App as Config
__author__ = "John Evans <john@grandadevans.com?"
__copyright__ = "Copyright 2015, John Evans"
__credits__ = ["John Evans <john@grandadevans.com>"]
__license__ = ... |
984,270 | cb388ba49c818703bd48eb53f3ca820a449e8279 | """
WARNING: OpenFace requires Python 2.7
Module for managing the SqueezeNet recognition method.
Obtained from https://github.com/kgrm/face-recog-eval
"""
import os
import cv2
import numpy as np
from keras import backend as K
from .networks_def import squeezenet
class SqueezeNet:
def __init__(self):
sel... |
984,271 | 0b1b6aece091ea191b3ddd3fed843deb5cda0346 | from unittest import TestCase
from enemies import *
__author__ = 'p076085'
class TestEnemy(TestCase):
def setUp(self):
self.soul = Soul()
self.specter = Specter()
def test_enemy_init(self):
self.assertDictEqual(self.soul.stats, Soul.stats)
self.assertDictEqual(self.soul.items... |
984,272 | 870b8f2dbe5a2803e2e61fa49aa5bd8b7384dfc3 | import os
os.system('cls')
class Node:
def __init__(self,data):
self.data=data
self.next=None
'''
find the kth to last element of a singly linked list.
'''
class LinkedList:
def __init__(self):
self.head=None
def appendnode(self,data):
New_Node = Node(data)
if... |
984,273 | a7486f10c3e4f6ccbf9f1f4981147c08c6492cfb | #读取文件第一行
import csv
from datetime import datetime
from matplotlib import pyplot as plt
filename="forme.csv"
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
#一列一列读取表格中数据
dates,opens,highs,lows,closes,adjcloses=[],[],[],[],[],[]
for row in reader:
current_date=datetime.str... |
984,274 | 22ed30ce358914f0632f2593f533f3bf97ee0198 | """
sphinx-simulink.directives
~~~~~~~~~~~~~~~~~~~~~~~
Embed Simulink diagrams on your documentation.
:copyright:
Copyright 2016 by Dennis Edward Kalinowski <dekalinowski@gmail.com>.
:license:
MIT, see LICENSE for details.
"""
import hashlib
import os
import tempfile
from docutils.pars... |
984,275 | 37314b76832dfe58c3b99e3ab4d593ff69ed2f02 | from django.http import HttpResponse
from models import Process
import json
import os
import subprocess
import time
from django.conf import settings
REPO_DIR = settings.MUNKI_REPO_DIR
MAKECATALOGS = settings.MAKECATALOGS_PATH
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
... |
984,276 | d4bfe6634e61e34ca60b274b6279d0434333a50a | import sys
sys.path.append('../')
import functions as fc
import matplotlib.pyplot as plt
import numpy as np
import os
print os.getcwd()
#Tlist=[10,20,30]
#A,T,eT=fc.data3('Data_and_Plots/April 23rd Aperture/ApertureData.txt')
#
#plt.figure(5)
#for indx,Av in enumerate(A):
# plt.errorbar(A[indx],T[indx],eT[indx],fm... |
984,277 | 80890afaa6e7752c404eb2d1aa163347ef76145f | """
Pre-process raw reddit data into tfrecord.
"""
import argparse
import os
import random
import tensorflow as tf
import numpy as np
import bert.tokenization as tokenization
import reddit.data_cleaning.reddit_posts as rp
rng = random.Random(0)
def process_without_response_task(row_dict, tokenizer):
context_fe... |
984,278 | e450ed450d3a6649174039100eb3562a8bd46494 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Cuenta, Partida, Periodo, Catalogo, Transaccion
# Register your models here.
class CuentaAdmin(admin.ModelAdmin):
list_display = ('nombre','codigo','naturaleza','debe','haber')
admin.site.register... |
984,279 | 7d458ac2b85f31942a2b47ac8cc94ee11be9c238 | # main.py
# Entry point for the game loop.
# The Blender World Object should have a custom property called __main__ that refers to this script. This causes bge to defer the render and logic loops to this script.
import bpy
import os
import bge
import sys
import time
import json
# Make sure api script is found by appe... |
984,280 | 5c1bf58755725b18d8620c8ad08084f2a6ff7461 | import sys
W, P = sys.stdin.readline().split(' ')
W = int(W)
parts = [False] * 101
dists = list(map(int, sys.stdin.readline().split(' ')))
dists.insert(0, 0)
dists.append(W)
for i in range(len(dists) - 1):
for j in range(i + 1, len(dists)):
parts[dists[j] - dists[i]] = True
for i in range(1, len(parts))... |
984,281 | e4c6d4d18f4c0f6772768587a478f2153dcb4984 | import dmarc_metrics_exporter.model as m
SAMPLE_XML = """
<?xml version="1.0" encoding="UTF-8" ?>
<feedback>
<report_metadata>
<org_name>google.com</org_name>
<email>noreply-dmarc-support@google.com</email>
<extra_contact_info>https://support.google.com/a/answer/2466580</extra_contact_info>
<report_i... |
984,282 | 66a988233c520c12b39f4e97b00f2c4450670778 | """treelstm.py - TreeLSTM RNN models
Written by Riddhiman Dasgupta (https://github.com/dasguptar/treelstm.pytorch)
Rewritten in 2018 by Long-Huei Chen <longhuei@g.ecc.u-tokyo.ac.jp>
To the extent possible under law, the author(s) have dedicated all copyright
and related and neighboring rights to this software to the ... |
984,283 | 987a93823b5d4c812d1b36d1ef30f81ee34ca818 | from .transfer import Transfer
__all__ = ["Transfer"]
|
984,284 | e3a3782a9ffd0e27c2cb6a65ea9a72285f2d555e | # string = 'My name is Azamat. I am a developer'
# # print(string.replace('a', '*'))
# list_ = []
# for i in string:
# if i.lower() == 'a':
# list_.append('*')
# else:
# list_.append(i)
# print(''.join(list_))
name = input()
last_name = input()
age = input()
city = input()
print(f" You are {n... |
984,285 | a0247abe679df952b923d3eae3449df5d8dcd741 | from sklearn.svm import LinearSVC
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import numpy as np
import wx
import os
import sys
import nltk
import math
import copy
import wx.lib.platebtn as platebutton
import cStringIO
reload(sys)
sys.setdefaultencoding('latin-1')
tr = [... |
984,286 | 77805457ef0ec51cafc97754f3d22b85daba3672 | # 编译日期:2020-10-27 16:15:31
# 版权所有:www.i-search.com.cn
# coding=utf-8
|
984,287 | 9c1cd44d742dd57ad34ec6834d2fb867e6f0c7fc | # Generated by Django 3.1.7 on 2021-02-27 18:19
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('envdaq', '0006_controllerdef_component_map'),
('envdatasystem', '0005_controllersystem_daqsystem'),
]
opera... |
984,288 | c15fa5f674af82ee599227c35a5798192e372208 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import requests
from baiduocr.result import LocateRecognizeResult
_API_URL = 'http://apis.baidu.com/idl_baidu/baiduocrpay/idlocrpaid'
class BaiduOcr(object):
"""百度 OCR 客户端"""
_IMAGE_FOR_TEST = '/9j/4AAQSkZJRgABAQEAYABgAAD/2wBD... |
984,289 | 71fe875273a55ec2b0fcad979ffd922b70cd766e |
# Import Libraries
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initialize CNN
classifier = Sequential()
# Convolution Layer
classifier.add(Convolution2D(32,3,3,input_shape = (64... |
984,290 | f27326208ec6b87df705a283f041244411bb68e6 | from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField, SubmitField, ValidationError,SelectField,IntegerField,validators,FormField
from wtforms.validators import DataRequired, Email, EqualTo
from ..models import Employee
from wtforms.fields.html5 import TelField
from wtforms_alchemy import Phone... |
984,291 | 79a44f4823e2b18d344ef669d8c2f0fbdf5e56df |
"""query_rcsb.py:
Query rscb
Last modified: Fri Aug 29, 2014 11:57PM
"""
__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2013, Dilawar Singh and NCBS Bangalore"
__credits__ = ["NCBS Bangalore"]
__license__ = "GNU GPL"
__version__ = "1.0.0"
__maintainer__... |
984,292 | cfef25d61ccdb426a9c5c186de9a1470e120227a | class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
'''
node.insert(5) is the same as BST.insert(node, 5)
We use this when recursively calling, e.g. self.left.insert
'''
i... |
984,293 | f382582d503cf648b57b48f0bf60a5532fa614f2 | import pandas as pd
collist = ['Team name','Intuitiveness','Creativity','Responsiveness','Novelilty'] #column names list
csvlist = ['jacob.csv','cyril.csv'] # csv files list
# Dictionary variables
Intuitiveness = 0
Creativity = 0
Responsiveness = 0
Novelilty = 0
# initalize Dictionary
dict = {
'Intuitiveness... |
984,294 | 7f0a5df8025c6445d59316b29b049b1d73a6d15e | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from nnsubspace.nndataset.dataset import Dataset
from nnsubspace.nnmodel.model import NNModel
dataset_ = Dataset(dataset='mnist')
model_ = NNModel(dataset='imagenet', model_id='0') |
984,295 | ec35baecc590aa98782014ced8f2c5b20be9e4dd | from collections import Counter
lst = [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11]
lst1 = []
for el in lst:
if lst.count(el) > 1:
lst1 = lst1.append(el)
print(lst1) |
984,296 | f23526a8ed19d09b5d199e8efd7a1231a5e2e537 | from django.db import models
class ReadOnly(models.Model):
num_jobs = models.IntegerField()
city_name = models.TextField()
state = models.TextField()
latitude = models.FloatField()
longitude = models.FloatField()
job_title = models.TextField()
created_at = models.DateField()
class Meta:
db_table = 'ReadOnly'... |
984,297 | a3cf9a43854e1e83b1679e2e3bc9dba9370f11c5 | from django.db import models
from common.base_model import BaseModel
from online_store.models_manager import AvailableObjectsManager
class Product(BaseModel):
title = models.CharField('наименование', max_length=128)
description = models.TextField('описание')
weight = models.IntegerField('вес')
price ... |
984,298 | f34b0ce23d57c8f707d2991e105017dbfdf29c63 | import cv2
import os
import logging
import numpy as np
import matplotlib.pyplot as plt
import sqlite3
from skimage import color, measure, feature
from skimage import io
from sklearn.cluster import KMeans, MeanShift
from zipfile import ZipFile, ZIP_DEFLATED
from yellowbrick.cluster import KElbowVisualizer
import math
#... |
984,299 | 2e39d4aa52ff2d5aefca208b7249585e6188fddb | from datetime import datetime
import calendar
import time
while True:
now = datetime.utcnow()
unixtime = calendar.timegm(now.utctimetuple())
minstamp = unixtime - (now.second)
print('Current timestamp: %s' % unixtime)
print('Current timestamp on the minute: %s' % minstamp)
print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.