index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
4,000 | 4d43e470144a6284d85902b495dc19dc150eb681 | # -*- coding: utf-8 -*-
import time
import errno
from gi.repository import GLib
from ..async import (FutureSourcePair, FutureCanceled, SucceededFuture,
BrokenPipeError, ConnectionError)
__all__ = ('GCore',)
#------------------------------------------------------------------------------#
# GLib Co... |
4,001 | 8b7fb0789d197e50d7bdde2791b6fac964782469 | from flask import Flask
from flask_mongoengine import MongoEngine
db = MongoEngine()
def create_app(**config_overrides):
app = Flask(__name__)
app.config.from_pyfile('settings.py')
app.config.update(config_overrides)
db.init_app(app)
from user.views import user_app
app.register_blueprint(user_app)
from wor... |
4,002 | e989f73011559080f96802dba4db30361d5626f9 | # the main program of this project
import log
import logging
import os
from ast_modifier import AstModifier
from analyzer import Analyzer
class Demo():
def __init__(self):
self.log = logging.getLogger(self.__class__.__name__)
def start(self, filename: str):
self.log.debug('analyse file: ' + fil... |
4,003 | e769e930ab8f0356116679bc38a09b83886eb8f6 | # -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
"""
The main service module
MIT License
Copyright (c) 2017-2020, Leo Moll
"""
# -- Imports ------------------------------------------------
from resources.lib.service import MediathekViewService
# -- Main Code ----------------------------------------------
if... |
4,004 | 86de5b4a72978e2c49e060eefc513e3ed61272ae | def longest_word(s, d):
lengths = [(entry, len(entry)) for entry in d]
sorted_d = sorted(lengths, key = lambda x: (-x[1], x[0]))
for word, length in sorted_d:
j = 0
for i in range(0, len(s)):
if j < len(word) and word[j] == s[i]:
j += 1
if j == len(wo... |
4,005 | ccb6973910dba5897f6a12be23c74a35e848313b | # Generated by Django 2.1 on 2018-12-05 00:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('PleniApp', '0006_auto_20181203_1144'),
]
operations = [
migrations.CreateModel(
name='Comment',
... |
4,006 | c33aedbd5aaa853131c297a9382b72c3c646a319 | import os
import base64
from binascii import hexlify
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes, hmac
from cryptography.hazmat.backends import default_backend
backend = default_backend()
# Llave falsa
key = key = b"vcOqXPg==lz3M0IH4s... |
4,007 | a61f351391ca1b18359323fd9e49f1efa4c7513c |
# website = urlopen("https://webservices.ulm.edu/forms/forms-list")
# data = bs(website, "lxml")
# forms = data.findAll("span", {"class": "file"})
# forms_list = []
# names = []
# for f in forms:
# forms_list.append(f.find("a")["href"])
# names.append(f.get_text())
# # print(forms_list)
# for f in forms_list:... |
4,008 | a847fc32af2602db3b5545c15186c0209eb8ae8d | # -*- coding: utf-8 -*-
__author__ = 'virtual'
statuses = {
None: {'name': 'None', },
-1: { 'name': 'unknown', },
0: { 'name': '',},
1: { 'name': 'Новый',},
2: { 'name': '',},
3: { 'name': 'Активный', },
4: { 'name': 'Приостановленный',},
5: { 'name': 'Заблокированный', },
6: { 'n... |
4,009 | 3741e44178375f351278cb17c2bf8f11c69e1262 | class StartStateImpl:
start_message = "Для продолжения мне необходим ваш корпоративный E-mail"\
"Адрес вида: <адрес>@edu.hse.ru (без кавычек)"
thank_you = "Спасибо за ваш адрес. Продолжаем."
def __init__(self):
pass
def enter_state(self, message, user):
user.send_message(StartS... |
4,010 | adec7efceb038c0ecb23c256c23c2ea212752d64 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#multi layer perceptron with back propogation
import numpy as np
import theano
import matplotlib.pyplot as plt
# In[2]:
inputs=[[0,0],
[1,0],
[0,1],
[1,1]]
outputs=[1,0,0,1]
# In[3]:
x=theano.tensor.matrix(name='x')
# In[4]:
#Hidden laye... |
4,011 | c4aa5869d5f916f13aa924c19dc9792337619b31 | from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
import random
def sim_data():
# Parameters
n_samples = random.randint(500, 5000)
n_features = random.randint(5, 25)
n_informative = random.randint(5, n_features)
noise = random.uniform(0.5, 2)
# ... |
4,012 | a9a60d4bee45a4012d004bacac7812160ed4241c | #!/usr/bin/env python
# coding: utf-8
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host = '192.168.10.28'
))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='... |
4,013 | c73bea686786a30f298500968cfd01e2d5125d75 | import copy
import six
from eclcli.common import command
from eclcli.common import utils
from eclcli.storage.storageclient import exceptions
class ListVolumeType(command.Lister):
def get_parser(self, prog_name):
parser = super(ListVolumeType, self).get_parser(prog_name)
parser.add_argument(
... |
4,014 | 20f0de097fdd8f2a435c06a73c6a90cc7ebc69ad | from django.contrib import admin
# Register your models here.
from blog.models import Post,Category,Profile
admin.site.register(Profile)
admin.site.register(Category)
admin.site.register(Post) |
4,015 | 8745855d86dcdabe55f8d1622b66b3613dbfe3e1 | arr = []
for i in range(5):
arr.append(int(input()))
print(min(arr[0],arr[1],arr[2])+min(arr[3],arr[4])-50) |
4,016 | 24fa41f916b54345e4647354f972bd22e130decf | #YET TO COMMENT.
import numpy as np
from functools import reduce
class ProbabilityNetwork:
def __init__(self,n,edges,probs):
self.nodes=list(range(n))
self.edges=edges
self.probs=probs
def parents(self, node):
return [a for a,b in edges if b==node]
def ancestralOrder(self... |
4,017 | 873a53983e3aeb66bd290450fb9c15a552bd163c | #!/usr/bin/env python
import os
import sys
import click
import logging
from signal import signal, SIGPIPE, SIG_DFL
from ..helpers.file_helpers import return_filehandle
from ..helpers.sequence_helpers import get_seqio_fastq_record
signal(SIGPIPE, SIG_DFL)
def subset_fastq(fastq, subset):
'''Subset FASTQ file. P... |
4,018 | 9767014992981001bd2e8dece67525650c05a2a8 | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import sublime
import sublime_plugin
"""
Copy and Paste selinium module and urllib3 module of Python in
"sublime-text-3/Lib/Python3.3" folder of sublime-text3
"""
def process(string):
# Get active file name
filename = subl... |
4,019 | 9620479e9ac27c1c7833c9a31b9cb18408b8d361 | import time
inputStr = """crruafyzloguvxwctqmphenbkd
srcjafyzlcguvrwctqmphenbkd
srijafyzlogbpxwctgmphenbkd
zrijafyzloguvxrctqmphendkd
srijabyzloguvowcqqmphenbkd
srijafyzsoguvxwctbmpienbkd
srirtfyzlognvxwctqmphenbkd
srijafyzloguvxwctgmphenbmq
senjafyzloguvxectqmphenbkd
srijafyeloguvxwwtqmphembkd
srijafyzlogurxtctqmpken... |
4,020 | 1de46ee2818b4cb2ae68ef5870581c341f8d9b04 | # coding=utf-8
from datetime import datetime, timedelta
from flask import current_app as app
from flask_script import Command
from main import db
from models.payment import Payment
from models.product import ProductGroup, Product, PriceTier, Price, ProductView, ProductViewProduct
from models.purchase import Purchase
... |
4,021 | 07b05093b630fc0167532884ec69a00420ed70b4 | # -*- coding: utf-8 -*-
###########################
# CSCI 573 Data Mining - Eclat and Linear Kernel SVM
# Author: Chu-An Tsai
# 12/14/2019
###########################
import fim
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.svm import SVC
from sklearn.m... |
4,022 | 17b3fb44d9e7a09fe3b807b47bdc0248b6960634 | from datapackage_pipelines.wrapper import ingest, spew
params, datapackage, res_iter = ingest()
columns = params['columns']
for resource in datapackage['resources']:
fields = resource.get('schema', {}).get('fields')
if fields is not None:
fields = [
field for field in fields
i... |
4,023 | c7ca8235864ce5de188c4aa2feb9ad82d4fa9b0f | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, Float
from sqlalchemy.orm import relationship, backref
ORMBase = declarative_base()
def create_all(engine):
ORMBase.metadata.create_all(engine)
|
4,024 | a1df804325a074ed980ec864c72fe231e2968997 | """ GetState
Usage:
get_state.py <pem-file> <ip-file> [options]
Options:
-h, --help print help message and exit
--output DIR set the output directory [default: logs]
"""
from docopt import docopt
import paramiko
import os
def get_logs(ip_addr, pem_file, log_dir):
pem = paramiko.RSAKey... |
4,025 | da2e388c64bbf65bcef7d09d7596c2869f51524a | import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
import numpy as np
x = 2
y = 3
add_op = tf.add(x, y)
mul_op = tf.multiply(x, y)
output_1 = tf.multiply(x, add_op)
output_2 = tf.pow(add_op, mul_op)
with tf.Session() as sess:
output_1, output_2 = sess.run([output_1, output_2])
prin... |
4,026 | d853964d424e628d6331b27123ad045f8d945dc0 | # coding: utf-8
num = int(input())
str = input().split()
table = [int(i) for i in str]
list.sort(table)
print(table[num-1] - table[0]) |
4,027 | 2dcb02ea2f36dd31eda13c1d666201f861c117e7 | from django.db import models
from django.utils import timezone
# Create your models here.
class URL(models.Model):
label = models.CharField(null=True, blank=True, max_length=30)
address = models.URLField()
slug = models.SlugField(unique=True, max_length=8)
created = models.DateTimeField(auto_now_add=T... |
4,028 | 35cd1c45294b826784eab9885ec5b0132624c957 | from kivy.uix.progressbar import ProgressBar
from kivy.animation import Animation
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.graphics import Color, Rectangle
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy... |
4,029 | 9c3ca2fa43c6a34d7fe06517812a6d0bf5d6dbe1 | #!/usr/bin/python
"""
Create a 1024-host network, and run the CLI on it.
If this fails because of kernel limits, you may have
to adjust them, e.g. by adding entries to /etc/sysctl.conf
and running sysctl -p. Check util/sysctl_addon.
This is a copy of tree1024.py that is using the Containernet
constructor. Containernet... |
4,030 | 883a50cf380b08c479c30edad3a2b61a6f3075cc | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import unittest
from selenium import webdriver
from appium import webdriver
from time import sleep
import os
from PublicResour import Desired_Capabilities
"""
登录状态下检查“我的”界面的所有的功能模块
大部分执行用例时在“我的”界面
"""
#Return ads path relative to this file not cwd
PATH = lambda p: ... |
4,031 | 466ffbd1f25423e4209fa7331d8b824b2dd3cd70 | # Code
import json
import os
import pandas
from pathlib import Path
from asyncio import sleep
# Import default websocket conection instance
from channels.generic.websocket import AsyncJsonWebsocketConsumer
# Global variable ----------
timeout = 0.5
# Get curent working directory
cwd = os.getcwd() # Get... |
4,032 | db49313d2bc8b9f0be0dfd48c6065ea0ab3294cb | """empty message
Revision ID: 3e4ee9eaaeaa
Revises: 6d58871d74a0
Create Date: 2016-07-25 15:30:38.008238
"""
# revision identifiers, used by Alembic.
revision = '3e4ee9eaaeaa'
down_revision = '6d58871d74a0'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
4,033 | ba486b64b1da3dc1775bee0980d5236516e130d4 | import time
import math
from random import randrange
import multilineMAX7219 as LEDMatrix
from multilineMAX7219_fonts import CP437_FONT, SINCLAIRS_FONT, LCD_FONT, TINY_FONT
from multilineMAX7219 import DIR_L, DIR_R, DIR_U, DIR_D
from multilineMAX7219 import DIR_LU, DIR_RU, DIR_LD, DIR_RD
from multilineMAX7219 import D... |
4,034 | 4ecf9c03750a31ecd113a7548df4e2a700e775e0 | from django.utils.html import strip_tags
from django.core.mail import send_mail
from django.urls import reverse
from django.http import HttpResponseRedirect
def Email(doctorFullName,password,otp,email,id):
print("\n== UTILS ===")
html_message='''
<html>
<body>
<p>Welcome %s and pass is %s... |
4,035 | 73d02615863826d77d65fbf0314dc71acb97ef28 | '''a,b = input().split()
a, b = [int(a),int(b)]
List = set()
ArrayA = list(map(int, input().split()))
temp = 1
ArrayB = list(map(int, input().split()))
for i in range(max(ArrayA), min(ArrayB)+1):
for j in ArrayA:
if i%j is 1:
temp += 1
if temp is len(ArrayA):
List.add(i)
temp=1
... |
4,036 | 2d9d66ea8a95285744b797570bfbeaa17fdc922a | numbers = [3, 7, 5]
maxNumber = 0
for number in numbers:
if maxNumber < number:
maxNumber = number
print maxNumber |
4,037 | f4715a1f59ceba85d95223ef59003410e35bfb7f | #!/usr/bin/python
import os
# http://stackoverflow.com/questions/4500564/directory-listing-based-on-time
def sorted_ls(path):
mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
return list(sorted(os.listdir(path), key=mtime))
def main():
print "Content-type: text/html\n\n"
print "<html><head><t... |
4,038 | 925e1a1a99b70a8d56289b72fa0e16997e12d854 | from bs4 import BeautifulSoup
import requests
import pandas as pd
import json
cmc = requests.get('https://coinmarketcap.com/')
soup = BeautifulSoup(cmc.content, 'html.parser')
data = soup.find('script', id="__NEXT_DATA__", type="application/json")
coins = {}
slugs = {}
coin_data = json.loads(data.contents[0])
listin... |
4,039 | f8c30f8ccd1b901fd750a2c9e14cab78e1d12a14 | from nose.tools import assert_equal
def rec_coin(target, coins):
'''
INPUT: Target change amount and list of coin values
OUTPUT: Minimum coins needed to make change
Note, this solution is not optimized.
'''
# Default to target value
min_coins = target
# Check to see if we have a sin... |
4,040 | acc39044fa1ae444dd4a737ea37a0baa60a2c7bd | from Stack import Stack
from Regex import Regex
from Symbol import Symbol
class Postfix:
def __init__(self, regex):
self.__regex = regex.expression
self.__modr = Postfix.modRegex(self.__regex)
self.__pila = Stack()
self.__postfix = self.convertInfixToPostfix()
def getRegex(... |
4,041 | 6375ac80b081b7eafbc5c3fc7e84c4eff2604848 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import pandas as pd
df = pd.read_csv('games_data.csv')
names = df['game']
driver = webdriver.Chrome('D:/chromedriver.exe')
driver.get('https://www.google.ca/imghp?hl=en&tab=ri&authuser=0&ogbl')
k = 0
for name in names:
bo... |
4,042 | b52429f936013ac60659950492b67078fabf3a13 | """
======================
@author:小谢学测试
@time:2021/9/8:8:34
@email:xie7791@qq.com
======================
"""
import pytest
# @pytest.fixture()
# def login():
# print("登录方法")
# def pytest_conftest(config):
# marker_list = ["search","login"]
# for markers in marker_list:
# config.addinivalue_line("m... |
4,043 | 362c4e572f0fe61b77e54ab5608d4cd052291da4 | import io
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/')
def index():
buf = io.BytesIO()
buf.write('hello world')
buf.seek(0)
return send_file(buf,
attachment_filename="testing.txt",
as_attachment=True)
|
4,044 | b8d45a0028cb4e393ddca9dd6d246289328d1791 | from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as keras
unet_feature_n = 512
unet_feature_nstep_size = 1e-4
unet_input_image_size = 128
def unet(pretrained_weights=None, input_size=(unet_... |
4,045 | c2f82cf73d095979d1da346b7dd7779bcc675805 | # 1 use the operators to solve for the following equation:
# (a)
number = ((30*39) + 300) **10
print(number)
# find the value of C. X + Y = C Given:
x = 0.0050
y = 0.1000
c = x + y
print(c)
"""
what is the result of the following:
(a) take the sentence:
the study or use of the systems
(especially computers and... |
4,046 | 0d98472d1c04bfc52378aa6401a47d96582696a2 | from sklearn import datasets, svm
import matplotlib.pyplot as plt
digits = datasets.load_digits()
X, y = digits.data[:-1], digits.target[:-1]
clf = svm.SVC(gamma=0.1, C=100)
clf.fit(X, y)
prediction = clf.predict(digits.data[-1:])
actual = digits.target[-1:]
print("prediction = " + str(prediction) + ", actual = " + ... |
4,047 | 9dccc19abb6dac9e9606dc1fd83a227b4da9bf1f | # -*- coding: utf-8 -*-
"""
Neverland2 Colorscheme
~~~~~~~~~~~~~~~~~~~~~~
Converted by Vim Colorscheme Converter
"""
from pygments.style import Style
from pygments.token import Token, Keyword, Comment, Number, Generic, Operator, Name, String
class Neverland2Style(Style):
background_color = '#121212'
... |
4,048 | 099396a75060ad0388f5a852c4c3cb148febd8a3 | from network import WLAN
import machine
import pycom
import time
import request
def wifiConnect():
wlan = WLAN(mode=WLAN.STA)
pycom.heartbeat(False)
wlan.connect(ssid="telenet-4D87F74", auth=(WLAN.WPA2, "x2UcakjTsryz"))
while not wlan.isconnected():
time.sleep(1)
print("... |
4,049 | f77df47fdb72ba50331b8b5d65984efaec474057 | # -*- coding: utf-8 -*-
import threading
import time
def work():
i = 0
while i < 10:
print 'I am working..'
time.sleep(0.5)
i += 1
t = threading.Thread(target=work)
# Daemon 설정
#t.setDaemon(True)
t.daemon = True # 혹인 이렇게도 가능
t.start()
print 'main thread finished'
|
4,050 | c9b76fed088b85cf68e96778016d8974fea84933 | #!/usr/bin/python
import os, sys
# Assuming /tmp/foo.txt exists and has read/write permissions.
ret = os.access("/tmp/foo.txt", os.F_OK)
print "F_OK - return value %s"% ret
ret = os.access("/tmp/foo.txt", os.R_OK)
print "R_OK - return value %s"% ret
ret = os.access("/tmp/foo.txt", os.W_OK)
print "W_OK -... |
4,051 | 1cc9a7bbe1bda06ce76fa8ec1cdc17c7b2fde73b |
a = 1
b = a
print(a)
print(b)
a = 2
print(a)
print(b)
# 全部大写字符代表常量
USER_NAME = "常量"
print(USER_NAME)
print(USER_NAME) |
4,052 | 7f2489aa440441568af153b231420aa2736716ca | print ("Welcome to the Guessing Game 2.0\n")
print ("1 = Easy\t(1 - 10)")
print ("2 = Medium\t(1 - 50)")
print ("3 = Hard\t(1 - 100)")
# Player: Input user's choice
# while: Check if user enters 1 or 2 or 3
# CPU: Generate a random number
# Player: Input user's number
# Variable: Add a variable 'attempt... |
4,053 | c40bb410ad68808c2e0cc636820ec6a2ec2739b8 | # Importing the random library for random choice.
import random
getnum = int(input("Pick a number greater than 7: "))
# Error checking.
if (getnum < 7):
print("Error 205: Too little characters entered")
print("Run again using python passwordgenerator.py, or click the run button on your IDE.")
exit()
# A li... |
4,054 | 681788ffe7672458e8d334316aa87936746352b1 | # CSE 415 Winter 2019
# Assignment 1
# Jichun Li 1531264
# Part A
# 1
def five_x_cubed_plus_1(x):
return 5 * (x ** 3) + 1
#2
def pair_off(ary):
result = []
for i in range(0, int(len(ary) / 2 * 2), 2):
result.append([ary[i], ary[i + 1]])
if (int (len(ary) % 2) == 1):
result.append([ar... |
4,055 | 18e76df1693d4fc27620a0cf491c33197caa5d15 | '''
Created on Dec 2, 2013
A reference entity implementation for Power devices
that can be controlled via RF communication.
@author: rycus
'''
from entities import Entity, EntityType
from entities import STATE_UNKNOWN, STATE_OFF, STATE_ON
from entities import COMMAND_ON, COMMAND_OFF
class GenericPower(Entity):
... |
4,056 | e60d57e8884cba8ce50a571e3bd0affcd4dcaf68 | import requests
import re
from bs4 import BeautifulSoup
r = requests.get("https://terraria.fandom.com/wiki/Banners_(enemy)")
soup = BeautifulSoup(r.text, 'html.parser')
list_of_banners = soup.find_all('span', {'id': re.compile(r'_Banner')})
x_count = 1
y_count = 1
for banner_span in list_of_banners:
print(f"{banner... |
4,057 | f3a34d1c37165490c77ccd21f428718c8c90f866 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import random
import sys
def sequential_search(my_list, search_elt):
found = False
start_time = time.time()
for elt in my_list:
if search_elt == elt:
found = True
break
return (time.time() - start_time), found
def ordered_sequential_... |
4,058 | 800edfc61635564abf8297c4f33c59d48cc99960 | import heapq as heap
import networkx as nx
import copy
import random
def remove_jumps(moves):
res = []
for move in moves:
if move[2] > 1:
move[3].reverse()
res.extend(make_moves_from_path(move[3]))
else:
res.append(move)
return res
def make_moves_from... |
4,059 | a3cfd507e30cf232f351fbc66d347aaca99a0447 | from pyramid.view import view_config, view_defaults
from ecoreleve_server.core.base_view import CRUDCommonView
from .individual_resource import IndividualResource, IndividualsResource, IndividualLocationsResource
@view_defaults(context=IndividualResource)
class IndividualView(CRUDCommonView):
@view_config(name=... |
4,060 | 37d079ca6a22036e2660507f37442617d4842c4e | import arcade
import os
SPRITE_SCALING = 0.5
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Raymond Game"
MOVEMENT_SPEED = 50
class Ball:
def __init__(self, position_x, position_y, change_x, change_y, radius):
# Take the parameters of the init function above, and create instance variables ou... |
4,061 | 3a678f9b5274f008a510a23b2358fe2a506c3221 | import logging
import argparse
import getpass
import errno
import re
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import dns.resolver
class Mail(object):
def __init__(self, recipient=None, sender=None, subject=None, body=None):
self.recipient = recipi... |
4,062 | ae0547aa1af2d4dd73bb60154574e64e74107a58 | import numpy as np
import cv2
def optical_flow_from_video():
cap = cv2.VideoCapture("/home/ubuntu/data1.5TB/异常dataset/Avenue_dataset/training_videos/01.avi")
# 设置 ShiTomasi 角点检测的参数
feature_params = dict(maxCorners=100, qualityLevel=0.3, minDistance=7, blockSize=7)
# 设置 lucas kanade 光流场的参数
# maxLe... |
4,063 | f3d9e783491916e684cda659afa73ce5a6a5894a | import numpy as np
import os
import sys
file_path = sys.argv[1]
triplets = np.loadtxt(os.path.join(file_path, "kaggle_visible_evaluation_triplets.txt"),
delimiter="\t", dtype="str")
enum_users = np.ndenumerate(np.unique(triplets[:, 0]))
print(enum_users)
triplets[triplets[:, 0] == user... |
4,064 | 612b1851ba5a07a277982ed5be334392182c66ef | import re # regex module
from ftplib import FTP, error_perm
from itertools import groupby
from typing import List, Tuple, Dict
import requests # HTTP requests module
from util import retry_multi, GLOBAL_TIMEOUT # from util.py
class ReleaseFile:
"""! Class representing a Released file on Nebula
`name`: str... |
4,065 | ff20b65f35614415ad786602c0fc2cabd08124fb | from typing import Sequence
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
def plot3D(X, Y, Z, proporcao=1, espelharZ = False):
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_xlabel('X ')
ax.set_ylabel('Y ')
ax.set_zlabel('Z ')
np.floor
col... |
4,066 | f89800e0d8d4026c167381f275ca86c2cf7f011e | def digitSum(x):
if x < 10: return x
return x % 10 + digitSum(x // 10)
def solve(S,n):
Discriminante = S*S + 4*n
r = int(Discriminante**0.5)
if r * r == Discriminante:
if r % 2 == S % 2:
return (r - S) // 2
else:
return -1
else:
return -1
n = int... |
4,067 | 255130082ee5f8428f1700b47dee717465fed72f | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 18 18:21:37 2021
@author: benoitdeschrynmakers
"""
import requests
url = 'http://127.0.0.1:8888/productionplan'
if __name__ == "__main__":
filename = "example_payloads/payload1.json"
data = open(filename, 'rb').read()
headers = {'Acc... |
4,068 | dbec74ecf488ca98f3f441e252f79bc2bc0959c1 | from django.db import models
# Create your models here.
class UserInfo(models.Model):
uname = models.CharField('用户名', max_length=50, null=False)
upassword = models.CharField('密码', max_length=200, null=False)
email = models.CharField('邮箱', max_length=50, null=True)
phone = models.CharField('手机号', max_le... |
4,069 | f765f54a89a98a5f61c70a37379860f170444c0a | G = 1000000000
M = 1000000
K = 1000 |
4,070 | 6c94b487eaa179a70ea6528b0214d04d5148574f | # File Name: create_data.py
from sqlalchemy.orm import sessionmaker
from faker import Faker
from db_orm import Base, engine, User, Course
from sqlalchemy import MedaData
session = sessionmaker(engine)()
fake = Faker('zh-cn')
# 创建表
users_table = Table('users', metadata,
Column('id', Integer, primary_key = True),
... |
4,071 | 01e60123ad87d9ff49812fe3a6f5d55bc85921c5 | """
-*- coding:utf-8 -*-
@ Time : 14:05
@ Name : handle_ini_file.py
@ Author : xiaoyin_ing
@ Email : 2455899418@qq.com
@ Software : PyCharm
...
"""
from configparser import ConfigParser
from Common.handle_path import conf_dir
import os
class HandleConfig(ConfigParser):
def __init__(self, ini_... |
4,072 | b2f9a133581b5144b73a47f50a3b355d1112f7ea | import numpy as np
import time
# Create key based on timestamp
KEY = time.time()
np.random.seed(int(KEY))
# Read in message
with open('Message.txt', 'r') as f:
Message = f.read()
f.close()
# Generate vector of random integers
Encoder = np.random.random_integers(300, size=len(Message))
# Map message to encoded arr... |
4,073 | b2bb7393bf7955f5de30c59364b495b8f888e178 | import numpy as np
class Constants():
DNN_DEFAULT_ACTIVATION = 'relu'
DNN_DEFAULT_KERNEL_REGULARIZATION = [0, 5e-5]
DNN_DEFAULT_BIAS_REGULARIZATION = [0, 5e-5]
DNN_DEFAULT_LOSS = 'mean_squared_error'
DNN_DEFAULT_VALIDATION_SPLIT = 0.2
DNN_DEFAULT_EPOCHS = 100
DNN_DEFAULT_CHECKPOINT_PERIOD =... |
4,074 | f01f97f8998134f5e4b11232d1c5d341349c3c79 | import numpy as np
import matplotlib.pyplot as plt
# image data
a = np.array([0.1,0.2,0.3,
0.4,0.5,0.6,
0.7,0.8,0.9]).reshape(3,3)
plt.imshow(a,interpolation='nearest',cmap='bone',origin='upper')
plt.colorbar()
plt.xticks(())
plt.yticks(())
plt.show()
|
4,075 | 14a39b9aa56777c8198794fe2f51c9a068500743 | #!/bin/python3
import socket
HOST = '127.0.0.1'
PORT= 4444
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT)) |
4,076 | cf7556034020d88ddb6b71b9f908c905e2f03cdb | #17219
tot, inp = map(int, input().split())
ID_dict = {}
for _ in range(tot):
id, pw = map(str, input().split())
ID_dict[id] = pw
for _ in range(inp):
print(ID_dict[input()]) |
4,077 | ec6067cc86b6ac702123d13911cc4ab97be6a857 | from oil_prices import *
with_without = 'without training'
show_plot = 'yes'
print('START')
# Defining the past and future sequences for the LSTM training
n_past = 8
n_future = 1
target_date = '2018-11-16'
past = ['t']+['t-'+str(i) for i in range(1,n_past)]
future = ['t+'+str(i) for i in range(1,n_future+1)]
# Imp... |
4,078 | d3c36ad36c50cd97f2101bc8df99d1961b0ad7ea | #!/usr/bin/env python
# coding: utf-8
# In[2]:
print(" sum of n numbers with help of for loop. ")
n = 10
sum = 0
for num in range(0, n+1, 1):
sum = sum+num
print("Output: SUM of first ", n, "numbers is: ", sum )
# In[3]:
print(" sum of n numbers with help of while loop. ")
num = int(input("Enter the value of... |
4,079 | d10468d2d0aefa19a7d225bfffad03ec6cb6e082 | class Solution:
def getDescentPeriods(self, prices: List[int]) -> int:
ans = 1 # prices[0]
dp = 1
for i in range(1, len(prices)):
if prices[i] == prices[i - 1] - 1:
dp += 1
else:
dp = 1
ans += dp
return ans
|
4,080 | ab5412a3d22bd53a592c93bad4870b06fd9f0720 | radius = int(input("enter the value for the radius of the cycle: "))
circumference = 2 * 3.14159 * radius
diameter = 2 * radius
area = 3.14159 * radius ** 2
print('circumference is ', circumference)
print('diameter is: ', diameter)
print('area is ', area)
|
4,081 | fa07553477e3bb2ecbeb87bd1383a2194282579c | #coding=UTF-8
import random
import random
list=[]
s=0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i!=j and j<>k:
list.append(str(i)+str(j)+str(k))
s=s+1
print len(list)
print s
if len(list)==s:
print "是相等的!"
else:
print "不相等!"
print l... |
4,082 | 5d4ef436c4ee5c31496977a5ae9b55db9ff34e79 |
class Donkey(object):
def manzou(self):
print('走路慢……')
def jiao(self):
print('驴在欢叫%……')
class Horse(object):
def naili(self):
print('马力足,持久强……')
def jiao(self):
print('马在嘶鸣')
class Mule(Donkey,Horse):
pass
def jiao(self):
print('骡子在唱歌')
骡子一号 = Mule()
骡... |
4,083 | c58f40d369388b94778e8583176f1ba8b81d0c5e | #!/usr/bin/env python
from program_class import Program
import tmdata
import os
def main():
""""""
args1 = {"progname" : "whoami",
"command" : "/usr/bin/whoami",
"procnum" : 1,
"autolaunch" : True,
"starttime" : 5,
"restart" : "never",
"retries" : 2,
"stopsig" : "SSIG",
"stoptime" : 10,
"e... |
4,084 | 05021c3b39a0df07ca3d7d1c3ff9d47be6723131 | import numpy
import cv2
from keras.models import model_from_json
from keras.layers import Dense
from keras.utils import np_utils
import os
from keras.optimizers import SGD, Adam
numpy.random.seed(42)
file_json = open('model.json', "r")
model_json = file_json.read()
file_json.close()
model = model_from_json(model_json)... |
4,085 | 3c738a07d71338ab838e4f1d683e631252d50a30 | __author__ = 'ldd'
# -*- coding: utf-8 -*-
from view.api_doc import handler_define, api_define, Param
from view.base import BaseHandler,CachedPlusHandler
@handler_define
class HelloWorld(BaseHandler):
@api_define("HelloWorld", r'/', [
], description="HelloWorld")
def get(self):
self.write({'st... |
4,086 | dc2cbbaca3c35f76ac09c93a2e8ad13eb0bdfce6 |
from xai.brain.wordbase.verbs._essay import _ESSAY
#calss header
class _ESSAYED(_ESSAY, ):
def __init__(self,):
_ESSAY.__init__(self)
self.name = "ESSAYED"
self.specie = 'verbs'
self.basic = "essay"
self.jsondata = {}
|
4,087 | 6c0ca72d7f5d2373a50cd344991ad9f9e3046e8d | #tkinter:Label 、Button 、标签、按钮
#详见:
#1、os:https://blog.csdn.net/xxlovesht/article/details/80913193
#2、shutil:https://www.jb51.net/article/157891.htm
#3、tkinter:https://blog.csdn.net/mingshao104/article/details/79591965
# https://blog.csdn.net/sinat_41104353/article/details/79313424
# https:/... |
4,088 | 7997efb00f24ecc5c4fbf3ca049eca6b5b178d53 | import pytest
from freezegun import freeze_time
from datetime import datetime
from khayyam import JalaliDatetime, TehranTimezone
from dilami_calendar import DilamiDatetime, dilami_to_jalali
def test_dilami_date():
gdate = datetime(2018, 2, 1)
ddate = DilamiDatetime(gdate, tzinfo=TehranTimezone)
assert ... |
4,089 | acf787885834961a71fb2655b9d8a1eb026942c7 | #https://www.hackerrank.com/challenges/caesar-cipher-1/problem
n=int(input())
stringy=input()
k=int(input())
s=""
for i in stringy:
if ord(i)>=65 and ord(i)<=90:
temp=(ord(i)+k-65)%26
s+=chr(temp+65)
elif ord(i)>=97 and ord(i)<=122:
temp=(ord(i)+k-97)%26
s+=chr(temp+97)
else... |
4,090 | 9cf32e127664cb4c3290e665e35245acc936e064 | # created by ahmad on 17-07-2019
# last updated on 21-07-2019
#recommended font size of console in pydroid is 12
from decimal import Decimal
def fromTen():
global fin
fin = num
nnum = num
base = base2
if count == 1:
nnum = sum(milst) + sum(mdlst)
Ipart = int(nnum)
Dpart = Dec... |
4,091 | 5d8d47d77fba9027d7c5ec4e672fc0c597b76eae | # models.py
from sentiment_data import *
from utils import *
import nltk
from nltk.corpus import stopwords
import numpy as np
from scipy.sparse import csr_matrix
class FeatureExtractor(object):
"""
Feature extraction base type. Takes a sentence and returns an indexed list of features.
"""
def get_inde... |
4,092 | 0b2a036b806cca6e7f58008040b3a261a8bc844d | PROJECT_ID = "aaet-geoscience-dev"
# The tmp folder is for lasio I/O purposes
DATA_PATH = "/home/airflow/gcs/data/tmp"
# Credential JSON key for accessing other projects
# CREDENTIALS_JSON = "gs://aaet_zexuan/flow/keys/composer_las_merge.json"
CREDENTIALS_JSON = "keys/composer_las_merge.json"
# Bucket name fo... |
4,093 | 7ff7da216bdda5c30bf7c973c82886035b31247c | #!/usr/bin/python
class Bob(object):
def __init__(self):
self.question_response = "Sure."
self.yell_response = "Woah, chill out!"
self.silent_response = "Fine. Be that way!"
self.whatever = "Whatever."
def hey(self, question):
if not(question) or question.strip()=='':
... |
4,094 | 443ed24ab396e83dbf12558207376258124bca8b | # Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... |
4,095 | 773fc4660def134410eca92886b2629be6977f74 | #
# Util for WebDriver
#
import sys
from string import Formatter
from functools import wraps
from numbers import Integral
from .locator import Locator
from .keys import Keys
PY3 = sys.version_info[0] == 3
class MemorizeFormatter(Formatter):
"""Customize the Formatter to record used and unused kwargs."""
... |
4,096 | cb0df06ee474576b3024678fa0f63ce400d773ea | from flask.ext.wtf import Form
from wtforms import TextField
from wtforms.validators import Required
class VerifyHandphoneForm(Form):
handphone_hash = TextField('Enter verification code here', validators=[Required()]) |
4,097 | aec45936bb07277360ea1a66b062edc4c282b45a | import server_pb2
import atexit
from grpc.beta import implementations
from random import randint
from grpc._adapter._types import ConnectivityState
global _pool
_pool = dict()
class ChannelPool(object):
def __init__(self, host, port, pool_size):
self.host = host
self.port = port
self.p... |
4,098 | 97eb599ae8bf726d827d6f8313b7cf2838f9c125 | import math
from chainer import cuda
from chainer import function
from chainer.functions import Sigmoid
from chainer.utils import type_check
import numpy
def _as_mat(x):
if x.ndim == 2:
return x
return x.reshape(len(x), -1)
class Autoencoder(function.Function):
def __init__(self, in_size, hidde... |
4,099 | 41f2a5ba0d7a726389936c1ff66a5724209ee99c | import torch
import torch.optim as optim
import torch.nn as nn
import torch.utils.data as data
from dataset import InsuranceAnswerDataset, DataEmbedding
from model import Matcher
from tools import Trainer, Evaluator
from tools import save_checkpoint, load_checkpoint, get_memory_use
def main():
batch_size = 64
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.