index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
991,000 | 3d004e0dfa6e9883bc4385fce24302d54d8ae1b4 | #coding:cp949
prompt = """
1.Add
2.Del
3.List
4.Quit
Enter number: """
number =0
While number !=4:
print(prompt)
number = int(input())
|
991,001 | 6ae762e91429a8f986a336d72cd07aa9600af30d | import os
import dgl
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import networkx as nx
import numpy as np
from sklearn.model_selection import KFold
import digital_patient
from digital_patient.conformal.base import RegressorAdapter
from digital_patient.conformal.icp import IcpRegressor
f... |
991,002 | 1ba39b03f10c1ab7498a80cfe80463d9626f5172 | n=int(input())
sum1=0
while n>0:
s=n%10
sum1=sum1+(s*s)
n=n//10
print(sum1)
|
991,003 | 9b18b86e6f482514f11322490d15b59e94172355 | from Crypto.Util.number import size
from dateutil.parser import parser
__author__ = 'zanetworker'
from ConfigParser import SafeConfigParser
import utils.CommonUtils as CommonUtil
parser = SafeConfigParser()
try:
config_file = CommonUtil.get_file_location('config', 'deployment.ini')
parser.read(config_file)... |
991,004 | 035a97c756d61cdaf309336ecc495091ca0be97c | # -*- coding:utf-8 -*-
import time
import openpyxl
from config import SHEET_TITLE
def get_excel(data, field, file):
# create a workbook
new = openpyxl.Workbook()
# create a sheet
sheet = new.active
# named the sheet
sheet.title = SHEET_TITLE
# write the field into the first row of sheet
... |
991,005 | 9558fbb18cd7b9e37a5ab4fd33207a4f995975f7 | from utilities.file_operations import FileOperation
from utilities.read_configs import ReadConfig
from utilities.os_operations import OSOperations
import pytest
@pytest.mark.recon
@pytest.mark.findasset
@pytest.mark.gau_test_get_all_urls
def test_get_all_urls():
"""should return result of 'gau 42qwerty42.com'"""
... |
991,006 | 5fbb77ca9933c141fe36ebfc9d1c7ebf2583f400 | # 테트로미노
# https://www.acmicpc.net/problem/14500
# 힌트
# 1. 반례세트 : https://www.acmicpc.net/board/view/61597
# 2. dfs를 활용하여 길이(크기)가 4일때까지의 합 중 가장 큰 값을 정답으로 갱신한다.
# 3. 같은 위치의 같은 모양이 중복되지 않도록, limit_i, limit_j를 지정해주어
# 추가되는 블록이 limit_i보다 위에나 limit_i와 같거나 limit_j보다 작은쪽으로 생성되지 않도록 한다.
# 4. dp를 사용하여 이미 점유된 블록은 추가로 점유하지 않도록 ... |
991,007 | 3e9ce65efa0dc5e2ff060deda73e97f9b63765c5 | #-*- coding: utf-8 -*-
# Copyright (c) 2015 Blowmorph Team
from __future__ import unicode_literals
import wx
from launcher_frame import LauncherFrame
##############################################################################
class Launcher(wx.App):
#------------------------------------------------------------... |
991,008 | f46b02a5dd8c04a2a9f3389ce831193952175434 |
# BEE Structure stores data about the keystroke
class BufferEventElement(object):
def __init__(self, key, action, time):
self.key = key
self.action = action
self.time = time
self.delete = False
class GroupingBuffer(object):
def __init__(self, holdkey_matrix):
self.even... |
991,009 | 0ab1019c07d6e8fa2eaa724c20f8753c1c82b0bc |
print(''+"\n".join((i[0]+str(i[1])) for i in zip(['明天','后天','大后天'],[1,2,3])))
def ss (a,b,**c):
print(a)
print(b)
print(c)
s=dict()
o=input("key")
p=input("value")
s[o]=p
ss(1,2,**s) |
991,010 | 93ee4ab43cb2eae61ef9473fdd5cb3e732317234 | from django.test import TestCase
from manifest_parser import ManifestParser, ParseError
from models import MediaFile, Manifest
valid_manifest_file = 'file_manager/test_data/valid.xml'
test_upload_manifest = 'file_manager/test_data/test_upload_manifest.xml'
test_upload_1 = 'file_manager/test_data/test_upload_1.txt'
... |
991,011 | 3b49013c439fee3e686c4f19bf5b350e924bfe83 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 13:09:29 2021
@author: lalyor
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.metrics import confusion_matrix,classification_report
from skle... |
991,012 | 191d9b882647262b7b6908a363fc89c3f892627a | from django.apps import AppConfig
class StatustransitionConfig(AppConfig):
name = 'statustransition'
|
991,013 | 98ff8ba6a0da02fce774846a48e23fdc01804162 | # Copyright 2019-2020 the ProGraML authors.
#
# Contact Chris Cummins <chrisc.101@gmail.com>.
#
# 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... |
991,014 | dbfcd8953f4fc7607748e1b3838719f0228fa1a2 | class User:
firstName=None;
lastName=None;
userName=None;
password=None;
salt=None;
def __init__(self,firstName,lastName,userName,password,salt):
print "User constructor";
self.firstName=firstName;
self.lastName=lastName;
self.userName=userName;
self.sal... |
991,015 | 4e5b7c5cbca92232617d2e8f51ff82de2412372e | class Solution(object):
def areConnected(self, n, threshold, queries):
"""
:type n: int
:type threshold: int
:type queries: List[List[int]]
:rtype: List[bool]
"""
data = range(n + 1)
def find(x):
if data[x] != x:
da... |
991,016 | 721993343fdb4c7b2dd7a79805dcb28ad1fd3ca3 | import json
from decimal import Decimal
import boto3
restaurantMenu = {
"categories": [{
"categoryName": "Mains",
"timeServed": [""],
"items": [{
"itemName": "New Item",
"itemDescription": "",
"itemPrice": 0.0,
"picture": "",
"ingredients": "",
"available": True,
... |
991,017 | b5d0c67946d1ba093ec79880049b5f1bd525dc46 | import problem
class Node():
def __init__(self, parent=None, position=None , cost=0 ):
self.parent = parent
self.position = position
self.c = cost
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position == other.position
def ... |
991,018 | c9b94c02549bd036b45a0719ecc6d7a9a2cbd074 | from random import *
# --- Define your functions below! ---
def begin():
print("Hi! I'm Chatbot. I love talking to people!")
def name():
print("What is your name?")
user_input = input()
print("Hello " + user_input + "! Nice to meet you!")
return user_input
def color():
print("What's your favor... |
991,019 | 16c27fffaa326a1ec3e84555f3dd3cfc21037b0f | import json
import logging
import os
import urllib
from string import Template
from typing import List, Dict
import networkx as nx
import requests
from rdflib import URIRef, RDF
from utils import ResourceDictionary, serialize, deserialize
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message... |
991,020 | 332f2fca01d224a329f6ab8f6e0a4e8895f142a2 | import cx_Freeze
target = cx_Freeze.Executable(
script="JUJUJUL.py",
base = "Win32GUI",
icon=r"E:\putting 1s and 0s in the right order\Le J\Google Chrome.ico"
)
cx_Freeze.setup(
name = "JUJUJUL",
options = {"build_exe" : {"packages": ["ctypes", "winsound"], "inclu... |
991,021 | a881a8c803ab64def311b52519308f02f26a335d | import os
from cartmigration.models.setup import Setup
file_config = 'cartmigration/etc/config.ini'
if os.path.isfile(file_config):
print("File config is exist, setup db with file config")
print("----------------------------------")
setup = Setup()
setup.run() |
991,022 | dbe5f393957540a6a1cab00a0650c3fc78f1ebf9 | __author__ = 'leif'
from ifind.search import EngineFactory
from example_utils import make_query, run_query, display_results
query_str = u'retrievability'
wiki_engine = EngineFactory('wikipedia')
query = make_query(query_str)
response = run_query(wiki_engine, query)
display_results(response) |
991,023 | 8c187d9be36a49a6203b77995e39e83f677c3b0a | import random
# to generate random value
print(random.random())
# to generate a integer randam value between two numbers
print(random.randint(10,20)) |
991,024 | 0b56a31c04740ea57ab77e9b294fb6c74dee37fb | from requests_html import HTMLSession
from bs4 import BeautifulSoup as BS
import shelve
import pandas as pd
import pprint
session = HTMLSession()
url = 'http://corganinet.com/_applications/locator_v1/view_officemap_01.cfm'
def make_dict():
emp_dict = dict()
floors = dict([('First Floor', 10025),('S... |
991,025 | 79aa4f67b3c8c625398368fd0736c3534ddcad45 | ### XLSX PARSER ###
from bisect import insort
from openpyxl import load_workbook
from typing import List, Dict, Iterable
import re
def list_column(spreadsheet: str, column: str) -> List[str]:
## Takes a path to an xlsx and a column and returns a list
wb = load_workbook(spreadsheet)
worksheet = wb.active
retur... |
991,026 | 66301785698cd29216cdcaf7d0b6db6677c00fda | import unittest
class SegmentTee:
def __init__(self, input_arr, query_func, no_overlap_default_value):
"""
:param input_arr: an array that is an object of the query
:param query_func: a lambda function that accept two arguments amd returns a number
:param no_overlap_default_value: ... |
991,027 | fac71d576dc9739bc24295a8e7f8dc1dcb5ed0d0 | #!/usr/bin/python
import os
import sys
import numpy as np
import logging
from create_dataset import genererate_dataframe
from preprocess_data import Preprocces
import pickle
from sklearn.model_selection import train_test_split
from keras.preprocessing.text import Tokenizer
from keras.layers import Embeddi... |
991,028 | c0c9dec78f0bae58898c1685f7a1e76f2dfbebbc | import copy
import math
import os
from typing import Dict, Type, Union, Tuple, Optional
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim.lr_scheduler import StepLR
import source.evaluation_utils as eval_utils
from source.data_han... |
991,029 | 7903be6fc31dad03c65199597f33d9ee931e402a | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import podium_api
from podium_api.asyncreq import get_json_header_token, make_request_custom_success
from podium_api.types.racestat import get_racestat_from_json
from podium_api.types.redirect import get_redirect_from_json
def make_racestat_get(
token,
endpoint,
... |
991,030 | 54aed481c901cca120906facb87d4dea01905ae7 | WTF_CSRF_ENABLED = True
SECRET_KEY = 'changed-in-production'
|
991,031 | 42e6df731eab9360d1f0a0fcacb70c3f2af9b2a5 | #!/usr/bin/python
# Env: python3
# Rewrite by afei_0and1
'''
9、将列表中的0进行后置(列表重排)
输入一个整数列表,列表中穿插存入了元素0。要求编写程序,将列表中所有的0后置,同时保持其他元素的顺序不变。例如:
输入列表为[1,3,0,2,0,5],则需要返回[1,3,2,5,0,0]。
解题思路:
方法一:创建一个新的列表,通过遍历旧的列表,将旧列表中的元素按照新的规则放入新列表完成重排,这种重排方式被称为
非原地重排;
方法二:通过对旧列表的元素进行交换和移动操作实现重排,这种重排方式被称为原地重排。原地重排可以节省不必要的内存
空间,但是需要需要进行额外的... |
991,032 | 7393a02fb05cd4b9eea564c5f08f8db28debcd79 | """
connection to database
"""
import datetime
import logging
import os
import sqlalchemy
from sqlalchemy import orm
from db.db_connect import TABLE_NAME, COLUMN_TYPES
from db.mysql_connect import create_mysql_session
from straddle.market_watcher_parser import getOptionMW
from straddle.strategy import Strike
# ke... |
991,033 | d83e32b3a5431e0521b6e0a3d73a7c3836bb4265 | import unittest
from fizzbuzz import fizzbuzz, FizzBuzzInt
class FizzBuzzTestCase(unittest.TestCase):
def test_fizzbuzz_1_retorna_1(self):
result = fizzbuzz(1)
self.assertEqual(1, result)
def test_fizzbuzz_2_retorna_2(self):
result = fizzbuzz(2)
self.assertEqual(2, result)
... |
991,034 | 55796b97be2983a3ae5cd502c8bf6a7ba206b79e | import numpy as np
class BinaryHigherOrderModel:
"""Higher order model.
"""
def __init__(self, interactions: list):
self.interactions = interactions
indices = set(self.interactions[0].keys())
for coeff in self.interactions[1:]:
for _inds in coeff.keys():
... |
991,035 | 44ecea8b6b486dab3df130b6c7ccc154f9142742 | a = float(input())
while True:
n = float(input())
if(n==999): break
print('{:0.2f}'.format(n-a))
a = n |
991,036 | 3f2beb22acf9bfeac28e763fae22fe33186eec08 | import Tkinter as tk
from lxml import etree
element_to_view_map = {}
# this is a mixin class that is used to implement data binding between views
# and models; it shouldn't be instantiated on its own because it has no model
# without deriving a specific type of view from it
class ViewWithUpdate(object):
def up... |
991,037 | c126000499f4647d070a77d2885586bbd14bdd8b | from flask import Flask
from flask import render_template
from twilio.rest import TwilioRestClient
import twilio.twiml
from flask import request
app = Flask(__name__)
def makePhoneCall():
account_sid = "ACc593f66f0b7dd76aefcc8dba0ad31361"
auth_token = "96aa5dffecbd672bfa957570da84d43b"
client = TwilioRe... |
991,038 | 71e4fae2e9569aa807c12f0f32dac83cd76a278f | from src.tools import vector
class LineSprite:
def __init__(self, size=None, color=None, arrow_type=None, visible=True):
self.size = size if size else vector.zero
self.color = color if color else "gray"
self.arrow_type = arrow_type
self.visible = visible
self.sprite_type = ... |
991,039 | efa187620d712fe1e5dc1e6a4383cd72c3ec7d14 | from settings import DATABASES
import os
import sys
print(DATABASES)
|
991,040 | ee79a65eaecb8adcbc0c4a97a40d9252f3ac7b78 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import abc
import logging
import os
import time
from functools import partial
import numpy as np
import ray
import torch
from ray import tun... |
991,041 | 0cce3781f3f2171f07a0a195d10f917debe5aff5 | import math
def golden_section(f,a,b):
'''The parameters to the golden_section function to compute the minimum are
f - objective function
a - starting point
b - ending point'''
# Setting the Golden Numbers
g = (3 - math.sqrt(5)) / 2
gn = 1 - g
n = 0 #Se... |
991,042 | 480fd619eb11e348ea037e2d53a8e33f69132ab7 | n,h = map(int,input().split())
A = []
B = []
ans = 0
for i in range(n):
a,b = map(int,input().split())
A.append(a)
B.append(b)
#aの最大値を求める。
maxa = max(A)
#maxaのうち、bが最小の刀を求める。これを刀sとする。刀sを取り除く
minb = 10**10
s = 0
for i in range(n):
if A[i] == maxa and B[i] < minb:
minb = B[i]
s = i
B.pop(... |
991,043 | 7dbeb00e94fc50419a9c277380dd0f7a0e25d357 | import math
import numpy as np
from sklearn.neighbors import kneighbors_graph
from sklearn.cluster import SpectralClustering
class NcutSegmenter:
def __init__(self, values, k):
self.values = values
self.k = k
def customNcuts(self):
""" Return segmentation label using classic Ncuts ""... |
991,044 | b15fd43e94854b2c2337210631cb18974f0fa441 | # Generated by Django 3.1.5 on 2021-03-13 15:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0011_auto_20210122_1154'),
]
operations = [
migrations.AddField(
model_name='user',
name='own_reviews',
... |
991,045 | 30a26b3d17faf9a0f585c0cc41dfb6ac7643eb9b | # -*- coding: utf-8 -*-
"""
controller GUI
========
"""
import traceback, sys
from eurotherm_reader.GUI.styles import style, img
from eurotherm_reader.controller.eurotherm_controller import CK20
from eurotherm_reader.controller.serial_ports import SerialPorts
from eurotherm_reader.analysis.cal_analysis import Thermoco... |
991,046 | f30abb71fc7d65d784a82c458e5e85ee7d0b5af8 | from event import event
from event import subscriber
from event import publisher
class Ev(event.Event):
def __init__(self):
super(Ev, self).__init__("event1111")
def serialize_payload(self):
return self.payload
def deserialize_payload(self, payload):
return payload
clas... |
991,047 | d0905618c803b10443a39e1e3cc116d2c5f7c64c | __author__ = 'branw'
import os
import base64
import tempfile
from openstack import connection
import wsme
from wsme.rest import json as wsme_json
class Base(wsme.types.Base):
def to_dict(self):
return wsme_json.tojson(self.__class__, self)
@classmethod
def to_obj(cls, values):
# wsme_... |
991,048 | 47d7d679efb2415d741f3aee91db74e5c677b252 | import numpy as np
from downsample import *
import sys
sys.path.append('../') # import from folder one directory out
import util
import pandas as pd
import data_handler
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
rc('font', family='serif', size=12)
df = util.csv_to_df('../Data... |
991,049 | a7a95cf5276a5193eb586eaf63b0d97928a52186 | from .registry import DATASETS
from .xml_style import XMLDataset
@DATASETS.register_module
class VOCDataset(XMLDataset):
CLASSES = ('aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car',
'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse',
'motorbike', 'person', 'pottedpla... |
991,050 | fd26947f7bc31f1f4f02891d74181b50b007635f | #!/usr/bin/env python
"""
nxosm was written to extract and build a road network using OSM data;
to build adjacency matrix with geolocation information for each node.
Citation Format:
Legara, E.F. (2014) nxosm source code (Version 2.0) [source code].
http://www.erikalegara.net
"""
__author__ = "Erika Fille L... |
991,051 | d154c5ed0e45c496db12ce01909e0d25ded1d97d | import pandas as pd
from models import DATACONTRACT
from loguru import logger
class DraftParser:
def __init__(self):
pass
def parse_draft_info(self, draft_soup, info_dict):
# DRAFTTRACKERCOLS = [UNIQUE_ID, LEAGUE_ID, TEAM_ID, TEAM_NAME, DRAFTORDER, CLASSORDER, PLAYERNAME, PLAYERPOS]
t... |
991,052 | d4e44aae2049ab147eedd3a1c3669d2b13acf610 |
def area(largura, comprimento):
return largura * comprimento
def divisor():
print('-='*30)
def msg(msg):
print(msg)
def lerteclado(msg):
return input(msg)
msg('Controle de Terrenos')
divisor()
largura = float(lerteclado('Largura (m): '))
comprimento = float(lerteclado('Comprimento (m): '))
diviso... |
991,053 | fc3a28c8193bdcc7fe7a8d93fc6e85a16e798c3f | import copy
import pathlib
import pickle
import time
from functools import partial, reduce
import numpy as np
import torch
from det3d.core.bbox import box_np_ops
from det3d.core.sampler import preprocess as prep
from det3d.utils.check import shape_mergeable
class DataBaseSamplerV2:
def __init__(
self,
... |
991,054 | 21541297a9acd6d12f2470d7327cafb575bc0b1b | #Importamos las librerías
import numpy as np
import matplotlib.pyplot as plt
import pyaudio
from pyaudio import PyAudio as pa
import math
import wave
import time
from scipy import signal
#%% Seteamos el rate
#def bitrate(rate):
# global BITRATE
# BITRATE=rate
BITRATE = 44100
def print_bitrate():
print(BIT... |
991,055 | f59fa272ae3f44a1d8e6b2ba2f3db44bebbba6f4 | from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup
from urllib.request import urlopen
im... |
991,056 | 89387ff9bbc8b069b79bcba773b734aa795c5544 | """
This code computes the refractive index of a protein,
using PaliwalTomarGupta2014 Uricase as a base.
We use the relation:
n^2 = A + B/(1-C/L^2) + D/(1-E/L^2)
n: real part of refraction index
L: wavelength
A=-97.26
B=95.053
C=0.016
D=0.0647
E=0.521
We assume imaginary part of refractive index=0.024 (constant)
"""
i... |
991,057 | 76ef15fe0922bcedfea1d057e36e8f9b5cbf1df4 | from PyQt5.QtCore import QThread, pyqtSignal
class ThreadRefreshOnOrderStatus(QThread):
signal = pyqtSignal('PyQt_PyObject')
def __init__(self, parent_class):
super().__init__()
self.output_list = []
self.parent_class = parent_class
def run(self):
self.output_list.clear()... |
991,058 | e6a704e16e0285e7618e9947cf5be9034a6f8737 | import json
import os
from argparse import ArgumentParser
from typing import List
from tensorflow import keras
from calamari_ocr.ocr import SavedCalamariModel
from calamari_ocr.ocr.model.ensemblegraph import EnsembleGraph
from calamari_ocr.ocr.model.graph import Graph
def split(args):
ckpt = SavedCalamariModel(... |
991,059 | c6a0c5cbaf443d7092a6f2c780ce58422eebd166 | #importing libraries
import tensorflow as tf
import numpy as np
numpy_inputs = np.mat([[5,2,13],[7,9,0]], dtype = int)
inputs = tf.convert_to_tensor(value = numpy_inputs, dtype = tf.int8)
#session start
with tf.Session() as sess:
print(sess.run(fetches = inputs))
print(inputs)
#session end
ses... |
991,060 | d89fbd6eb51a7a79e69344d77408949b6b440a08 | from db import Column, Integer, ForeignKey, Boolean
from models.abstract_models import BaseModel
from models.clinical_story.medicine_type import MedicineTypeModel
class MedicineModel(BaseModel):
__tablename__ = "medicaciones"
medicine_type_id = Column("medicamentos_id", Integer, ForeignKey(MedicineTypeModel... |
991,061 | 3b0233a4157595ea5706411522878e91d9c06684 | class DependencyNotFound(Exception):
pass
class DependencyResolvingException(Exception):
pass
|
991,062 | a4bea911faaf5f3e2df3c1c159df7f7ffb0aaf4b | # Copyright 2019 British Broadcasting Corporation
#
# 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 applicable law or agree... |
991,063 | 2bcb2d5fdf0374f7f5267538c67d96db7786c895 | import random
from indy import ledger
from perf_load.perf_req_gen import RequestGenerator
class RGConfigChangeState(RequestGenerator):
_req_types = ["111"]
def _rand_data(self):
return str(random.randint(0, 99999999))
async def _gen_req(self, submit_did, req_data):
return await ledger.b... |
991,064 | d80f4da69a92d9e131b26f64d9fe0dff5b75ac47 | #https://github.com/micropython/micropython-lib/tree/master/umqtt.simple
#https://github.com/micropython/micropython-lib/blob/master/umqtt.simple/example_pub.py
#https://github.com/micropython/micropython-lib/pull/91#issuecomment-239030008
# wlan = network.WLAN(network.STA_IF)
# while not wlan.isconnected():
# ... |
991,065 | 5fe07a5d67c46d3850ca0e30fd59f27e4f4df9b7 | #!/usr/bin/env python2
from limiti import *
usage="""Generatore per "salti".
Parametri:
* N (primo numero in input)
Constraint:
* 1 <= N < %d
""" % MAXN
from sys import argv, exit, stderr
import os
from numpy.random import seed, random, randint
from random import choice, sample
if __name__ == "__main__":
try:... |
991,066 | 03748f954e72c92e8328a46cfa50c8cd0ac2a197 | # -*- coding:utf-8 -*-
import time
import cv2
t_start = time.time()
fps = 0
# 图片识别方法封装
def discern(img):
global fps
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cap = cv2.CascadeClassifier(
"Cascades/haarcascade_frontalface_default.xml"
)
faceRects = cap.detectMultiScale(
gray, sca... |
991,067 | 31fff8ea911283dac3aa2a61892ab413c095aaf8 | # 位1的个数
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
# # 我的想法
# return bin(n).count("1")
# 人家的解法
res = 0
while n != 0:
n = n & (n - 1)
res += 1
return res
# # 人家的... |
991,068 | 894d3cdee4104276bb7de2d6cbbe0b0112530fe3 | # Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = 'replace with Web client ID'
|
991,069 | 5d3c53d1563bd4df71f90640b4b44b1399d1598c | print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do \n newlines and \
t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
prin... |
991,070 | af8401e5fab460f20603afb5cee6a79e673622e9 | #!/usr/bin/python
# -*- coding: utf-8 -*-.
# Mapper Input
# The input is a 2-element list: [document_id, text],
# where document_id is a string representing a document identifier and text is a string representing the text of the document.
# The document text may have words in upper or lower case and may contain punc... |
991,071 | 12859a199d393efad1835e88389dab661d69265f | '''
A serial commonly regular expressions is listed below. It includes:
* Regular float number, like ``1.0``, ``0.9``
* Scientific float number, like ``1.0e4``
* Float number with percentage, like ``93.75%``
'''
import re
# Used to match regular float number
# For example: -0.1
reFloatNumber = re.compile('... |
991,072 | 31afe096a27986efd87208d78af3a2ebd7577d24 | ### Simple Array Sum - Solution
def simpleArraySum(arr):
print(sum(arr))
size = int(input())
arr = tuple(map(int, input().split()[:size]))
simpleArraySum(arr) |
991,073 | 08ab4e0219024e1392a477eb156297e62b56f721 | # Import Module --------------------------------------------------------------#
import doctest
# Test Suite Class Definition ------------------------------------------------#
def testToUpper(_in):
"""
>>> testToUpper('test')
'TEST'
"""
return _in.upper()
# Main ----------------------------------... |
991,074 | d59360f7aebc5885077834d95842ee0cc5085e29 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 28 17:07:19 2019
@author: Mark
"""
import numpy as np
import TicTacToeGame
from IBot import IBot
import pandas as pd
import random
import TQmodel_train
WIN_VALUE = 1.0 # type: float
DRAW_VALUE = 0.5 # type: float
LOSS_VALUE = 0.0 # type: float
def hash_value(board_s... |
991,075 | 2a6d7b01d1b88f793425a5413fae77e48f4e9d44 | # uvicorn server:app --reload
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import pybullet
from concurrent.futures import ThreadPoolExecutor
from robot import NoSuchControlType, robot
import asyncio
from logger import Logger
from dtos import *
app = FastAPI()
@app.on_event("startup"... |
991,076 | aaed9f6d2c9aab3eeddd57478fb733f7c8fe160c | # 2022.12.27-Changed for EDSR-PyTorch
# Huawei Technologies Co., Ltd. <wangchengcheng11@huawei.com>
# Copyright 2022 Huawei Technologies Co., Ltd.
# Copyright 2018 sanghyun-son (https://github.com/sanghyun-son/EDSR-PyTorch).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this... |
991,077 | 79efecaaa51cbfaad0450d319c71a6e530d4e719 | # coding: latin-1
'''
Canal K+ voltage-dépendant.
'''
from brian import *
El=-70*mV
tau=20*ms
R=50*Mohm
C=tau/R # capacité
tauK=1*ms
va=-60*mV # demi-activation
k=3*mV # pente
#gK=1/R # conductance K+ maximale (ici = conductance de fuite)
EK=-90*mV # potentiel de réversion
eqs='''
dv/dt=(El-v)/tau + ... |
991,078 | f35d3dbfedeb135d05a4e92b768e78372334a560 | from collections import defaultdict
import numpy as np
import copy
import time
import sys
import json
import random
import csv
import socket
import math
from multiprocessing import Pool
from functools import partial
from help import send,receive
from sklearn import preprocessing
from phe import paillier
from phe import... |
991,079 | 8bd13414208de63739288562a0f19e7788018e4c | import z2edit
from z2edit import Address
from z2edit.util import Tile, chr_clear, chr_copy, chr_swap
# Graphics arrangement (numbers in expressed in hex):
#
# Western Hyrule = bank 2/3
# Eastern Hyrule = bank 4/5
# P1 = bank 8/9
# P2 = bank a/b
# P3 = bank 12/13
# P4 = bank 14/15
# P5 = bank 16/17
# P6 = bank 18/19
# ... |
991,080 | c762d426837882e75acadec666191436b33821aa | #AD1-1 - Questão 1
#Programa Principal
entrada = input("Digite um número inteiro ou tecle enter para sair: ")
pi = 3.1415
while entrada != "": # loop
raio = int(entrada)
if raio %2 != 0:
perimetro = 2*pi*raio
area = pi*raio**2
print(f"Área e Perímetro do Círculo de Raio {raio:d} são {a... |
991,081 | 17c8ebb74015e86a452a86702d8db207bf28d532 | ####################################################################################
#法1:利用后缀表达式计算来实现
#输入:以空白作为分隔
#输出:一个计算结果
###################################################################################
#line = input('Infix Expression: ')
line = '( ( 1 + 2 ) * ( 3 + 4 ) - 27 ) / ( 2 + 1 )'
value = suf_exp_evaluat... |
991,082 | 88974182893c6178d01505be789195f2fad0073b | # git commit -m "code: Solve boj 01107 리모컨 (yoonbaek)"
# 도르마무를 해야하는 문제
# 자꾸 EOF로 틀리네요.... 테케 모두 통과되면 수정하겠습니다.
if __name__ == "__main__":
target_channel = input()
length = len(target_channel)
target_channel = int(target_channel)
broken_num = int(input())
broken_buttons = []
if broken_num:
... |
991,083 | 00592e64fba09c36d70082301ee04500806e9115 | class Solution:
"""
@param nums: a list of integers.
@param k: length of window.
@return: the sum of the element inside the window at each moving.
"""
def winSum(self, nums, k):
if k == 0:
return []
n = len(nums)
firstIndex = 0
result = [sum(nums[fir... |
991,084 | af2e9659c006fe781e87ecf33ee000417526f22a | # Imports the Google Cloud client library
from google.cloud import language_v1
import math
# returns a tuple containing the normalized direction and magnitude of sentiment
# (out of five using gaussian model)
def sentimentDetection(tweet):
client = language_v1.LanguageServiceClient()
document = language_v1.Do... |
991,085 | 76c40e916d132590b56520b3d04e260748ea94d1 | import simplejson
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
a = "C:/Users/rafayk7/Documents/Steam_game_comparer/allgamedata.txt"
with open(a) as data:
content = simplejson.load(data)
all_appids = []
total_games = len(content["applist"]["apps"])
for i in range(total_games):
appid... |
991,086 | f9ad711944dd1aaf330341d088936e7d9e9bc292 | def getList(inputString):
indentedTabsEachLine = []
splittedLines = inputString.split("\n")
for line in splittedLines:
# Remove all spaces from selected line
stringwithoutTabs = line.strip()
# LOGIC : tabs at beginning = substring index
tabsAtBeginnning = line.in... |
991,087 | f5af3b90dda5b1f6bc1ff1cbb36cc749dc3ac2bb | # Jason Shawn D Souza
# import numpy as np
# import math
# import os
# import time
#
# class KNN():
#
# def __init__(self):
# pass
#
# def splitarray(self,arr):
# return arr[:, :-1], arr[:, -1]
#
# def calculateDistances(self, training_data, test_instance):
# esubtract = np.subtrac... |
991,088 | 3dd56b5003ecad39727335c963688f5ec306ff5a | from datetime import timedelta
from django.db import models
from django.utils import timezone
class Visit(models.Model):
datetime = models.DateTimeField()
ip = models.CharField(max_length=15)
method = models.CharField(max_length=6)
url = models.CharField(max_length=1000)
referer = models.CharFiel... |
991,089 | 7f554102f3dcfc0dc3df6a92b51ae736b11394da | """SQL database for the template_pattern.py file."""
import sqlite3
connection = sqlite3.Connection("template_pattern.db")
connection.execute(
"CREATE TABLE IF NOT EXISTS Sales (salesperson text, amt currency, year integer,"
"model text, new boolean)"
)
connection.execute(
"INSERT INTO Sales values ('Tim... |
991,090 | d6e135d1d989b3b95b89bd34ef5c14ec2350a9b0 | """
@Time : 2021/3/30 22:19
@Author : Xiao Qinfeng
@Email : qfxiao@bjtu.edu.cn
@File : backbone_3d.py
@Software: PyCharm
@Desc :
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv3x3x3(in_planes, out_planes, stride=1, bias=False):
# 3x3x3 convolution with pad... |
991,091 | a3f9b1c38f64ced9d95a514b681d467d3c2f2c8e | import logging
DOMAIN = "tavos_water_outage"
_LOGGER = logging.getLogger(__name__)
MONITORED_STRING = "monitored_string"
|
991,092 | ecf86737420eb963c9844f74fbe9498331ae5ee0 | from bravado.client import SwaggerClient
from collections import Counter
from getGeneIdList import getGeneIdList
import xlsxwriter
# Connects to cbioportal database api
# Turned off validation requests because of discovered incorrect error throwing
cbioportal = SwaggerClient.from_url('https://www.cbioportal.org/api/ap... |
991,093 | 24a3c385c5b88fe8d6c34f9b43943b696b5564db | from flask import render_template
from app import app, headers
from flask import request
import requests, os
@app.route('/')
def index():
return render_template('index.html')
@app.route('/notify', methods=['POST'])
def notify():
fcm_token = request.form['fcm_token']
data = {}
if 'url' in request.fo... |
991,094 | f576769cd09868e815de6021d7094adb3f7dc5e0 | #-- coding: utf-8 --
# ******
# __author__ = 'chaoneng'
# __time__ =2017/4/25 9:59
# ******* |
991,095 | b9a9ac163f02e2b631047ef87a4a84752f2e082a | import os
os.system("sudo apt-get install mosquitto")
os.system("sudo apt-get install mosquitto-clients -y")
os.system("pip3 install paho-mqtt")
os.system("./configure.sh")
print("Username:")
username = input()
command = "mosquitto_passwd -c /etc/mosquitto/pwfile " + username
os.system(command)
os.system("sudo systemct... |
991,096 | 3c14c503f7b8d5000af42eec27f9505afe280164 | #!/usr/bin/python
import fileinput
import itertools
nums = [ int(ln) for ln in fileinput.input() ]
seen = set()
value = 0
for n in itertools.cycle(nums):
value += n
if value in seen:
print(value)
break
seen.add(value)
|
991,097 | b8a66e4cbf3b9c8c9822a5aa8be26ac0ecf79a77 | # Copyright 2012 Nebula, Inc.
#
# 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 applicable law or agree... |
991,098 | 4dc55b4fd56627cc54e648ea872e085d9065fc47 | magicians = ['alice','david','carolina']
for magician in magicians: #for循环遍历list, magician是个变量,建议变量名和list名称相似,比较有意义,通常list名称为复数,变量名称为单数
print(magician)
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your n... |
991,099 | d378d778c4d9bf9d5085feeb9e0dfb3be191484f | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# A script to update an XML file in order to:
# - Include a correct path to the DTD file
# - Include a correct path to some LTL-to-Buechi tool
import os
import sys
import resource
import subprocess
import signal
import xml.dom.minidom
# ======================================... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.