index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
11,200
6c7267fd257a9ecc6325a012b52052447cb326cd
import time name=input (print("What's your name?")) print("Hello "+name,"Time to play hangman!") time.sleep(1) print ("Start guessing...") time.sleep(0.5) word= str (input(print("Enter any word: "))) print ("The length of the word is: ") print (len(word)) guesses=" " turns=10 while turns >0: failed =0 ...
11,201
bb94a6f7dd43c506749dbbaea8e77ce8ce05edfa
# 合并排序 # 时间复杂度, 最坏情况, 最好情况, 空间复杂度 # O(nlogn), O(nlogn), O(nlogn), O(n) def merge(l, r): """ 合并的过程 :param l: :param r: :return: """ new_list = [] tag_l = 0 tag_r = 0 while tag_l < len(l) and tag_r < len(r): if l[tag_l] < r[tag_r]: new_list.append(l[tag_...
11,202
8a46da47f866e506ece43284a896e9ffe7c2a453
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow import keras import bert from bert import BertModelLayer from bert.loader import StockBertConfig, map_stock_config_to_params, load_stock_weights import numpy as np impor...
11,203
2097c2f7ca16a07af7fd132b3a4f540fccca7973
import vrep import vrep_constants as const import math from matplotlib.path import Path from numpy import array class Point: def __init__(self, xy=None): if isinstance(xy, tuple): if len(xy) >= 2: self.x = xy[0] self.y = xy[1] else: if not isi...
11,204
7b2214c835749e01abe93b561b9b9063040d942f
buttons = [ 'й', 'ц', 'у', 'к', 'е', 'н', 'г', 'ш', 'щ', 'з', 'х', 'ъ', 'ф', 'ы', 'в', 'а', 'п', 'р', 'о', 'л', 'д', 'ж', 'э', 'я', 'ч', 'с', 'м', 'и', 'т', 'ь', 'б', 'ю', '-', 'ё', 'ПРОБЕЛ', 'СТЕРЕТЬ', 'ЗАГЛАВН', 'ПЕЧАТЬ' ] bg_color = '#3c4987' fg_color = '#ffffff' active_color = fg_color fg_active_co...
11,205
cdd7b4420b0ccfe2ee31c81890a0fbb6c14178e9
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions ...
11,206
0fb859a1504454590ffdb236769f40b0136b326f
from abc import ABCMeta, abstractmethod class SignalTransform(object): __metaclass__ = ABCMeta @abstractmethod def interpolate(self, image): """ gets the value of the signal at the specific point, as the signal is discrete it will be interpolated """ return
11,207
021c16b3aa2b8424555798eccb39edf29e4d790f
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import shutil import unittest from pathlib import Path from unittest.mock import MagicMock, call, patch from .. import source_dat...
11,208
d56f0054b53c0ee21960f54ffd57bcb0557fe327
from schematics import Model from schematics.types import StringType, FloatType class ConvertModel(Model): currency_from = StringType(required=True) currency_to = StringType(required=True, default="USD") amount = FloatType(required=True) class SetCurrencyModel(Model): currency_name = StringType(requ...
11,209
aa95f2f39d80895607271f715762d84ab37a7bfa
#CODE HAS ISSUES 1/25/11 (TIF) # Adding and scaling vectors # This is the same example except you can make # this easier to understand by using just two # values: the initial point (a P3) and the direction # (another P3). You can add two P3's together and multiply # a P3 by a number. from Panda import * # Replace th...
11,210
a00c42d08869d3440e5a655fef6a588fa9e360c4
import os import json import tomopy import dxchange import numpy as np from tomopy_cli import log from tomopy_cli import file_io from tomopy_cli import prep from tomopy_cli import beamhardening def all(proj, flat, dark, params, sino): # zinger_removal proj, flat = zinger_removal(proj, flat, params) if (...
11,211
50024dda9e6169a0916ec4bd7cf2f8d4ed861de1
def facto(number): number = int(number) if number <= 1: return 1 else: return number * facto(number - 1) # note: f strings don't allow escape sequences in substrings print(f"{facto(input('Enter a number:'))} is the factorial")
11,212
c3414efc519aab0cd8e56c53f0b007873775a983
from PySide6.QtCore import * from PySide6.QtWidgets import * import sys class myLabel(QLabel): clicked = Signal() def mouseReleaseEvent(self, QMouseEvent): if QMouseEvent.button() == Qt.LeftButton: self.clicked.emit() class Wind(QDialog): clicked = Signal() def __init__(self): ...
11,213
3c10debca638eac97dad7e32a71469b0a366ee48
from ast import literal_eval from enum import Enum import numpy as np from evaluation.relative_error.rerr_reduction import rel_err_reduction class Metric(Enum): # Relative Error Reduction RERR_RED = 'nae_reduction' PRED_BASELINE = 'pred_baseline' PRED_MEAN = 'pred_mean' ACTUAL_MEAN = 'actual_mea...
11,214
bcb6e4bca061fcc0dce6428bd61926deb5a4838a
import re text = """ This PEP contains the index of all Python Enhancement Proposals, known as PEPs. PEP numbers are assigned by the PEP editors, and once assigned are never changed[1]. The Mercurial history[2] of the PEP texts represent their historical record. """ pattern = r'hist+' match_obj = re.fi...
11,215
1017fc3e825e41870b0f0284bf6512e2f59f2d5c
import csv product=[] order=[] relationship=[] with open("products.csv") as pr_csv: pr_reader=csv.reader(pr_csv,delimiter=',') for row in pr_reader: product.append(row) pr_csv.close() with open("orders.csv") as or_csv: or_reader=csv.reader(or_csv,delimiter=',') next(or_reader) for row in or_...
11,216
6b19084f1f338c8bef5087b49b104b8b6cbb3454
#! /usr/bin/env python # Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration ## @Package test_trfExceptions.py # @brief Unittests for trfExceptions.py # @author graeme.andrew.stewart@cern.ch # @version $Id: test_trfExceptions.py 570543 2013-11-14 21:52:16Z graemes $ import unittest import log...
11,217
1e28d0dc0724c76a5ac09f63e9073ac6095e04cf
''' Created on Oct 31, 2012 @author: jason ''' import pymc from math import log import random as rand import numpy from itertools import izip import _Survival class Event(object): '''Represents a single event that can happen once. The typical example is death. time - (float) The time to death or censors...
11,218
80982caa189b21086a39995ed3819501e730771a
import re import urllib from kafka import KafkaProducer, KafkaClient import sys import json from kafka.client import KafkaClient from kafka.producer import KafkaProducer from twitter import * class Producer(object): def __init__(self, addr): self.producer = KafkaProducer(bootstrap_servers=addr) def pr...
11,219
016ba92883045e0be008ae8da4e28fd45fa81f6f
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('bookaround', '0025_auto_20140927_1958'), ] operations = [ migrations.AlterField( ...
11,220
2e847ec1f6a8b9379f3a7bd47929c3d1549996e4
#!/usr/bin/env python import rospy import time from geometry_msgs.msg import Twist from rosgraph_msgs.msg import Clock from std_msgs.msg import Bool class ActionPublisher(): def __init__(self): if rospy.get_param("train_mode"): raise Exception("This node should be used solely in eval mode!") ...
11,221
9032db9e403c94854a9c06c3a38df0c57275d8c7
import datetime as dt from typing import Optional, Iterable, Any, Dict, Tuple, Sequence from sqlalchemy import ( select, delete, update, func, literal_column, ) from sqlalchemy.dialects.postgresql import insert, aggregate_order_by from sqlalchemy.orm import selectinload, defer from aleph.db.models...
11,222
ef3b268d46e3f7ddfcb12048cb040533db6af125
from lesson18.pages.base_page import BasePage from lesson18.pages.locators import HeaderPageLocators class HeaderPage(BasePage): def search(self, txt): """ Поиск по сайту """ self.__should_be_search_input() self.__should_be_search_button() self.__set_search_text(txt) self._...
11,223
c3665e4c0d14802989275f6b3f73ca69c03dab05
from django.db import models from django.forms import ModelForm from datetime import datetime import datetime as dt from django.conf import settings from django.utils import timezone from django.dispatch import receiver from django.db.models.signals import post_save class DrinkInformation(models.Model): ...
11,224
1c52c7b6d9857824e599ead4060bc211efbd085c
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-12-08 16:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('projects', '0001_i...
11,225
4b76d73d3c75a57ecbb9cdfb867192f741009c5c
import pandas as pd IN_FPATH = "./ThemeList.xlsx" OUT_FPATH = "./ThemeList.csv" df = pd.read_excel(IN_FPATH, sheet_name="Sheet1") df_out = [] for theme in df["theme"].unique(): df_ = df[ df["theme"] == theme ] df_ = df_["content"] for i in range(len(df_.index)): for j in range(len(df_.ind...
11,226
f08f234b5e3b21dea0e28af767b31255cc1b713b
# # 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 agreed to in writing, software # distributed under ...
11,227
887566ad6e6035a30759a8d078f23c127ff39527
import os import django import timeit from datetime import date, datetime, timedelta os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") django.setup() import string from random import choice, randint, random, sample from django.contrib.auth.models import User from django.utils.text import slugify ...
11,228
40d34e45034c15edf20e142cd1a030f7a24bc30b
import pybedtools from pybedtools import BedTool import numpy as np from tqdm import tqdm import pandas as pd import multiprocessing from multiprocessing import Pool import functools import argparse # Process the given region, retrive all valid GEMs def ProcessRegion(ChIA_Drop,Loop,savebedpath): # Loop: thr...
11,229
6fb35881f4509c11769dfcb746d2736cc0b317f7
import random import time import threading from DetectDeadlock import DetectDeadlock pfNum = 5 phi_nums = ('Philosopher 1','Philosopher 2','Philosopher 3','Philosopher 4', 'Philosopher 5') Inventory = { 'fork1': 0, 'fork2': 0, 'fork3': 0, 'fork4': 0, 'fork5': 0, 'soup':...
11,230
bacd3cd8937871137d5bfca8607114a2d3e4e23b
# -*- coding: utf-8 -*- import time from serial import rs485 import serial from serial.tools.list_ports import comports from hextools import * import binascii class SerialPortProblem(Exception): pass class OledButton(object): ''' oled cy-7031 The OLED BUTTON SWITCH and DISPLAY MODULE p...
11,231
f88b87dd25a06f4f77d3bf8b1407377f45b5acb2
#! /usr/bin/python # -*- coding: utf8 -*- import sys file=(sys.argv[1]) open_file=open(file,"r") l=0 for line in open_file: l=l+1 print ("Number of lines:", l) open_file.close()
11,232
bae9b9680aa1457991ee01ff2637accd0e3fa242
x=raw_input("enter the string") n=input("enter the number of times") for y in range(n): print(x)
11,233
dfa057df15570c9470a88696cb36de4c07cfe226
#编程实现字符串反转 #输入:Hello,World! #输出:!dlroW,olleH # 字符串里面的每一个字符进行压栈 # 出栈 直到栈空为止 打印每个出栈元素 stack=[] for i in "hello,world!": stack.append(i) # print(stack.pop())#confirm if its right result=[] while len(stack) is not 0: result.append(stack.pop()) print("".join(result))
11,234
55d73504e5aeb8b5380e75bd0c84828c2afd650d
#_*_coding=UTF-8_*_ # copyright 2019 BILLAL FAUZAN # Karya Anak Bangsa # MD5 DENCRYPT Offline 90% """ NOTE: Please Abang Eneng Jangan Ubah Source Code Ny Saya Susah Payah Membuat Program Ini Saya Sengaja Open Source Supaya Anak Indonesia Bisa Membuat Program Sendiri Jadi Jangan Di Recode Bangsat!! """ __banner__...
11,235
14d974e9e4e582334604abc88558b127653cf12f
# coding=gb18030 cars = ['bmw', 'audi', 'toyota', 'subaru'] print(cars) print("注意,reverse()不是指按与字母顺序相反的顺序排列列表元素,") print("而只是反转列表元素的排列顺序:") cars.reverse() print(cars) print("方法reverse()永久性地修改列表元素的排列顺序,") print("但可随时恢复到原来的排列顺序, ") print("为此只需对列表再次调用reverse()即可。")
11,236
445db428f0a9a8c5f6189a589681fc53207e2425
from sklearn.model_selection import GridSearchCV from lightgbm import LGBMClassifier import joblib import pickle with open('yy.pickle' ,'rb') as f: x_train , y_train = pickle.load(f) model_lgb = LGBMClassifier(num_class =10 , objective='multiclass', metric=...
11,237
953a0c93772ef561e21c1fc78c2e117ae62f32d8
for n in range(6): out = '\t\t' for off in range(2): out += str(4*n)+',' for x in range(2): out += str(x+1+off+4*n)+',' out += ' ' print(out)
11,238
2c667978f29fedb95d21bafbdb79f9af3a7bb6f8
from random import randint import pyglet from source.settings import SETTINGS, player, enemies, Tile, TEXTURES, scenes from source.dungeons import dungeon import source.resources as res # Utility Functions def map_x(x): return x * (16) + 32 def map_y(y): return SETTINGS['Height'] - 16 * (y + 1) - 16 def ...
11,239
3d995aeb24138460994fa4aebccf25e786880b7b
from re import S from django import forms from django.forms import widgets from .models import Pizza, Size # class PizzaForm(forms.Form): # topping1 = forms.CharField(label='Topping 1', max_length=100) # topping2 = forms.CharField(label='Topping 1', max_length=100) # size = forms.ChoiceField(label='Size', ...
11,240
1a283ab2450840ad01b8187ccfc37f10430c2f36
import sys """ Combines the submission of various models into one submission Enter the files as command line arguments in order of decreasing weightage Assumes all files contain same number of rows """ def get_majority(lst): """ Uses Boyer-Moore algorithm to find majority element c...
11,241
ddf54566c58ddb4bb59019cd32c7141aa2cab50c
"""nibble_bee URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
11,242
1d4ba6f99db49af65391efc177494eebc9ef1b8d
cash = int(input("Amount of money you have?: ")) apple_price = int(input("How much is an apple?: ")) capacity_to_buy = cash//apple_price money_change = cash%apple_price print(f"You can buy {capacity_to_buy} apples and your change is {money_change} pesos.")
11,243
a994e4662a6592097bf8da52454e8f53c7de7251
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'jump_buy_1.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGui, QtWidgets import pyodbc class Ui_Dialog_jum...
11,244
30199b27f4c167b5e9cadb215b796af4a40b5a0c
import cv2 import numpy as np print("[CUDA TEST] Check CUDA enable device") count = cv2.cuda.getCudaEnabledDeviceCount() print("CUDA enable device count : %s \n" % count) print("[CUDA TEST] test CUDA upload & download") npMat = (np.random.random((128, 128, 3)) * 255).astype(np.uint8) cuMat = cv2.cuda_GpuMat() cuMat....
11,245
f447e26f1dcc23acd18908bedf878038ee002f14
import requests import pandas as pd from lxml import etree import time url_pa = 'https://search.51job.com/list/000000,000000,0000,00,9,99,%25E6%2595%25B0%25E6%258D%25AE,2,' url_end = '.html?lang=c&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare=' f...
11,246
f703a21f4d54bd7bd79bfbe22b6dec4b146f4ffb
import tensorflow as tf import numpy as np """ https://www.jianshu.com/p/52e7ae04cecf 保存模型和加载模型 这种方法不方便的在于,在使用模型的时候,必须把模型的结构重新定义一遍,然后载入对应名字的变量的值。 """ def save(): W = tf.Variable([[1, 1, 1], [2, 2, 2]], dtype=tf.float32, name="w") b = tf.Variable([0, 1, 2], dtype=tf.float32, name="b") print(W.shape) ...
11,247
f9e4705f9bca3bfc29e8619b6be83e76ab334cb5
""" @ Filename: AClassifier.py @ Author: ffcccc @ Create Date: 2019-11-07 @ Update Date: 2019-11-07 @ Description: Classification base class """ import numpy as np import pickle import preProcess class aClassifier: def __init__(self): self.prediction = None self.probabil...
11,248
726fbd2056797cabedcef594665a703f8236f44b
import os import platform __version__ = "1.5.6" __author__ = "Hao-Wei Lee" if platform.system() == "Windows": SEP = "\\" STDNUL = "NUL" else: SEP = "/" STDNUL = "/dev/null" ROOT_DIR = SEP.join(os.path.dirname(os.path.realpath(__file__)).split(SEP)[:-1]) def get_path(*names): return "{}{}{}".format(R...
11,249
6d7e796ae1fc9d0a0f4c9924e63d09ea60bea207
import sys import time import random def get(type): # random.seed(time.time() + 64738) rng = random.SystemRandom(time.time() * 64738) sort = random.SystemRandom(time.time() * 64738) if type == 'dick': rng.shuffle(DICK) return sort.choice(DICK) elif type == 'iching': linecoun...
11,250
09b6d774962b521b685276ff889f5447a838f9e9
#by zhuxing import datetime def do_telnet(Host, username, password): import telnetlib tn = telnetlib.Telnet(Host) tn.set_debuglevel(2) tn.read_until(‘Username:’) tn.write(username + ‘\n’) tn.read_until(‘Password:’) tn.write(password + ‘\n’) tn.read_until(‘switch#’) tn.write(‘sh run ‘ + ‘\n’) spacetime = 0 while...
11,251
5d4e1899ca8236348b34cf693fa9b4c32a21c0e1
import pip def install(package): if hasattr(pip, 'main'): pip.main(['install', package]) else: pip._internal.main(['install', package]) # Example if __name__ == '__main__': install('requests') install('collections') install('beautifulsoup4') install('nltk')
11,252
0e816a8f75ad8f45591c5c84302160ee154293a8
__all__ = [ 'ClothesPeg', ] from .peg import ClothesPeg
11,253
b324c161b9a1f63dabbaf9e352dd17a4b312c9b6
#03 - Modify the previous program such that only the users Alice and Bob are greeted with their names. print("Please, insert your name:") name = input() if name.lower() == "alice" or name.lower() == "bob": print("Welcome,", name)
11,254
bb4d85ea5a87f934441dc01085380d6c2e74ec13
# ! Author tuhinsaud@tuhinsaud # version: 1 import os from io import BytesIO from PIL import ImageTk, Image as PILImage import tkinter as tk from tkinter import * from tkinter import ttk, filedialog, messagebox import database_helper as db_helper from show_products_panel import * from update_window import update_wind...
11,255
2c3b64a137617b3d8835dcdb3bc08f5ffd352649
class RollingHash: def __init__(self, s): b1, b2 = 1007, 2009 self.mod1, self.mod2 = 10**9+7, 10**9+9 self.size = len(s) self.string = s self.hash1 = self.make_hashtable(b1, self.mod1) self.hash2 = self.make_hashtable(b2, self.mod2) self.pow1 = self.make_powt...
11,256
e141ac58c84295bbbd91a089c9a895ad389ee1fb
# coding = utf-8 ''' @author = super_fazai @File : demo1.py @Time : 2017/8/9 17:36 @connect : superonesfazai@gmail.com ''' import threading import time class MyThread(threading.Thread): # 重写 构造⽅法 def __init__(self,num,sleepTime): threading.Thread.__init__(self) self.num = num se...
11,257
6e5b3c2aebb562e048e2918e9d2fa2f5ba23fedb
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-03-03 11:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('testapp', '0006_auto_20190303_1105'), ] operations = [ migrations.CreateModel...
11,258
2dba51a6739827ce25fd0811c22852e3c44c289a
import time kvad = [] for i in xrange(1,16000+1): kvad.append(i*i) kv = [] for i in xrange(2000000): kv.append(i*i) kvad_s = set(kv) del kv def daili_net(x,y,z): if x+y in kvad_s and x-y in kvad_s and x+z in kvad_s and \ x-z in kvad_s and y+z in kvad_s and y-z in kvad_s: return True def da...
11,259
0efedcb7e6a230d23dc14bfd8714e52a54799d03
def prime(pStart=2,pEnd=20): a = [] for i in range(pStart,pEnd+1): for j in range(2,i+1): if(i%j == 0 and i != j): break; elif(i == j): a.append(i) for i in range(0,len(a)-1): print("{} ".format(a[i]),end='') print("{}".format(a[len...
11,260
d84e022b4cf1597618ff98c161eb0476ef5f13ff
#!/usr/bin/env python # coding: utf-8 # # Background # # - 1 The adjacent 3 tabs contain a data dump of search strings used by EXP clients to access relevant content available on Gartner.com for the months of August, September and October in the year 2018. Every row mentions if the EXP client is "P...
11,261
43ef305674c79110d5d416fa8f99f813bad3ef77
from pyaudio import PyAudio,paInt16 import numpy as np class AudioStream(object): def __init__(self, sample_rate = 16000, sample_channel = 1, sample_width = 2, sample_time = 0.025): samplebuffer = int(round(sample_rate * sample_channel * sample_width * sample_time)) pa = PyAudio() self.stre...
11,262
4fb9163e4a6b597b97c1a7fab2bd358dbb16ba63
from django.contrib import admin from .models import TalkProposal, AudienceChoice class AudienceChoiceModelAdmin(admin.ModelAdmin): model = AudienceChoice list_display = ("label", "created") ordering = ("label", ) class TalkProposalModelAdmin(admin.ModelAdmin): model = TalkProposal list_display...
11,263
5539203f0756b2708cf40a0a50d86ad727797310
#!/usr/bin/env python # -*- coding: utf-8 -*- import binascii import time import traceback import serial import ind903_reader.ind903_packet as ind903Packet from reader import reader Ind903Packet = ind903Packet.Ind903Packet; class DeviceException(Exception): pass class ReadException(Exception): pass cl...
11,264
2e83203c4b00fb53bcfb75138064a58a0618a8fc
from os.path import dirname, join from setuptools import setup from lan_presenter import __version__ with open(join(dirname(__file__), 'README.md')) as readme_file: long_description = readme_file.read() setup( name='lan-presenter', version=__version__, description='Presenter remote control over loca...
11,265
da47ec57dcaec311cac15a2b448732442911a824
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit van = Load(Filename='/SNS/CNCS/IPTS-21088/shared/autoreduce/van_273992.nxs', OutputWorkspace='van') data_folder = '/SNS/CNCS/IPTS-20360/nexus/' runs_1 = range(274470,274470+7, 1) #vanadium sample iteration = 0 for this_run in r...
11,266
4db7c3394f65868fdf2e90da33a24d3f12214f86
class Book: def __init__(self,page): self.page=page def __sub__(self, other): return Book(self.page-other.page) def __mul__(self, other): return Book(self.page*other.page) def __str__(self): return str(self.page) b=Book(25) c=Book(10) d=Book(5) print(b-c-d) print(b*c*d)...
11,267
df28db9d5077f7058cc6fd0ac76ec99838724b50
#!/usr/bin/env python3 # noqa: INP001, EXE001 """Tests for constants module.""" import pytest import overreact as rx from overreact import _constants as constants def test_reference_raw_constants(): """Ensure raw constants are close to values commonly used by the community. Reference values were taken fr...
11,268
3a61a671e61858657ec7f580862f3e60718c476c
# coding=utf-8 # time:2019-06-03 import requests from pyquery import PyQuery as pq def user_if_exits(): global url_list url_list = [] with open(file='url_list.txt', mode='r', encoding='utf-8') as u: data = u.readlines() for line in data: url_list.append(line.strip()) def ini...
11,269
515decf1d33aff5ef900d4eaa9cb057c0251924d
# Generated by Django 3.1.2 on 2021-04-02 19:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Comuna', fields=[ ...
11,270
333dc09dd095a7c19e4ea286f72abadea2bb7530
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger("db") from datetime import datetime, timedelta import sqlalchemy from sqlalchemy import Column, Integer, String, ForeignKey, DateTime from sqlalchemy.sql import func from sqlalchemy.orm impor...
11,271
5f841a8f62bef0c4a3343ba6084a0561540e10a3
from sklearn.feature_extraction.text import TfidfVectorizer import jieba def cut_word(text): """ 对中文进行分词 "我爱北京天安门"————>"我 爱 北京 天安门" :param text: :return: text """ # 用结巴对中文字符串进行分词 text = " ".join(list(jieba.cut(text))) return text def text_chinese_tfidf_demo(): """ 对中文进行特征抽...
11,272
4a902ea36b9bc9de05cfad4d5f9eafba6e322b02
from __future__ import annotations import logging import math from collections import defaultdict, deque from collections.abc import Iterable from datetime import timedelta from typing import TYPE_CHECKING, cast import tlz as toolz from tornado.ioloop import IOLoop from dask.utils import parse_timedelta from distri...
11,273
cd2b95246fb02225a9a4cf6a8f88d51086b03391
import re import os import io from datetime import datetime from typing import Optional, List, Callable, Tuple from pathlib import Path, PurePosixPath from contextlib import contextmanager from paramiko import RSAKey, DSSKey, ECDSAKey, Ed25519Key, \ Transport, ssh_exception, SSHClient, AutoAddPolicy, SSHException,...
11,274
660a2d39d264b675f288c1395ce27c53647e1831
from functools import wraps def debug(func): # func is a function being wrapped @wraps(func) def wrapper(*args, **kwargs): print(func.__qualname__) return func(*args, **kwargs) return wrapper @debug def add(x, y): return x + y @debug def subtract(x, y): return x - y @debug def multiply(x, y): return x ...
11,275
905a1dc56df7fb6789646dd8aaf784127b96d15e
#_training_code import pandas as pd import numpy as np from tensorflow.contrib.layers import flatten from keras.layers.pooling import MaxPooling2D from keras.models import Sequential, Model, load_model from keras.callbacks import EarlyStopping, Callback from keras.layers import Dense, Dropout, Activation, Flatten, L...
11,276
84ea489cdf4e438082226f2b97aaf4fdfaeeabcb
class Heap: def __init__(self): self.storage = [] def insert(self, value): index = len(self.storage) self.storage.append(value) self._bubble_up(index) def delete(self): deleted = self.storage.pop(0) if self.storage: temp = self.storage.pop() ...
11,277
3eea637fb55e6cd2269eb3e57ae4de059d9bc86c
import itertools from utils import load_embedding, Results, Metrics, save_model, load_model, load_directional_supervision, load_element_pairs, load_pair_features from model import PointNet, PairNet, TripletNet, PairNetWithPairFeatures, TripletNetWithPairFeatures from trainer import train_triplet_epoch from datasets imp...
11,278
643808c52ee34983b54abc4ee0fde4658a65ec73
credit = ' ' q =0 g=10 h=9 i=8 j=7 k=6 l=5 m='fail' def jac(o): if sub == 's' : return g*3 elif sub == 'a' : return h*3 elif sub == 'b': return i*3 elif sub == 'c': return j*3 elif sub == 'd': return k*3 elif sub == 'e': return l*3 elif sub =...
11,279
1db9d3b5d0bac9bb8a2d0068dcb2e92ec48513e4
import asyncio import aiohttp import mock import pytest from bravado_asyncio.definitions import AsyncioResponse from bravado_asyncio.response_adapter import AioHTTPResponseAdapter from bravado_asyncio.response_adapter import AsyncioHTTPResponseAdapter @pytest.fixture(params=(AioHTTPResponseAdapter, AsyncioHTTPRespo...
11,280
f3fd97abe38d17c525b4d59967ab73ccb1944e91
""" Client is resilient to enum and oneOf deserialization errors """ from datadog_api_client import ApiClient, Configuration from datadog_api_client.v1.api.synthetics_api import SyntheticsApi configuration = Configuration() with ApiClient(configuration) as api_client: api_instance = SyntheticsApi(api_client) ...
11,281
d53397e386c4f16dfd9ef2474be7178bbdcd2be8
# coding:utf-8 # This file is part of Alkemiems. # # Alkemiems is free software: you can redistribute it and/or modify # it under the terms of the MIT License. __author__ = 'Guanjie Wang' __version__ = 1.0 __maintainer__ = 'Guanjie Wang' __email__ = "gjwang@buaa.edu.cn" __date__ = '2021/06/10 16:39:3...
11,282
06cfd0a3efb236ab9ca8e7f42d715e8118d11a7a
import pandas as pd import numpy as np from mining_tools import my_tools from testimbalance import abalone_input from imbalance_tools import handle_imbalance from create_dendogram import my_dendogram #Check the class abalone_input which is used to take input from the data-set manually ab=abalone_input() x=ab....
11,283
e17bde4f0dd144bf38ad9f87678ec7fe18d2e29c
import pymysql.cursors import time # Connect to the database connection = pymysql.connect(host='localhost', user='root', password='1234', db='LJ', charset='utf8mb4', cursorcla...
11,284
0ee2ff418a7a27635bdbf90b9f3c5650263f7135
######################################################################### #-*- coding:utf-8 -*- # File Name: find_max_crossing_sub_array.py # Author: buptxiaomiao # mail: buptxiaomiao@outlook.com # Created Time: 2016年03月25日 星期五 20时13分35秒 ######################################################################### #!/usr/b...
11,285
73660ee6ef6b00414c9b58104533b8cb37db331f
# -*- coding: utf-8 -*- """ Created on Wed Mar 22 15:09:19 2017 @author: admin """ import re ####### def searching(text): #text = text.lower for i in range(len(text)): pattern = re.compile(r'192.\d{0,3}.\d{0,3}.\d{0,3}') result = pattern.findall(text[i]) searchForResult = pattern.sea...
11,286
2fc74a273869b594ceaead48ded835bbaa0cc4d0
import sqlite3 import os import sys def main(args): inputfile = args[1] databaseexisted = os.path.isfile('moncafe.db') dbcon = sqlite3.connect('moncafe.db') with dbcon: cursor = dbcon.cursor() if not databaseexisted: # initiating Employees table c...
11,287
e3caf7bc637bc1d5a6b4902b97a2d2ef3cc03ed2
import numpy as np from .Gateway import PacketRecord class PropagationModel: # log distance path loss model (or log normal shadowing) def __init__(self, gamma=2.32, d0=1000.0, std=0.5, Lpld0=128.95, GL=0): self.gamma = gamma self.d0 = d0 self.std = std if self.std < 0: ...
11,288
858e6c3d3021f159ebdec2743390cffb03f74ebb
#!/usr/bin/env python3 import sys #Define a function to calculate the insurance def calc_insurance(salary): return salary*(0.08+0.02+0.005+0.06) #Define a function to calculates the tax def calc_tax(salary): pay = salary - calc_insurance(salary) - 3500 if pay <= 0: tax = 0 elif pay > 0 and pa...
11,289
888e31a734c58dd1e432daae810884d099b27c3f
from Gerrit_Extractor.Gerrit_Connection_Setup import Connection_Setup from Gerrit_Extractor.Gerrit_Queries import Gerrit_Queries from Utilities.Log_Progessbar import show_progress class ReviewExtractor: def __init__(self, url, username,password): self.url = url self.username = username...
11,290
43892bf0bf3759ed3cedcc5283678efe76d6612a
#importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np from scipy import stats #reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image), 'with dimensions:', i...
11,291
0e6efc5a7a1c7aff6ef18406606165a7cfa387ff
# Generated by Django 3.1.3 on 2020-12-13 17:45 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_mri', '0013_auto_20201125_1858'), ] operations = [ migrations.CreateModel( name='IrbAppr...
11,292
0b9a4c81ce53465026912915e49d759833f0e91f
#!/usr/bin/env python3 # # SPDX-License-Identifier: BSD-3-Clause # Copyright 2021, Intel Corporation # # # Figure.py -- generate figure-related products (EXPERIMENTAL) # import matplotlib.pyplot as plt import os.path from textwrap import wrap from .common import * from .flat import * from .Benchmark import * class ...
11,293
9d99b6fc20d439b421fa1886e17e6290d0cbdfca
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ class for the C code generation author: Rinse Wester """ from csdfgraph import * class CCodeGen(object): """docstring for CCodeGen""" def __init__(self, arg): super(CCodeGen, self).__init__() self.arg = arg def generateCode(graph, targe...
11,294
17027998e242efc40db22e73fd843eb44df92cf8
import os import re result = [] for root, dirs, files in os.walk('.'): for filename in files: if 'rst' == filename.split('.')[-1]: result.append(os.path.join(root, filename)) if 'md' == filename.split('.')[-1]: result.append(os.path.join(root, filename)) def extractImages(...
11,295
7954eab0dae80c0e332af58d12862e188890e079
from apis.v1.models.blacklist import Blacklist from apis.v1.models.business import BusinessModel from apis.v1.models.review import ReviewModel from apis.v1.models.user import User class Database: """ class that defines how a database behaves""" database = dict() max_ids = dict() def __init__(self):...
11,296
d6c085174b2ab142e81ccdb1dcce3dd82212deaa
# def CountPair(L,R): # x=(R-L+1) # print(x//2) # if __name__=='__main__': # L,R=1,10 # CountPair(L,R) import math #lambda c:[i for i in range(c)if math.gcd(c,i)<2] # n=int(input()) # l=set() # for i in range(2,n+1): # for j in range(i+1,n+1): # a=set() # if math.gcd(i,j)<2: # ...
11,297
260e92376920b19bf41af7b8c68289ad41798450
# -*- coding: utf-8 -*- """ Created on Sat Apr 20 23:09:48 2019 @author: My Pc """ from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier def knn(dataset,comments,views,languages): #split dataset r_fb=[] #neg_descriptors = {"Confusing", "Unc...
11,298
f55d887128fda6f2ad3180fe79c3c54d9648d3e4
# generated from rosidl_generator_py/resource/_idl.py.em # with input from turtlesim:action/RotateAbsolute.idl # generated code does not contain a copyright notice # Import statements for member types import rosidl_parser.definition # noqa: E402, I100 class Metaclass_RotateAbsolute_Goal(type): """Metaclass of...
11,299
d5d3e00478671caa166eeaadafe6688dd18b9e5c
import unittest import mock import sublime import ctypes sublime.packagesPath = mock.Mock() sublime.packagesPath.return_value = "XXX" import sublimeplugin import executepscommand class SimpleTestCase(unittest.TestCase): def test_regionsToPoShArray(self): view = mock.Mock() rgs = [...