index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
993,100 | a3ffd918557e8c9f56a41195d2feb35a7e5ae975 | frase = str(input('Digite uma frase: ')).strip()
fraseu = frase.upper()
print('A letra "A" aparececeu {} vezes'.format(fraseu.count('A')))
print('A primeira letra A apareceu na posição de índice {}'.format(fraseu.find('A')))
print('A posição da última letra A é {}'.format(fraseu.rfind('A')))
|
993,101 | d93969787e72c446f6037b7c0e65681989506531 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 28 15:41:31 2018
速度预测
利用前面的TIMESTEPS个数据预测接下来的PREDICT_STEPS个数据(仅测试)
@author: lankuohsing
"""
# In[]
import numpy as np
import tensorflow as tf
from tensorflow.contrib import rnn
import pandas as pd
import matplotlib as mpl
from sklearn.preprocessing import MinMaxScaler
fro... |
993,102 | 7502ad98f1f2ce1279d4724f944b27df9ec6caa1 |
### filter
## filter()函数用于过滤序列
# filter()也接收一个函数和一个序列。filter()把传入的函数依次作用于每个元素,
# 然后根据返回值是True还是False决定保留还是丢弃该元素。
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
##删空字符串
def not_empty(s):
return s and s.strip() #用与非判断是否为空,strip应该用于去空
list(filter(n... |
993,103 | c27dc2f129e924bad7dd6c7380f4fae238386f67 | """
Api tests for login and registration user
"""
import json
import allure
import requests
import pytest
from tests_api.config import URL_AUTH, AUTH_PAYLOADS, HEADER
@pytest.mark.usefixtures('delete_user_and_close_conn')
class TestAuth():
@allure.feature("Login admin api")
@allure.story('Admin have an abili... |
993,104 | 0a745111498707b1f87248c86d2d7d8fc664d89b | #contains all sorting algorithms
'''
FUNCTION bubble
@param nums - list of numbers to sort
@param sz - size of list
@param graph - module for graphing
@param plt - matplotlib plt
@return number of swaps
'''
def bubble(nums, sz, graph, plt, GRAPHICS):
swaps = 0
for i in range(len(nums)-1, 0, -1):
for j ... |
993,105 | 0bedb127cf5ca5ab2a3f894e70540aeee99a9831 | from datetime import datetime
from django.db import models
from markdown import markdown
from smartypants import smartyPants
from taggit.managers import TaggableManager
class ArticleManager(models.Manager):
def published(self):
return self.filter(status=Article.PUBLISHED_STATUS)
class Article(models.Mod... |
993,106 | 7b53733e5b412e28776ec9028f6ba80673baf575 | from .vpp_papi import FuncWrapper, VPP, VppApiDynamicMethodHolder # noqa: F401
from .vpp_papi import VppEnum, VppEnumType # noqa: F401
from .vpp_papi import VPPIOError, VPPRuntimeError, VPPValueError # noqa: F401
from .vpp_papi import VPPApiClient # noqa: F401
from .vpp_papi import VPPApiJSONFiles # noqa: F401
from... |
993,107 | 423efd696401d12ba3f19b4579a2be1c4000c7e3 | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
chrome_options = webdriver.ChromeOptions()
prefs = {
# "profile.managed_default_content_settings.images": 2
}
chrome_opti... |
993,108 | 5d37674fbe67015aa694d9661c05ce944a369898 | import csv
import json
def to_text(fname1, fname2):
with open(fname1, newline='') as csvfile1:
with open(fname2, 'a', newline='') as textfile:
reader = csv.reader(csvfile1, delimiter=',')
next(reader, None)
for id, name, latitude, longitude in reader:
try:
s = '{{from:{{name: \'Columbus\', coordin... |
993,109 | b7b94f9e5a616808366206da16d46b53f9ed2013 | #!/usr/bin/env python
#
#
# This is the main iot console services CGI
# it allows iot devices to register via RT_REGISTER
# it fetches iot device status via RT_STATUS
# it sends set commands to iot devices via RT_CONTROL
#
# the FCGI is complaint with flup version for python 2.x
# flup version: flup 1.0.3.dev-2... |
993,110 | e20d660cff53b7f9097309e7de02963fd0272f3f | print("Ведите сначала класс, потом фамилию через энтер")
class_1 = input()
surname = list(input())
name = ['v', 'a', 'd', 'i', 'm', 16]
print('Номер 1 - ', name[1:-1]) #Задание номер 1
print('Номер 2 - ', name + [class_1]) #Задание номер 2
print('Номер 3 - ', name + [class_1]+surname) #Задание номер 3 |
993,111 | d66a5f7e4d25fd9fd0f597cb032d01912799335e | import numpy as np
import matplotlib.pyplot as plt
from blimpy import Waterfall
from scipy.signal import detrend
import BL21BurstData as BL21
def load(filename, info, tstart, tstop):
'''
Loads file data as a waterfall plot type array and can print data info
Inputs:
filename - name of fi... |
993,112 | 05cda59fede60d3067a35897c3c3f65a82e6e963 | # """"
# List Comprehensions
# """
# ls = [i for i in range(100) if i % 3 == 0]
# print(ls)
#
# """"
# Dictionary Comprehensions
# """
# dict1 = {
# i: f"Item{i}" for i in range(1, 101)
# if i % 5 == 0
# }
# dict2 = {
# value: key
# for key, value in dict1.items()
# }
# print(dict1, "\n", dict2)
#
# ""... |
993,113 | 3a69df190bf0ccedcc2f17ad2d26587083d364d9 | #
# @lc app=leetcode.cn id=70 lang=python3
#
# [70] 爬楼梯
#
# @lc code=start
class Solution:
def climbStairs(self, n: int) -> int:
#方法2:动态规划 + 空间优化
a = b = 1
for i in range(n):
b, a = a + b, b
return a
'''
#方法1:动态规划
#时间复杂度:O(n)
#空间复杂度:O(n)
... |
993,114 | 175345af9b4435a2bad90713e8478cac0d8c4c08 | /home/alex/myenv/zodiac/eggs/venusian-1.0a8-py2.7.egg/venusian/tests/fixtures/importerror/__init__.py |
993,115 | cf7f39ce28793085d196cdeedd2f35e69d985012 | '''
Sample Unit Test examples
'''
import unittest
class ExampleTests(unittest.TestCase):
def test_fizzbuzz_good(self):
output = []
for n in xrange(100):
output.append(str(fizzbuzz(n) + '\n'))
with open("fizzbuzz-output.txt", "r") as expected:
i = 0
... |
993,116 | 600755ef3214548a7046a1932d419a2a3dfd24b0 | import matplotlib.pyplot as plt
# if you need to create the data:
#test_data = process_test_data()
# if you already have some saved:
test_data = np.load('test_data.npy')
fig=plt.figure()
for num,data in enumerate(test_data[:12]):
# cat: [1,0]
# dog: [0,1]
img_num = data[1]
img_data = data[0]
... |
993,117 | 41a210487501c82d9321133e4d648b3402f447fb | from django.shortcuts import render
from django.template.context_processors import csrf
from django.http import HttpResponseRedirect
from django.core.exceptions import ObjectDoesNotExist
from .models import Review,Movie,User
from datetime import datetime
import numpy as np
import pandas as pd
import preprocess_kgptalk... |
993,118 | 80dde7aa7cc1ae3bed8f01bb9e9517d4e75aa7ae | """Dataloader Wrapper"""
from __future__ import absolute_import
import six
from . import sampler as _sampler
class DataLoaderNgnBase(object):
# for distinguishing from other dataloader
_attr_ngn_dataloader = True
def __init__(self, dataset,
batch_size=None,
shuffle=Fal... |
993,119 | e29baa0110e18dff5bbb36868d08fc3c43d1e90a | """
:class:`.DataBC` geocoder.
"""
from geopy.compat import urlencode
from geopy.geocoders.base import Geocoder, DEFAULT_SCHEME, DEFAULT_TIMEOUT
from geopy.exc import GeocoderQueryError
from geopy.location import Location
from geopy.util import logger
__all__ = ("DataBC", )
class DataBC(Geocoder):
"""
Geo... |
993,120 | 02a3b5da8ea9f9633048c2660d403ed731069198 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 20:08:38 2017
@author: Padam Singh
"""
def vowel_check(char) :
"""
This function takes a character (i.e. a string of length 1) and
returns True if it is a vowel, False otherwise.
"""
try :
if len(char) > 1 :
print("Plase ... |
993,121 | 4f3305158cc18cf5fbf4db21bbc4fe8c1b11e01c |
# coding: utf-8
# In[4]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.backends.backend_pdf
import seaborn
import pandas as pd
import pickle
# get_ipython().magic(u'matplotlib inline')
# In[8]:
numFlights = pickle.load(open('numFlights.pickle', 'r'))
numConflicts = pickle.load(open('numConf... |
993,122 | b23376eb6b60808cc11584088e21215dcaed8e04 | import FrMaya.tools.AboutFrMaya as AboutFrMaya
reload(AboutFrMaya)
AboutFrMaya.show(update_btn = True, remove_btn = True) |
993,123 | 588f5a991b723c133f9c335ef46cfb1ad45e66cc | # RESTful API Example
from flask import Flask, request, redirect,render_template
import base64
import random
import time
app = Flask(__name__)
redirect_uri = "http://localhost:5000/client/passport"
client_id = '123456'
users[client_id] = []
auth_code = {}
oauth_redirect_uri = []
users = {
"zagjab": ["123456"]
}
... |
993,124 | b036865f0da93ee2a9bafba79a08fe165c30e6cc | import os
import sys
import unittest
from pygcam.windows import IsWindows
def printLink(path):
islink = os.path.islink(os.path.normpath(path))
sys.stderr.write("%s islink: %s\n" % (path, islink))
if islink:
path = os.readlink(path)
sys.stderr.write("Link: %s" % path)
# printLink(pa... |
993,125 | eb899bd8ed9a4a6b78e557a2d51b1a9fcf031130 | #!/usr/bin/env python
# coding=utf-8
money_all = 123.6 + 23.8 + 47.2 + 53.7
print("总金额:" + str(money_all))
money_pay = int(money_all)
print("实收金额:" + str(money_pay))
|
993,126 | 6168045ffa527a3391e406fcbbe33c3eb01d6493 | l=int(input())
n=int(input())
for i in range(n):
a,b=list(map(int,input().split()))
if(a==b and a>=l and b>=l):
print("ACCEPTED")
elif(a!=b and a>=l and b>=l):
print("CROP IT")
else:
print("UPLOAD ANOTHER")
|
993,127 | 8604dde45e34917ced0fd1836f188a329517519a | import numpy as np
import os
import json
import random
import sklearn
from sklearn.feature_extraction.text import TfidfVectorizer
import jieba
from sklearn.externals import joblib
class TfidfFormatter:
def __init__(self,conf):
self.text_use_which=conf["text_use_which"]
self.label_use_wh... |
993,128 | b00491900978cc7864a50a15a94bd034175f802b | # -*- coding: utf-8 -*-
from httoop.meta import HTTPSemantic
class URIType(HTTPSemantic):
def __new__(mcs, name, bases, dict_):
cls = super(URIType, mcs).__new__(mcs, name, tuple(bases), dict_)
if dict_.get('SCHEME'):
for base in bases:
if getattr(base, 'SCHEMES', None) is not None:
base.SCHEMES.set... |
993,129 | 08afddea4b8538089bcfd35d14150c827d399ed8 | # Copyright (C) 2013 Christopher "Kasoki" Kaster
#
# This file is part of "FancyProjects". <http://github.com/Kasoki/FancyProjects>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without ... |
993,130 | 5fda429c0cece5802011f7b9be3c31f24414df18 | # Author: Acer Zhang
# Datetime: 2020/10/12
# Copyright belongs to the author.
# Please indicate the source for reprinting.
from train import *
from reader import InferReader
DATA_PATH = "/Users/zhanghongji/PycharmProjects/CaptchaDataset/sample_img"
CHECKPOINT_PATH = "/Users/zhanghongji/PycharmProjects/CaptchaDatase... |
993,131 | 8eeab5738a954213262912cc81a7e014626b07bc | #!/usr/bin/python
import os
import pandas as pd
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', default="experiments/HAN/result/", help="Directory containing the dataset")
def merge(basedir, output_file):
columns = "location_traffic_convenience,location_distance_from_business_dis... |
993,132 | 6a8fd584d0760ea193d1db551eddce5e5888f705 | # Generated by Django 3.2.6 on 2021-09-10 11:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('job', '0006_job_published_at'),
]
operations = [
migrations.AddField(
model_name='job',
name='experience',
... |
993,133 | b275678714d301a028aa868acf30bec68fc76782 | #!/usr/bin/env pyformex
# $Id$
##
## This file is part of pyFormex 0.8.5 Sun Nov 6 17:27:05 CET 2011
## pyFormex is a tool for generating, manipulating and transforming 3D
## geometrical models by sequences of mathematical operations.
## Home page: http://pyformex.org
## Project page: https://savannah.nongnu... |
993,134 | 76c5e286eb7d076e8c5dd7dfd1a10c4d06691eee | '''
-*- coding: utf-8 -*-
@Author : zoeyzhu
@Time : 2021/8/8 9:34 下午
@Software: PyCharm
@File : 1137.py
@function:
泰波那契序列 Tn 定义如下:
T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2
给你整数 n,请返回第 n 个泰波那契数 Tn 的值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/n-th-tribonacci-number
著作权归领扣网络所有。商... |
993,135 | ff35a5699163e5c8d49bb8afd0741ea7c173048a | from PIL import Image
# filename = r'C:\Users\..\01.jpg'
filename = r'./Importing files/trash/01.jpg'
Image.open(filename)
|
993,136 | 5057f3e4128a0f8af284fd42060c3cde30604f79 | def get_dvalue(s):
if len(s) < 2:
return 0
s.sort()
dvalue = 0
for i in range(0, len(s)-1):
if s[i+1]-s[i] > dvalue:
dvalue = s[i+1]-s[i]
return dvalue
if __name__ == "__main__":
s = [int(n) for n in input()[1:-1].split(',')]
print(get_dvalue(s))
|
993,137 | 7cf4507fe1477673481797c1a55301912c0500c1 | '''
void call(int n){
int i = 1;
CHECK_NUM:
int x = i;
if ( x % 3 == 0 ){
cout << " " << i;
goto END_CHECK_NUM;
}
INCLUDE3:
if ( x % 10 == 3 ){
cout << " " << i;
goto END_CHECK_NUM;
}
x /= 10;
if ( x ) goto INCLUDE3;
END_CHECK_NUM:
if ( ++i <= n ) goto CHECK_NUM;
cout << endl;
}
... |
993,138 | ef3c20230b3c20885c43ed60b977be761448147e | from numpy import*
v = array(eval(input("digite as notas: ")))
a =min(v)
b = sum(v)
t = size(v)
y = (b - a)/(t - 1)
print(round(y, 2)) |
993,139 | 1b9092ba0e6d320ebb6e5922dd3e07b464efde78 | from turtle import *
from random import randint
import string
for step in range(16):
speed(0.1)
write(step,align="left")
right(90)
forward(10)
pendown()
forward(150)
penup()
backward(160)
left(90)
forward(20)
try:
ada= Turtle("turtle")
ada.color("red")... |
993,140 | 11fead29a9fbb90cf234518be4a67048ecfa7427 | """
2. What is duck typing philosophy of python
"""
"""
Duck Typing is a type system used in dynamic languages. For example, Python, Perl, Ruby, PHP, Javascript, etc.
where the type or the class of an object is less important than the method it defines. Using Duck Typing, we do
not check types at all. Instead, ... |
993,141 | a107b8439bc5e198dd434f1f2d197e8ff22015ca | #!/usr/bin/sudo python
from serial import Serial
import datetime
arduino = Serial("/dev/ttyS1", baudrate=115200, timeout=3.0)
success = 0
failure = 0
echoedPayload = ""
timeout = 1
print("Serial Test: The tinker send a payload containing a number from 0 to 10,000, which will be echoed back by the arduino."
"The e... |
993,142 | a73c4b055c00b389e2d8e70a30a2608051a02492 | from mmrcnn import model as modellib, visualize
import os
#os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]='-1'
import coco
import skimage.io
from datetime import datetime
import cv2
WEIGHTS_DIR = "./weights"
TEST_PIC_DIR = "./testpictures"
class_names = ['BG', 'person', 'bicycle', 'car... |
993,143 | 35cd775a8631cb16ab25afe73cbb71b4b58d6f71 | import csv
import pandas as pd
import numpy as np
from sklearn import svm
import numpy as np
from numpy.random import randn
from numpy.random import seed
import properties as prop
import quandl
delta=prop.delta
target_index=prop.target_index
dependency=prop.dependency
authtoken=prop.authtoken
start_date=... |
993,144 | d8c99e58f18169075093d6a471bc3225649a879a | ii = [('ShawHDE.py', 1), ('WilkJMC3.py', 1), ('TennAP.py', 1), ('FitzRNS3.py', 2), ('WilkJMC2.py', 1), ('WestJIT2.py', 1), ('BackGNE.py', 3), ('WheeJPT.py', 1), ('FitzRNS.py', 3), ('MackCNH2.py', 3), ('JacoWHI2.py', 1), ('SomeMMH.py', 3)] |
993,145 | cca0064c44809b3113939c9c328af9147c472380 | #aplanar una lista anidada utilizando el bucle for teniendo en cuenta los diferentes tipos de datos que se encuentran en la lista a aplanar
datos = [1,5,8,2,[1,5,6,7,],[1,[4,2,5,7,]]]
plana = []
for dato in datos:
if type(dato) == int:
plana.append(dato)
elif type(dato) == list:
for elemento... |
993,146 | 8568b358fcb09693f4ca2270dd43931520107d0c | import os
import pandas as pd
import numpy as np
import statsmodels.api as sm
boston = pd.read_csv("./boston_house.csv")
print(boston.head(5))
features = boston[['CRIM', 'RM', 'LSTAT']]
target = boston[['Target']]
print(features.head(3))
multi_features = sm.add_constant(features, has_constant='add')
multi_model = sm... |
993,147 | bab61c0963275ddcffab62d35d0bad7424a75569 | # avg of time = 2.7401173988
from lxml import etree
import cv2
from scipy import ndimage
import pytesseract
import numpy as np
from PIL import Image
def making_data_ready(n):
img1 = cv2.imread(n+'.jpg')
img2 = 255 - img1[650:650+200,750:750+1800]
rotated = ndimage.rotate(img2, 90)
temp = img1.copy... |
993,148 | 811f518f6ab8f4064d4cd8b2daa5a24f8eba3753 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from core.task import on_start, on_message, on_timeout, on_output_message, Task # , on_sequence
# The following tasks us the following bit-based vocabulary:
# stay_quiet 01
# space 00
# period 10
# say 11
# i... |
993,149 | d323f46bf2de5538b021a267f890ecafa9de0b11 | from socket import *
import os
import sys
import datetime, time
from _thread import start_new_thread
class Server:
def __init__(self, port, fileDir):
self.confFile = "dfs.conf"
self.fileDir = fileDir
self.host = "127.0.0.1"
self.port = int(port)
self.sSocket = None
... |
993,150 | f1f57f9c2f417beaebd2d28a1eaaa808420a3cd3 | # Generated by Django 3.1.3 on 2020-12-09 11:36
import api.models.tag
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0008_auto_20201206_2028'),
]
operations = [
migrations.RenameField(
model_name='profile',
... |
993,151 | a3f33a164da01432173475fce82dcf43338d2599 | n = int(input())
a = list(map(int, input().split(" ")))
a = sorted(a)[::-1]
if n % 2:
ans = a[0] + 2 * sum(a[1:(n//2)]) + a[n//2]
else:
ans = a[0] + 2 * sum(a[1:(n//2)])
print(ans) |
993,152 | 95a154e27123b445c5f91696e47933fded8aa5c5 | # MIT License
#
# Copyright (c) 2016-2022 Mark Qvist / unsigned.io
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, cop... |
993,153 | 16c854e2ddf8e252df552e8273a1f757253bf9bf | from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Float
from sqlalchemy.orm import relationship
import sqlalchemy.dialects.postgresql as postgresql
from sqlalchemy.sql import func
from .orm import Base
import uuid
class User(Base):
__tablename__ = "users"
id = Column(postgresql.UUID(as_uu... |
993,154 | e205f1a1921c93f4398e69fa09c65727b6cec58d | import os
from unittest import TestCase
import warnings
import torch
import torch.nn as nn
from mock import patch, Mock, ANY, MagicMock
import torchbearer
from torchbearer.callbacks import TensorBoard, TensorBoardImages, TensorBoardProjector, TensorBoardText
class TestTensorBoard(TestCase):
@patch('tensorboard... |
993,155 | c8c3d1ff0833808c3e006099e1c49a2902adea9a | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.urls import path
urlpatterns = []
|
993,156 | 35b8ddf13193f62e08ecce08fda73cb9aebf06df |
# Question 28
# Question:
# Define a function that can receive two integer numbers in string form and compute
# their sum and then print it in console.
def sum_of_two_number_string (str1,str2):
return int(str1)+int(str2)
print(sum_of_two_number_string("324","34243"))
def concatenate_two_strings(s1,s2):
return (... |
993,157 | a358271c86077ce8cd6bfae3fb1b3b85d481ea3e | ans = 0
loss = 0
for i in range(5):
x = int(input())
if x%10 != 0:
loss = max(loss, 10-x%10)
ans += (x+9)//10*10
print(ans - loss)
|
993,158 | 80fe5b6ae687ead6ebd2f5c2b71742f4fc72684c | """
https://community.topcoder.com/stat?c=problem_statement&pm=2235&rd=5070
https://www.topcoder.com/community/data-science/data-science-tutorials/greedy-is-good/
"""
def GoldMine(mines, miners):
# sanitize input
t = []
for mine in mines:
t.append([int(i) / 100 for i in mine.split(', ')])
... |
993,159 | 37014af3faa29f539078f795415c0ad13c786521 | import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from gui.RegisterPopup import Ui_Register
from gui.controllers.message_popup import MessagePopup
from gui.helperfunctions.helpers import combine_into_class
from server import Database
class RegisterPopup(QtWidgets.QDialog, Ui_Register):
def __init__(self, *ar... |
993,160 | 4221a91c4cd8500535e4ec33dec099161df507e8 | class VoucherService(object):
"""
:class:`fortnox.VoucherService` is used by :class:`fortnox.Client` to make
actions related to Voucher resource.
Normally you won't instantiate this class directly.
"""
"""
Allowed attributes for Voucher to send to Fortnox backend servers.
"""
OPTS_... |
993,161 | 4a026c6176a5ae5f87dfa11d389a130e2f6a9d8c | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 23:21:08 2019
@author: thebjm
"""
# import the necessary packages
from flask import *
from flask_mysqldb import *
from wtforms import *
import os
from werkzeug import secure_filename
from wtforms.fields.html5 import *
from wtforms.validators import ... |
993,162 | 48fb4c2c89003099b29c4bd56cdd3097b50f38aa | import math
from model.resnetfpn import ResnetFPN
import torch
from torch import nn
class TextDet(nn.Module):
# reference: https://github.com/SakuraRiven/EAST/blob/cec7ae98f9c21a475b935f74f4c3969f3a989bd4/model.py#L136
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(256, 256, 3, ... |
993,163 | 3ef2d9b2c59ff885eff01f5829dd6e433660f053 | import tensorflow as tf
def dqn(state_input, name, training=None):
with tf.variable_scope(name) as scope:
conv_1 = tf.layers.conv2d(state_input, 32, 8, strides=4, padding='same', activation=tf.nn.relu, name='conv_1')
conv_2 = tf.layers.conv2d(conv_1, 64, 4, strides=2, padding='same', activation... |
993,164 | dcae550b7c9b00aa80aac944ba68b0c4e22f51dc | # -*- coding:utf-8 -*-
# @Time: 2021/7/29 6:55 下午
# @Author: Elvin
'''
1.类变量(属性):类变量在整个实例化的对象中是公用的。类变量定义在类中,且在方法之外。类变量通常不
作为实例变量使用。类变量也称作属性。
2.数据成员:类变量或实例变量用于处理类及其实例对象的相关数据。
3.方法重写:如果从父类继承的方法不能满足子类的需求,就可以对其进行改写,这个过程称为方法的覆盖。
4.实例变量:定义在方法中的变量只作用于当前实例的类。
5.多态:对不同类的对象使用同样的操作。
6.封装:对外部隐藏工作细节。
7.继承:即一个派生类继承基类的字段和方法。继承允许把一个派生... |
993,165 | 6ca224679872a56fb8eb1b1fb372e0c6e0f0d9e0 | def get_hypotenuse(side1, side2):
return (side1 ** 2 + side2 ** 2) ** 0.5
def get_area(side1, side2):
area = (side1 * side2) / 2
return area
def get_perimeter(side1, side2):
perimeter = 2 * side1 + 2 * side2
return perimeter
def write_to_file(side1, side2, file_destination):
print(
ge... |
993,166 | a5f9f129056431df482892dca2d175d89fb68487 | #!/usr/bin/env python3
import sys
import json
import logging
import random
import time
from ratelimiter import RateLimiter
from jsonschema import validate
import singer
import singer.messages
import singer.metrics as metrics
from singer import utils
from singer import (UNIX_MILLISECONDS_INTEGER_DATETIME_PARSING,
... |
993,167 | 090fc3e86ede15c4221b3e8778ba7afc42c1485f | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder,
their colleagues and Ethan Swallow.
"""
########################################################################
# done: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
... |
993,168 | 700e8c5da83319e48b7c45522b1d13b262b7ae54 | import sys
import os
from trainpredict import TrainPredictData
import h5py
def get_existing_file(msg, skip=False):
"""Shows msg and asks for input until the input is an existing file.
:param msg: some message
"""
inp = None
while inp is None:
inp = raw_input(msg)
if skip and len(i... |
993,169 | 3dfb5444ef29577c7fc56652e8764985b9ab5697 | '''
# ---------------------------------- prg-----------------------------------------------
# Prime_Number.py
# date : 26/08/2019
# Find given number is prime or not
'''
#method for find prime number
def prime(n):
#Check base condition 1
if n < 2 :
return False
#Check base condition 2
if n == 2:... |
993,170 | d0b86ece98e6e802d41b22a977e8961671b528dd | # Simple example of reading the MCP3008 analog input channels and printing
# them all out.
# Author: Tony DiCola
# License: Public Domain
import time
import datetime
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
# Software SPI configuration:
CLK ... |
993,171 | dd1ad6a370feca5e9aa8f0f4d9781a245b93d774 | from splinter import Browser
from bs4 import BeautifulSoup
def init_browser():
# @NOTE: Replace the path with your actual path to the chromedriver
executable_path = {"executable_path": "chromedriver.exe"}
return Browser("chrome", **executable_path, headless=False)
def scrape():
browser = init_browser(... |
993,172 | bf7bb1ce4f98089f9e9ea875d418e9744374bc0b | class Player:
def __init__(self):
self.player_status = None
self.player_moves = []
p1 = Player()
p2 = Player()
game_turns = 0
game_board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
game_status = None
places_taken = []
def game_board_printing(game_board):
line = ""
for i in range(len(... |
993,173 | 3dcff9a70bf8c4491b70a4ab83da8b911fc495cb | import networkx
from networkx.convert_matrix import to_numpy_matrix
import numpy as np
from numpy.linalg import eig
import matplotlib.pyplot as plt
from scipy.sparse import csc_matrix
from matplotlib.pyplot import cm
# --------------------------- Modularity evolution --------------------------- #
def plot_Q(graph,NCom... |
993,174 | dc3ff6f66da18feb97ec00d500f4bcc6ed2a8b42 | class Demo:
def __init__(self):
print("parent constructor")
def func1(self):
print("func1")
class Demo1(Demo):
def func2(self):
print("func2")
def __init__(self):
print("child constructor")
class Demo2(Demo1):
def func3(self):
print("func3")
d2=Demo2()
d... |
993,175 | 11a4b9766a8845d4a2d47f46e5c40ec9b897756f | # Generated by Django 3.1.5 on 2021-02-11 09:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Cart... |
993,176 | cfba2efab8a2130941199efade9667cf18b4e794 | #!/usr/bin/env python
# coding: utf-8
# # Primeiros passos
#
# O interpretador Python é um cara legal que gosta de conversar, mas ele é um pouco repetitivo..
#
# Os notebooks Jupyter se comunicam com o interpretador, mandando suas mensagens e mostrando as resposta que ele dá.
#
# Clique no botão de Play para execu... |
993,177 | 393db6d24cdae2473f95c9234200ea264d4f3cc0 | #--encoding:utf-8--
from bag import Bag
from graph_visualized import MSTVisualized
class Edge(object):
_v = None
_w = None
_weight = None
_black = None
def __init__(self, v, w, weight):
super(Edge, self).__init__()
self._v = v
self._w = w
self._wei... |
993,178 | c21728dbc4bf168f17d0c2e0444a828e6420fa27 | #!/usr/bin/env python
## http://projecteuler.net/index.php?section=problems&id=25 ##
## What is the first term in the Fibonacci sequence to contain 1000 digits? ##
import math
def fib(n, fibs):
print "called fib(", n, ")"
fn1 = 0
fn2 = 0
if (n - 1) in fibs:
fn1 = fibs[n - 1]
else:
fn1 = fib(n - 1, fibs)
if... |
993,179 | dc36e1be00ee3c29ec4dcae5e35ea4b3e748376a | '''
PATTERN MatchedING WITH REGULAR EXPRESSIONS
'''
import re
## (1) Basic structure of RegEx from re module
dateUnderScore = re.compile(r'\d\d_\d\d_\d\d\d\d') ## \ is for exit, so put r outside
mo = dateUnderScore.search('I name a file as today_file_12_05_2019')
print('Matched pattern: '+ mo.group())
## (1.1) Gro... |
993,180 | a300191dbaedbd757a3f6dd27d0d080008ece33f | # Generated by Django 3.1.7 on 2021-03-14 07:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='note',
name='title',
field=mo... |
993,181 | d90b2351ce1f67b699a18797ebb0b9e2618d533b | import shutil
import tempfile
from django.contrib.auth import get_user_model
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from django import forms
from django.core.files.uploadedfile import SimpleUploadedFile
from django.conf import settings
from django.core.cache import ... |
993,182 | e39f96cdf55a59e94d37edb69248f676e8bf0f61 | __author__ = 'kpeterson'
import traceback, sys
def repl(prompt='lisp> '):
"""A prompt-read-eval-print loop."""
while True:
try:
val = eval(parse(raw_input(prompt)))
if val is not None:
print to_string(val)
except KeyboardInterrupt:
print "\nE... |
993,183 | 20ebf78543a8bbf3964244fd207bf57eeb603c56 | from Paasmer import *
import time
#Callback functions for subscribed feeds
def feed1_CB(name):
print("This is in feed1")
print(name)
def feed2_CB(name):
print("This is in feed2")
print(name)
def feed3_CB(name):
print("This is in feed3")
print(name)
###connecting to the Paasmer Edge docker device
test = Paasmer(... |
993,184 | 0868b627d13af092760be815ba19a47f965b5da9 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
993,185 | 5781f1c80b4e6fd0bbdeb017d828b09ee26c904f | from datetime import datetime, timedelta
from django.http import Http404, JsonResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.contrib import messages
import json
from django.core.serializer... |
993,186 | 48dfde97c63fe5dfc9850d255fca3c6a10641cd4 | # -*- Python -*-
# ----------------------------------------------------------------------
# Generate geometry
# ----------------------------------------------------------------------
playback 'geometry.jou'
# ----------------------------------------------------------------------
# Set discretization size
# -----------... |
993,187 | e5b174d0c56fe2575b5f977530623383c23bb9fe | # -*- coding: cp936 -*-
import re
c ="""fisixxrenxxdlkfsaxxqingxxwdlkjjixx
xiaoxxlwdhlkjxxzhuoxxdwlkn9kjxxmaxxddwdok"""
b = re.findall('xx(.*?)xx',c,re.S)
print b
#没有re.S输出的是:['ren', 'qing', 'lwdhlkj', 'dwlkn9kj']
#有re.S输出的是: ['ren', 'qing', '\nxiao', 'zhuo', 'ma']
#对比 sub的使用:替换的功能
s = "123abc123"
b = re.sub('123(... |
993,188 | 5fb0490508d42d6c1ab512ea0120f3852b008889 | #!/usr/bin/env python
from core.agents.Parameters import Query
from core.agents.web.Yahoo.Controller import Controller
from strategy.basic import basic
import matplotlib.pyplot as plt
import matplotlib.dates as matplotlibdates
def get_data_from_stock(stock_name):
query = Query()
query.add(Controller.PARAM_NAM... |
993,189 | 49f7b49ad6f7f37992a3d4bb410497f6d9582786 | def build_profile(first, breed, **user_info):
user_info['first name'] = first.title()
user_info['breed'] = breed.title()
return user_info
user_info = build_profile('jock', 'jack russel', size='medium',
health='dead')
# print(f"first name: {user_info['first name']}")
# print(f"breeed {user_info['breed']}")
# # print... |
993,190 | a19052cc6a36261db60ae1b6d22418edb1276d50 | import librosa
import os
import pandas as pd
import sys
sys.path.insert(0, '/home/huanyuan/code/demo/common')
from common.utils.python.metrics_tools import *
def cal_fpr_tpr(src_csv, pst_csv, positive_label, bool_write_audio):
# laod csv
src_pd = pd.read_csv(src_csv)
pst_pd = pd.read_csv(pst_csv)
sr... |
993,191 | d4efba6b82ed1e07d8ee0c74e587f016f9fe31e0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# 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.apach... |
993,192 | 78241da7bdffaed93855ddfb2c7384bec30f845a |
import os, sys, glob, pickle
import optparse
import numpy as np
from scipy.interpolate import interpolate as interp
import scipy.stats
from astropy.table import Table, Column
import matplotlib
#matplotlib.rc('text', usetex=True)
matplotlib.use('Agg')
#matplotlib.rcParams.update({'font.size': 20})
import matplotlib.p... |
993,193 | b3fe981518928ac866fa5c3c71fbb5bd9a09a78d | import logging
from flask_restplus import Api
log = logging.getLogger(__name__)
api = Api(
description="Description",
title="API",
doc="/documentation/",
validate=True,
)
|
993,194 | 944a976bbdcabb063f97a06fdfecee4fd9bc6e93 | from .entities.personas import personas
class modeloPersona():
@classmethod
def listar_personas(self,db):
try:
listapersonas=personas.query.all()
return listapersonas
except Exception as ex:
raise Exception(ex)
@classmethod
d... |
993,195 | b3c9b758ea0b683aa4762a1e8e30bfffb2074a00 |
"""
Find mirror tree of a binary tree
"""
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
def mirror(root):
if not root:
return
mirror(root.left)
mirror(root.right)
temp = root.left
root.left = root.right
root.right = temp
... |
993,196 | c7f1ae174534a8a7cc30a4345940d56cfca8d077 | # Generated by Django 3.1.2 on 2020-12-23 10:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('account', '0005_auto_20201223_1532'),
]
operations = [
migrations.RemoveField(
model_name='account',
name='USN',
),
... |
993,197 | a1732134e36c0bcd3fb9101fd97005c26cb00752 | import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
# This is needed since the notebook is stored in the object_detection f... |
993,198 | aa42760de681f549967010332b60f13dd5ee2073 | from common.logger import Logging
from page_obj.base import Page
from readConfig import ReadConfig
logger = Logging('safeEdit').getlog()
config = ReadConfig()
class safeEdit(Page):
def __init__(self,driver):
Page.__init__(self,driver)
self.config_element = {
"账号输入框": ["id", "login_user... |
993,199 | d2773b7dcb0374251d66a60a3175ecf0c88f873e | #python is a formally an interpreter language
#python will start by entering python in the cmdline
#python syntax primarlily uses white space for compiling
#GPA calculator
print('Welcome to the GPA calculator')
print('Please enter all your grades, one per line')
print('Enter a blank line to delegate them at the end... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.