index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
1,800
ea2183530667437e086bc89f137e464dec6f363a
from django.db import models class Kit(models.Model): name = models.CharField(max_length=100, null=True) main_image_url = models.URLField(max_length=1000) price = models.DecimalField(max_digits=10, decimal_places=2, default=0) description = models.CharField(max_length=1000, null=T...
1,801
e4e2e8ca65d109805b267f148e8d255d81d4ee83
from django.shortcuts import render, redirect from django.contrib.auth import authenticate, logout, login from django.contrib import messages from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views import View class login_view(View): template...
1,802
2ad326f739b42b9c7c252078b8c28e90da17b95d
import multiprocessing name = "flask_gunicorn" workers = multiprocessing.cpu_count() * 2 + 1 loglevel = "debug" bind = f"0.0.0.0:18080"
1,803
01900c1d14a04ee43553c8602a07e0c6ecfabded
# -*- coding: utf-8 -*- from django.shortcuts import get_object_or_404 from rest_framework import serializers from tandlr.core.api.serializers import ModelSerializer from tandlr.users.models import DeviceUser, User, UserSettings from tandlr.utils.refresh_token import create_token class LoginSerializer(serializers.S...
1,804
3b381668dbb9b4e5a2e323dc4d6b5e3951736882
from collections import namedtuple import argparse import pdb import traceback import sys import os from qca_hex_analyzer import WmiCtrlAnalyzer, HtcCtrlAnalyzer, HttAnalyzer, AllAnalyzer import hexfilter description = \ "Tool used to analyze hexdumps produced by a qca wireless kernel " \ "driver (such as ath...
1,805
bebe098c5abb579eb155a1dc325347d100ddfa8f
def coroutine(func): def start_coroutine(*args, **kwargs): cr = func(*args, **kwargs) next(cr) #cr.send(None) return cr return start_coroutine @coroutine def grep(pattern): print('start grep') try: while True: line = yield if pattern in line: print(line) except GeneratorExit: print('stop grep'...
1,806
af903feda57e4ace0c7f909abbeb86bb9a7e4d8c
from data.dataframe_sequence_multi import DataFrameSequenceMulti from metrics import Metrics from models.models_ts_multi import lstm_model_multi import threading import sys from keras import optimizers from data.data_helper import plot_history epochs = 100 start = 6 end = 18 res = [] sets = [] min_vals = [] min_loss ...
1,807
43179b8b096836758271a791b4aacb7bbe398ea9
import sys from Decks.Virtual_World.vw_sets import * from tools import * hand_3playable_hts = ["Nibiru, the Primal Being", "Effect Veiler", "Fantastical Dragon Phantazmay", "Dragon Buster Destruction Sword", "Dragon Buster Destruction Sword"] hand_2playable_hts = ["Nibiru, the Primal Being", "Nibiru, the Primal Being"...
1,808
c599a75788e3548c52ebb3b29e7a2398ff1b28a2
from sklearn.metrics import roc_auc_score, matthews_corrcoef, f1_score, confusion_matrix import numpy as np from scipy.stats import rankdata def iou_score(target, prediction): intersection = np.logical_and(target, prediction) union = np.logical_or(target, prediction) iou_score = np.sum(intersection) / (np...
1,809
1db16ae1fc6546575150187432265ac1cf834ec2
import pandas as pd import numpy as np import datetime as dt def sum_unique(x): return np.unique(x).shape[0] def analyze_count(data): """real time, vk, itemid, action""" dsct_vk = pd.unique(data['vk']) dsct_itemid = pd.unique(data['itemid']) print 'number of user:', dsct_vk.shape print ...
1,810
5749f30d1a1efd5404654d755bca4515adcf4bca
import json from django.db import models from django.conf import settings from django.core.serializers import serialize # Create your models here. def upload_updated_image(instance,filename): return '/MyApi/{user}/{filename}'.format(user=instance.user,filename=filename) class UpdateQueryset(models.QuerySet): ...
1,811
3a09cbd71d23b1320af9b8ddcfc65b223e487b21
import random import csv # 提取随机问,同类组成正例,异类组成负例,正:负=1:3 with open('final_regroup.csv', 'w', newline='') as train: writer = csv.writer(train) with open('final_syn_train.csv', 'r') as zhidao: reader = csv.reader(zhidao) cluster = [] cur = [] stand = '' # 将同一标准问...
1,812
707855a4e07b68d9ae97c2e1dc8bfd52f11c314c
import nltk import spacy import textacy from keras.layers import Embedding, Bidirectional, Dense, Dropout, BatchNormalization from keras_preprocessing.sequence import pad_sequences from keras_preprocessing.text import Tokenizer from nltk import word_tokenize, re from rasa import model import pandas as pd from spacy imp...
1,813
ab5400f4b44a53cb5cc2f6394bcdb8f55fd218f0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
1,814
2872c86294037b4585158e7ff6db414ba7ab90cc
from django.db import models # Create your models here. class AlertMailModel(models.Model): receipient_mail = models.EmailField() host_mail = models.EmailField() host_smtpaddress = models.CharField(max_length=25) mail_host_password = models.CharField(max_length=200) use_tls=models.BooleanField(defa...
1,815
07ed8c12e8e5c568c897b6b632c48831267eba51
t_dim_2 = [[1, 2], [3, 4]] def z(i, j, dim): t = dim ** 2 if dim == 2: return t_dim_2[i-1][j-1] d = dim//2 if i <= d: # I or II if j <= d: return z(i, j, d) #I else: j -= d return t//4 + z(i, j, d) # II else: # III or IV if j <=d...
1,816
d6cfea95c76021bdbfbb4471878c653564c9accd
import urllib.request from bs4 import BeautifulSoup def getTitlesFromAll(amount, rating='all'): output = '' for i in range(1, amount+1): try: if rating == 'all': html = urllib.request.urlopen('https://habr.com/all/page'+ str(i) +'/').read() else: ...
1,817
5f13866bd5c6d20e8ddc112fb1d1335e3fd46c3e
import requests import json import base64 import re def main(targetsrting): email="" #email key="" #key #targetsrting='ip="202.107.117.5/24"' #搜索关键字 target=base64.b64encode(targetsrting.encode('utf-8')).decode("utf-8") url="https://fofa.so/api/v1/search/all?email={}&key={}&qbase64={}&fields=hos...
1,818
c1bb2052b3f623c6787ba080dff2dc81f4d6f55e
import pandas as pd import numpy as np import json from pprint import pprint from shapely.geometry import shape, Point from geopy.geocoders import Nominatim from geopy.exc import GeocoderTimedOut from geopy.exc import GeocoderServiceError import collections from matplotlib import pyplot as plt import time import csv ...
1,819
1b4c86fe3aae25aeec6cd75fa8177983ce9d14a2
#!/usr/bin/python2.7 import os, sys COMPILER = "gcc" SRC_DIR = "../src" INCLUDE_DIR = "../src" BIN_DIR = "../bin" BIN_NAME = False CFLAGS = ["-O3", "-Wall", "-Wextra", "--std=c89", "-pedantic"] DLIBS = ["ws2_32"] if os.name == "nt" else [] DEFINES = [] def strformat(fmt, var): for k in...
1,820
1aed8e92a31ee42a3a609123af927f7074598ec1
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/7/14 下午6:06 # @Author : Huang HUi # @Site : # @File : Longest Common Prefix.py # @Software: PyCharm class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ ...
1,821
63edbbbad9561ddae005d2b5e22a089819dc34c5
import torch import random from itertools import product from Struct import Action class Agent(object): """the agent""" def __init__(self, q, epsilon=0.8, discount=0.9, learningRate=0.5, traceDecay=0.3): # action set possibleChangesPerMagnet = (1e-2, 1e-3, 0, -1e-2, -1e-3) # possible...
1,822
41842e8b75860c65e87e9db1f7ae058957e37e45
#Import Discord Package import discord from discord.ext import commands import asyncio import glob from dotenv import load_dotenv import os load_dotenv() # Load your Discord Token TOKEN = os.getenv("TOKEN") bot = commands.Bot(command_prefix='.',case_insensitive=True) print('Ready!') @bot.command() async def stop...
1,823
e3e6f1b6580a223558791cebfcb1a92d45553162
def digital_sum(n): if n < 10: return n return n % 10 + digital_sum(n // 10) def digital_root(n): if n < 10: return n return digital_root(digital_sum(n))
1,824
c5ac37ce09f7cd76ccd9b93c64e602209a04c55c
import requests from pyrogram import Client as Bot from samantha.config import API_HASH, API_ID, BG_IMAGE, BOT_TOKEN from samantha.services.callsmusic import run response = requests.get(BG_IMAGE) file = open("./etc/tg_vc_bot.jpg", "wb") file.write(response.content) file.close() bot = Bot( ":memory:", API_ID,...
1,825
f4c90a6d6afdcf78ec6742b1924a5c854a5a4ed6
import os def take_shot(filename): os.system("screencapture "+filename+".png")
1,826
1e41cc5d2661f1fb4f3a356318fabcb2b742cbdf
from flask import Flask,Response,render_template,url_for,request,jsonify from flask_bootstrap import Bootstrap import pandas as pd import gpt_2_simple as gpt2 import json app = Flask(__name__) Bootstrap(app) #Main Page @app.route('/') def interactive_input(): return render_template('main.html') #Creating the diff...
1,827
fab7ee8a7336ba2c044adce4cc8483af78b775ba
#!/usr/bin/env python from distutils.core import setup setup( name='RBM', version='0.0.1', description='Restricted Boltzmann Machines', long_description='README', install_requires=['numpy','pandas'], )
1,828
3329db63552592aabb751348efc5d983f2cc3f36
# -*- coding: utf-8 -*- """ Created on Sat Mar 21 09:46:47 2020 @author: Carlos Jose Munoz """ # se importa el modelo y vista para que sesten comunicados por medio del controlador from Modelo import ventanadentrada from Vista import Ventanainicio,dosventana import sys from PyQt5.QtWidgets import QApplication clas...
1,829
05573b4ff68ca8638f8e13946b410df2a012840a
from datetime import timedelta, datetime import glob import json import os import re import pickle import os,time import pandas as pd import numpy as np from collections import Counter from sentencepiece import SentencePieceTrainer from sentencepiece import SentencePieceProcessor from sklearn.feature_extraction.text i...
1,830
b29f85ccf396640c2a63bf634b549a3eaa0dbb1b
#!/usr/bin/env python2 from Crypto.PublicKey import RSA from Crypto.Util.number import * from timeit import default_timer as timer import os import gmpy2 import itertools as it def extract2(inp): two = 0 while inp % 2 == 0: inp //= 2 two += 1 return inp, two def genkey(): while 1: ...
1,831
f1fbbbe4258d0fb0a43505f4718730934fd595ec
import socket import threading server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) port = 12321 server.bind(('', port)) server.listen() client_names = [] clients = [] def broadcast(message): for client in clients: client.send(message) def handle(client): while True: try: ...
1,832
018b9533074d2766dc5010ff9c5e70888d249b45
a = range(10) [x*x for x in a]
1,833
7f33effa86fc3a80fce0e5e1ecf97ab4ca80402d
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import json import requests BASE_URL = 'http://www.omdbapi.com/' def rating_msg(rating): if rating > 80: return 'You should watch this movie right now!\n' elif rating < 50: return 'Avoid this movie at all cost!\n' else: re...
1,834
23bcef07326db084d4e0e6337beb00faba329193
// Time Complexity : O(n) // Space Complexity : O(n) // Did this code successfully run on Leetcode : Yes // // Any problem you faced while coding this : No // Your code here along with comments explaining your approach class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: res=[] ...
1,835
7d5f41cfa2d5423c6db2678f1eb8160638b50c02
import re class CoordinatesDataParser: def __init__(self): return def get_coords(self, response): html = response.xpath('.//body').extract_first() longitude = re.search(r'-\d+\.\d{5,}', html) longitude = longitude.group() if longitude else None if longitude: ...
1,836
b720a52f1c2e6e6be7c0887cd94441d248382242
from joecceasy import Easy def main(): paths = ['..','.'] absOfEntries = [ i.abs for i in Easy.WalkAnIter(paths) ] for i in absOfEntries: print( i ) if __name__=='__main__': main() """ def main(maxEntries = 99): i = -1 print( "Walker test, Walking cu...
1,837
de884413dcbd0e89e8bfcf5657fe189156d9a661
from setuptools import setup, find_packages setup(name="sk_processor", packages=find_packages())
1,838
b3bba1119bfaf0c1e684e8835259ec6fa8c42cf7
from text_to_word_cloud import * from collections import Counter from preprocess import * if __name__ == '__main__': data = load_data('train.json') words = text_to_words(get_all_text(data), as_set=False) cnt = Counter(words) save_il_to_word_cloud_file("cloudofw.txt",cnt,len(words),call_R=True...
1,839
c67cd3c16c15d6aab02a07736c83bbdd5bd98514
# -*- coding: utf-8 -*-" """ getMetaStream action for graphingwiki - alternative meta retrieval action that uses abuse-sa query language for filtering metas and returns Line Delimeted JSON or event-stream @copyright: 2015 Lauri Pokka <larpo@codenomicon.com> @license: MIT <http://www.openso...
1,840
7f72f6a2ff0c7ceacb0f893d04c20402e850421a
ss=str(input()) print(len(ss)-ss.count(' '))
1,841
1972e3733918da654cd156a500432a35a239aed4
tn=int(input()) for ti in range(tn): #ans = work() rn,cn = [int(x) for x in input().split()] evenRow='-'.join(['+']*(cn+1)) oddRow='.'.join(['|']*(cn+1)) artrn = rn*2+1 print(f'Case #{ti+1}:') for ri in range(artrn): defaultRow = evenRow if ri%2==0 else oddRow if ri//2==0: ...
1,842
07a0ba3ded8a2d4a980cfb8e3dbd6fd491ea24b0
import web import datetime # run with sudo to run on port 80 and use GPIO urls = ('/', 'index', '/survey', 'survey') render = web.template.render('templates/') class survey: def GET(self): return render.survey() class index: def GET(self): i = web.input(enter=None) ...
1,843
d07046e33bbfa404c354fef3e8990a3fa0203060
#Task 4 - writing a code that prints all the commit message from repository import requests r = requests.get('https://api.github.com/repos/smeiklej/secu2002_2017/commits') text = r.json() #asking the code to print out the commit message for all rows in the text for row in text: print row['commit']['message']
1,844
72d41f939a586fbd8459927983d9d62a96b650e2
from __future__ import division, print_function import numpy as np from copy import deepcopy class IntegratedRegressor(): regs = [] def __init__(self, reg, predict_log=True): self.reg = reg self.predict_log = predict_log def fit(self, X, y): self.regs = [] for target in ...
1,845
6946601050802aaaa559d25612d0d4f5116559eb
from django.shortcuts import render, redirect, get_object_or_404 from .models import Article, Comment # from IPython import embed # Create your views here. def article_list(request): articles = Article.objects.all() return render(request, 'board/list.html', { 'articles': articles, }) def articl...
1,846
81da2aab9ca11e63dafdd4eefc340d37b326fc6f
# ======= # Imports # ======= import os import sympy import numpy from distutils.spawn import find_executable import matplotlib import matplotlib.pyplot as plt from .Declarations import n,t # ============= # Plot Settings # ============= def PlotSettings(): """ General settings for the plot. """ # C...
1,847
3bfe4021d5cf9bd24c0fb778b252bc04c6ac47ed
import json import requests class Bitcoin: coindesk = 'https://api.coindesk.com/v1/bpi/currentprice.json' def __init__(self): pass def get_current_price(self, url=coindesk): self.resp = requests.get(url) if self.resp.status_code == 200: return json.loads(self.resp.con...
1,848
1dd62264aafe8ee745a3cfdfb994ac6a40c1af42
import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt class LogisticRegression: '''LogisticRegression for binary classification max_iter: the maximum iteration times for training learning_rate: learing rate for gradiend decsend training Input's shape shoul...
1,849
aa817b86e26cf8cd9771aeb276914a1f5869c737
#!/usr/bin/python import csv import sys import os.path #Versao 2 do gerador das RawZones #global DIR_PYGEN = "/bid/_temporario_/pythonGeneration/" DIR_INTGR_PAR = "/bid/integration_layer/par/" DIR_INTGR_JOB = "/bid/integration_layer/job/" def Sqoop(filename,source_database,source_table, split_field, sourcesystem, ta...
1,850
29298ee7ddb4e524a23000abf86854d72f49954c
from app import db from datetime import datetime from sqlalchemy.orm import validates class Posts(db.Model): id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) title = db.Column(db.String(200)) content = db.Column(db.Text) category = db.Column(db.String(100)) created_date = db.Column(db.Date...
1,851
20ac73789fa7297a9230a6a2b814349d2b7da5fb
import hashlib a = hashlib.pbkdf2_hmac("sha256", b"hallo", b"salt", 1) b = hashlib.pbkdf2_hmac("sha256", a, b"salt", 1) c = hashlib.pbkdf2_hmac("sha256", b"hallo", b"salt", 2) print(b) print(c)
1,852
7040db119f8fd6da78499fc732e291280228ca10
# Generated by Django 3.2.3 on 2021-05-16 07:56 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('problem', '0002_problem_...
1,853
e267108177841110493061a4f84ae3d29850d028
from django.urls import path from . import views urlpatterns = [ # @app.route("/") path('', views.home), path("teams", views.showTeams), path("teams/new", views.new), path("teams/<teamname>", views.showSpecificTeam), # path("allfood", views.showAllFoodItems), # path("team/<teamname>",...
1,854
080110e404cf5edfe53622a5942b53f9188ddd76
import pickle if __name__ == '__main__': with open('id_generator.bin', 'rb') as f: print(pickle.load(f))
1,855
e9a6baf10efc5b6bd07af1fe352b0b17ecc172bd
import numpy as np import json import random from encapsulate_state import StateEncapsulator from scalar_to_action import ActionMapper import pickle from basis_functions import identity_basis, interactive_basis, actions_only_basis, actions_cubic_basis, BASIS_MAP import matplotlib.pyplot as plt STATE_FILENAME = "stat...
1,856
365e2059d5ed3d7f8d9dbb4e44f563b79d68b087
from keras.preprocessing.text import text_to_word_sequence import os # keras NLP tools filter out certain tokens by default # this function replaces the default with a smaller set of things to filter out def filter_not_punctuation(): return '"#$%&()*+-/:;<=>@[\\]^_`{|}~\t\n' def get_first_n_words(text, n): ...
1,857
d17f1176ac60a3f6836c706883ab1847b61f50bf
import ConfigParser ''' Merge as many as ConfigParser as you want''' def Config_Append(SRC_Config ,DST_Config): import tempfile temp_src = tempfile.NamedTemporaryFile(delete=True) temp_dst = tempfile.NamedTemporaryFile(delete=True) with open(temp_src.name,'wb') as src, open(temp_dst.name,'wb') as dst: ...
1,858
afacc2c54584c070963c4cb3cabbae64bb0e3159
# Generated by Django 2.2.16 on 2020-11-04 12:48 import ckeditor_uploader.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course', '0002_auto_20201103_1648'), ] operations = [ migrations.AddField( model_name='course',...
1,859
3135483c68880eeeaf7ebc085a6cd3c0c7f0550c
import pymysql def main(): conn = pymysql.connect(host='127.0.0.1', port=3306,user='root',password='383240gyz',db='bycicle',charset='utf8') print(conn) try: with conn.cursor() as cursor: # 上下文语法否则需要 # cursor.close() cursor.execute('''drop table if exists pymysql''') curs...
1,860
9666c87b4d4dc721683ea33fdbbeadefc65a0cd1
#!/usr/bin/env python number=int(input("Enter an integer")) if number<=100: print("Your number is smaller than equal to 100") else: print("Your number is greater than 100")
1,861
6e5b8be6182f39f185f4547f0abd84a4e404bf34
import numpy as np mydict = {} mylist0 = np.array([1, 2, 3, 4, 5]) mylist1 = np.array([2, 3, 4, 5, 6]) print(mydict) print(mylist0) print(mylist1) for c in ('0', '1'): if c in mydict: mydict[c] += mylist0 else: mydict[c] = mylist0 print(mydict) for c in ('0', '1'): ...
1,862
0527dc2b6fa0fe703b604c6e28fba44fe6def83b
def main(): # defaults to 0 print a a = 7 a *= 6 print a
1,863
6424fccb7990b0a1722d5d787e7eb5acb4ff1a74
import boto3 ec2 = boto3.resource('ec2') response = client.allocate_address( Domain='standard' ) print(response)
1,864
2561db1264fe399db85460e9f32213b70ddf03ff
#!/usr/bin/env python # encoding: utf-8 """ @author: swensun @github:https://github.com/yunshuipiao @software: python @file: encode_decode.py @desc: 字符串编解码 @hint: """ def encode(strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ res = '' ...
1,865
fc5a4c27a21c2bd3900a6ad0bff68c249fe29d7a
from selenium import webdriver from selenium.webdriver.common.keys import Keys import requests import time driver = webdriver.Chrome(executable_path='/home/bc/桌面/chromedriver') driver.get('https://www.zhaopin.com/') time.sleep(5) driver.find_element_by_id('KeyWord_kw2').send_keys('技术') driver.find_element_by_class_na...
1,866
03a024140d8d0136bf9838f8942539f6d19bb351
from cmd import Cmd class CMD(Cmd): def __init__(self): pass def do_move(self, direction): if direction == "up": self.game.movePlayer(0, 1) elif direction == "down": self.game.movePlayer(0, -1) elif direction == "left": self.game.movePlayer(-...
1,867
8fe71e87512dfd2ccfcd21c9c175cb50274d9661
""" Tests based on: https://github.com/pydata/xarray/blob/071da2a900702d65c47d265192bc7e424bb57932/xarray/tests/test_backends_file_manager.py """ import concurrent.futures import gc import pickle from unittest import mock import pytest from rioxarray._io import URIManager def test_uri_manager_mock_write(): mock...
1,868
9627e8a468d3a75787c5a9e01856913fc8beb3c4
# -*- coding: utf-8 -*- """ Created on Fri Nov 14 22:09:56 2014 @author: duhan """ #arrayMapPath = r'/usr/local/lib/python2.7/dist-packages/ticketpitcher/data/3' arrayMapPath = r'C:\Python27\Lib\site-packages\ticketpitcher\data' #tempPath = r'/tmp/' tempPath = 'd:\\temp\\'
1,869
97857c1c5468a96187d44abc23ffaaf2a7ead1a6
# data={ # "name":"Alby", # "age":23 # } # print (data['age']) # def foo(): # print("Hellow world") # return 1 # print (foo()) a="aa" def add(): print(a) add()
1,870
ed4c97913a9dba5cf6be56050a8d2ce24dbd6033
''' A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Given two integers A and B, print the number of primes between them, inclusively. ''' a = int(input()) b = int(input()) count = 0 for i in range(a, b+1): true_prime = True for num in range(2, i): ...
1,871
c435b0f162512bb2bc0c35e1817f64c5ef9ff7bc
# vim:fileencoding=utf-8:noet from __future__ import absolute_import, unicode_literals, print_function import os BINDINGS_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bindings') TMUX_CONFIG_DIRECTORY = os.path.join(BINDINGS_DIRECTORY, 'tmux') DEFAULT_SYSTEM_CONFIG_DIR = None
1,872
cf5a9b8dad5a02610fa5ce2a849b6f9fc50a0aa8
#2) write a program to make banking system develop business logic #in one module and call functionality in another .py file class Customer: #user defined class def __init__(self,name,phoneno,address,pin,accno,balance) : #constructor with multiple arguments self._name=name self._pno=phoneno ...
1,873
0f0b3eea9dc397d32e81749304041abaf6651e94
from common.get_keyword import GetKeyword from common.operation_Excel import OperationExcel from common.op_database import OpDatabase from interface.login import Login from interface.address import Address import unittest import ddt # 测试数据 op_excel = OperationExcel() add_file = r'D:\pyCharm\Demo\pycode\Requests\201911...
1,874
f3bfa30f51c4a91844457c72fbf2b2b8368d8476
import datetime interval_length_minutes = 10 # 10 minutes per interval tek_rolling_period = 144 # 24*60//10 - 24 hours per day, 60 minutes per hour, 10 minutes per interval def get_timestamp_from_interval(interval_number): return interval_number * interval_length_minutes * 60 # 60 seconds per minute def get...
1,875
6eecf0ff1ad762089db6e9498e906e68b507370c
import spacy nlp = spacy.load("en_core_web_sm") text = ( "Chick-fil-A is an American fast food restaurant chain headquartered in " "the city of College Park, Georgia, specializing in chicken sandwiches." ) # Disable the tagger and parser with ____.____(____): # Process the text doc = ____ # Print ...
1,876
b3f62c331ff4ae9f909fc90cc7303997b32daceb
''' O(n) time complexity O(n) space complexity ''' class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ seenum = dict() for idx, val in enumerate(nums): if target - val in seenum: ...
1,877
471cab65aac29f5b47de0ffef8f032dbbadf8dd0
from flask import Flask, render_template, send_from_directory from flask import request, send_file from flask_cors import CORS import os import json from crossdomain import crossdomain import constants import generation_tools from music_theory import name_chords_in_tracks import midi_tools from client_logging import Cl...
1,878
da69fd937153fe2112b9f64411882527274247ef
from sys import exit from os import stat file = open("fiunamfs.img","r") nombre = file.read(8) file.seek(10) version = file.read(3) file.seek(20) etiqueta = file.read(15) file.seek(40) cluster = file.read(5) file.seek(47) numero = file.read(2) file.seek(52) numeroCompleto = file.read(8) file.close() archivos = [] tam...
1,879
b28ae19f31ae746f901dea645dfeaa211a15cd31
from mcpi.minecraft import Minecraft from time import sleep import random mc = Minecraft.create() myID=mc.getPlayerEntityId("Baymax1112") mineral = [14,15,16,56,73,129,57] while True: sleep(0.5) r=random.choice(mineral) x,y,z = mc.entity.getTilePos(myID) mc.setBlocks(x+1,y+3,z+1,x-1,y-3,z-1,r)
1,880
5c0ee6e8a0d80dbb77a7a376c411b85bf1405272
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from math import sqrt from sys import exit from subprocess import Popen, DEVNULL from resmon import LineSegment, reorder_step def write_head(file): with open("head.tex", "r") as head: for line in head: f.write(line) def writ...
1,881
016c004fd95d901a6d55b6f7460397223a6baa3b
# -*- coding: UTF-8 -*- from flask import Blueprint, jsonify, request, abort, current_app import json from config import config_orm_initial orm = config_orm_initial.initialize_orm() session = orm['dict_session'] Article_list = orm['dict_Articlelist'] user = orm['dict_user'] app = Blueprint('api_get_comments', __name_...
1,882
4e6401672d4762b444bb679e4cc39ada04193a26
import tkinter as tk from tkinter import Tk, BOTH,RIGHT,LEFT,END from tkinter.ttk import Frame, Label, Style,Entry from tkinter.ttk import Frame, Button, Style import random import time class StartPage(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) tk.Frame.configu...
1,883
a2e4e4a0c49c319df2adb073b11107d3f520aa6e
import itertools def odds(upper_limit): return [i for i in range(1,upper_limit,2)] def evens(upper_limit): return [i for i in range(0,upper_limit,2)] nested = [i**j for i in range(1,10) for j in range(1,4)] vowels = ['a', 'e', 'i', 'o', 'u'] consonants = [chr(i) for i in range(97,123) if chr(i) not in vowe...
1,884
7611a57705939ce456e34d5ae379d6ca748b13c3
#!/usr/bin/env python # encoding: utf8 #from __future__ import unicode_literals class RefObject(object): def __init__(self,): self.pose = [] self.name = [] self.time = None self.id = None def set_data(self,pose, name, time, Id): self.pose = pose self....
1,885
7bcdd6c5c6e41b076e476e1db35b663e34d74a67
from urllib import request from urllib import error from urllib.request import urlretrieve import os, re from bs4 import BeautifulSoup import configparser from apng2gif import apng2gif config = configparser.ConfigParser() config.read('crawler.config') # 下載儲存位置 directoryLocation = os.getcwd() + '\\img' # 設置要爬的頁面 urlLis...
1,886
d423b0bc6cd9ea9795317750141ad5f5eab01636
import sys import os sys.path.append("C:/Users/Laptop/Documents/Repos/udacity_stats_functions/descriptive") import normal_distribution_06 #import sampling_distributions_07 def lower_upper_confidence_intervals(avg, SD): #avg is x bar. The mean value at the "would be" point. ie Bieber Tweeter #SD is standard err...
1,887
f69351474fb3eb48eeb65eaf1aa46d2f4a390471
# -*- coding: utf-8 -*- from nose.tools import * # noqa import mock import httpretty from tests.base import OsfTestCase from tests.factories import AuthUserFactory, ProjectFactory import urlparse from framework.auth import Auth from website.addons.mendeley.tests.factories import ( MendeleyAccountFactory, ...
1,888
08ccc58fe139db3f4712aa551b80f6ea57e0ad76
# -*- coding: utf-8 -*- """ Created on Tue Sep 23 10:16:40 2014 @author: Yusuke """ import math result = [] for i in range(6 * 9**5): sum_num = 0 for j_digit in str(i): sum_num += int(j_digit) ** 5 if sum_num == i: print i result.append(i) print math.fsum(result)
1,889
4989d01f31ca034aacdda28eff56adb2e0bb15da
""" Modulo collection - Counter Collections -> High-performance Container Datatypes Counter -> Recebe um interável como parametro e cria um objeto do tipo Collections Counter que é parecido com um dicionario, contendo como chave o elemento da lista passada como parametro e como valor a quantidade de ocorrencia...
1,890
57d6b9e7f48d32e5d10bfd6a340ea56281f5d82d
# O(logn) T O(1) S def binarySearch(array, target): if len(array) == 0: return -1 else: return binarySearchR(array, target, 0, len(array) - 1) def binarySearchR(array, target, leftPointer, rightPointer): if leftPointer > rightPointer: return -1 else: midPointer = (leftP...
1,891
9b7ffa2bb62a8decbec51c6bdea38b4338726816
# -*- coding: utf-8 -*- """pytest People functions, fixtures and tests.""" import pytest import ciscosparkapi from tests.utils import create_string # Helper Functions # pytest Fixtures @pytest.fixture(scope="session") def me(api): return api.people.me()
1,892
d22ebe24605065452ae35c44367ee21a726ae7a1
# Databricks notebook source #import and create sparksession object from pyspark.sql import SparkSession spark=SparkSession.builder.appName('rc').getOrCreate() # COMMAND ---------- #import the required functions and libraries from pyspark.sql.functions import * # COMMAND ---------- # Convert csv file to Spark Data...
1,893
d6cfe7132855d832d8fd1ea9ca9760bd22109a92
# -*- utf-8 -*- from django.db import models class FieldsTest(models.Model): pub_date = models.DateTimeField() mod_date = models.DateTimeField() class BigS(models.Model): s = models.SlugField(max_length=255) class Foo(models.Model): a = models.CharField(max_length=10) d = models.DecimalField(...
1,894
3dcca85c8003b57ad37734bbbe171ab8cef0f56c
# This package includes different measures to evaluate topics
1,895
b360ba7412bd10e2818511cee81302d407f88fd1
# 3번 반복하고 싶은 경우 # 별 10개를 한줄로 for x in range(0, 10, 3): # 3번째 숫자는 증감할 양을 정해줌. # print(x) print("★", end=" ") print() print("------------------------") #이중 for문 for y in range(0, 10): for x in range(0, 10): # print(x) print("★", end=" ") print()
1,896
a79c9799ed237a943ae3d249a4d66eb2f8693e83
# Runtime: 44 ms, faster than 62.95% of Python3 online submissions for Rotate List. # Memory Usage: 13.9 MB, less than 6.05% of Python3 online submissions for Rotate List. # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class...
1,897
0f0ea6f07f9a082042ed9aff7a95d372c32b5a13
from __future__ import absolute_import, division, print_function import numbers import torch from torch.distributions import constraints from pyro.distributions.distribution import Distribution from pyro.distributions.score_parts import ScoreParts from pyro.distributions.util import broadcast_shape, sum_rightmost ...
1,898
9bc955def6250908050a1f3046dd78480f25e0a1
from pyplasm import * doorY = [.2,.18,.08,.18,.08,.18,.4,.18,.08,.18,.08,.18,.2] doorX = [.2,.5,.2,1.8,.08,.18,.08,.18,.2] doorOccurrency = [[True]*13, [True, False, True, False, True, False, True, False, True, False, True, False, True], [True]*13, [True, False, True, False, True, False, True, False, T...
1,899
8126af930ec75e2818455d959f00285bdc08c044
import unittest from LempelZivWelchDecoder import LempelZivWelchDecoder class TestLempelZivWelchDecoder(unittest.TestCase): def test_decode(self): test_value = ['t', 256, 257, 'e', 's', 260, 't', '1'] run_length_decoder = LempelZivWelchDecoder() self.assertRaises(ValueError, ...