text
stringlengths
8
6.05M
import os import sys import shutil import py2exe import argparse import subprocess import compileall from distutils.core import setup from zipfile import ZipFile parser = argparse.ArgumentParser(description='Emmaus House Food Pantry Setup') parser.add_argument('-c', '--clean', action='store_true', ...
import spidev import time spi = spidev.SpiDev() spi.open(0,0) spi.max_speed_hz=16000000 #16Mhz #spi.max_speed_hz=32000000 #32Mhz while True: #resp = spi.xfer2( [0x80, 0xFF] ) resp = spi.xfer2( [0xFF] ) print resp #print "r2"+resp[1] time.sleep(1)
import sys import argparse from misc.Logger import logger from core.base import base from misc import Misc class env(base): def __init__(self, global_options=None): self.global_options = global_options logger.info('Env module entry endpoint') self.cli = Misc.cli_argument_parse() def ...
import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm def draw(x, y, Edges): plt.scatter(x, y) for edge in Edges: plt.plot([x[edge[0]], x[edge[1]]], [y[edge[0]], y[edge[1]]], 'k-') plt.show() def drawRegret(x, y, Edges): colors = cm.rainbow(np.linspace(0, 1, len(Edg...
from pytrends.pyGTrends import pyGTrends import time from random import randint google_username = "an_email@gmail.com" google_password = "password" path = "" # connect to Google connector = pyGTrends(google_username, google_password) # make request connector.request_report("Pizza") # wait a random amount of time be...
from django.db import models from recurrence.fields import RecurrenceField class Course(models.Model): title = models.CharField(max_length=100) schedule = RecurrenceField()
from AlgebraicDataType import ADT def nt_to_tuple(nt): return tuple((getattr(nt, f) for f in nt.__class__._fields)) class PatternMatchBind(object): def __init__(self, name): self.name = name class PatternMatchListBind(object): def __init__(self, head, tail): self.head = head se...
from time import time def my_dec(func): def wrapper(*args, **kwargs): t1 = time() res = func(*args, **kwargs) t2 = time() t3 = t2 - t1 print(f'It took {t3} seconds') return res return wrapper @my_dec def my_own_range(num, start=0): new_list = [...
import numpy as np class ColorPalette: def __init__(self, numColors): np.random.seed(1) self.colorMap = np.array([[255, 0, 0], [50, 150, 0], [0, 0, 255], [80, 128, 255], ...
from django.http import HttpResponse import simplejson import logging from v1_meta import V1Meta from datetime import datetime import xml.etree.cElementTree as ET from defects.v1defect import V1Defect from django.shortcuts import render # Create your views here. def GetDefectsNumber(request): t1 = datetime.now() ...
import matplotlib.pyplot as pl import numpy as np f = open('angular_data.txt','r') str = f.read() data = str.split(); desired = [] for i in range(len(data)-1): desired.append(data[0]) feedback = data[1:len(data)] t = np.arange(0,len(feedback),1) xlimit = len(feedback)-1 ylimit = int(max(data))+1000 pl.plot(t,fe...
n = int(input()) t = [1,2] for i in range(2,n+1,1): res = t[i - 1] + t[i-2] t.append(res) print(t[n-1])
import csv data = [[1, "a", 1.1] # 리스트를 요소로 포함하는 리스트 생성 [2, "b", 1.2], [3, "c", 1.3]] with open("output.csv", "w") as f: wr = csv.writer(f) # csv 파일에 저장 for row in data: wr.writerow(row
import numpy as np import cv2 #이미지 Contour : 같은 값을 가진 곳을 연결한 선 #이미지에서 Contour를 찾기 전에 threshold나 Canny edge detection을 적용하는 것이 좋다. #Contour를 찾고자 하는 대상은 흰색으로, 배경은 검정색으로 변경해야함 def contour(): img = cv2.imread('images/globe.jpg') imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thr = cv2.threshold(imgray, ...
import socket clisock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) clisock.connect( ('', 8000) ) clisock.send("Hi I am the client\n") print clisock.recv(100) clisock.close()
# %% from myApp.models import Grades.Students, Grades from django.utils import timezone from datatime import * # %%
import sklearn.linear_model from sklearn import svm import numpy as np class SVM: def __init__(self,C=1.0,kernel='linear'): self.svm = svm.SVC(C,kernel) def learn(self,X,T): self.svm.fit(X,T) def predict(self,X,T): count = 0 presission = [0,0,0,0,0] recall = [0,0,0...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys, operator, math from sys import argv with open(argv[1], 'r') as f: with open('scores.txt','w') as fScores: for line in f: wordScore = line.split() score = wordScore[1] fScores.write(score + ' ')
input_string = input() dom = input_string.index(".") print(input_string[dom+1:])
import numpy as np import matplotlib.pyplot as plt from src.shaft_secant_piles import plot_cylinder_2points, set_axis_equal_3d def get_parameters_wall_secant_piles(D, a, L, H_drilling_platform, v=0.75): """ Gets parameters for secant piled wall D: pile diameter [m] a: C/C pile spacing b/w two neighboring p...
#coding:utf-8 def script(s, player=None): from NaoQuest.quest import Quest from NaoCreator.setting import Setting import NaoCreator.Tool.speech_move as SM if not player: Setting.error("Error in execution of post_script of objective \"ChoixService\": ...
import unittest from neo.rawio.winwcprawio import WinWcpRawIO from neo.test.rawiotest.common_rawio_test import BaseTestRawIO class TestWinWcpRawIO(BaseTestRawIO, unittest.TestCase, ): rawioclass = WinWcpRawIO entities_to_test = ['File_winwcp_1.wcp'] files_to_download = entities_to_test if __name__ == "...
import click import torch from models.rnn_attention_s2s import RnnAttentionS2S from utils import prepareData @click.command(help="train env_name exp_dir data_path") @click.option("-d","--data-path", default="data", type=str) @click.option("-a", "--architecture", default="rnn_attention_s2s", type=str) @click.option("-n...
import sys sys.path.append('../500_common') import lib_curation import lib_ss import time from bs4 import BeautifulSoup #-------------- # soup = lib_ss.main("/Users/nakamurasatoru/git/d_genji/genji_curation/src/500_common/Chrome11", "Profile 1") soup = BeautifulSoup(open("data/result.html"), "lxml") tr_list = soup.fi...
import unittest from katas.kyu_7.double_char import double_char class DoubleCharTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(double_char('String'), 'SSttrriinngg') def test_equals_2(self): self.assertEqual(double_char('Hello World'), 'HHeelllloo WWoorrlldd') def...
import os import yaml def loadyamlfile(yamlfile): configfilelist = [] with open(yamlfile, encoding='utf-8') as f: y = yaml.load_all(f) for data in y: configfilelist.append(data) return configfilelist def getnessussearchyaml():# yamlfile里面放配置文件 yamllist = [] dirpath...
import mysql.connector from mysql.connector import Error from logger import * from traceback_info import * import sys ERR_1 = 1 ERR_2 = 2 ERR_FATAL = 3 class DB_Session_MySQL: def __init__(self, username, password, db_id): logger.debug( "DB_Session_MySQL::__init__()" ) self.username_ = username ...
#coding:utf-8 PIC_CODE_EXPIRES_SECONDS = 180 SMS_CODE_EXPIRES_SECONDS = 300 SESSION_EXPIRES_SECONDS = 86400 QINIU_URL_PREFIX = "http://olymmyzny.bkt.clouddn.com/" QINIU_URL_SUFFIX = "?imageMogr2/auto-orient/thumbnail/x220/blur/1x0/quality/75|imageslim" REDIS_AREA_INFO_EXPIRES_SECONDES = 86400 REDIS_HOUSE_INFO_EXPIRES_...
"""API v2 tests.""" from django.urls import reverse from modoboa.admin import factories as admin_factories from modoboa.admin import models as admin_models from modoboa.dnstools import factories from modoboa.lib.tests import ModoAPITestCase class DNSViewSetTestCase(ModoAPITestCase): @classmethod def setUpT...
from common.run_method import RunMethod import allure @allure.step("在线诊断/条件获取接口") def admission_condition_post(params=None, body=None, header=None, return_json=True, **kwargs): ''' :param: url地址后面的参数 :body: 请求体 :return_json: 是否返回json格式的响应(默认是) :header: 请求的header :host: 请求的环境 :return: 默认js...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('myapp', '0003_blog_first_name'), ] operations = [ migrations.AlterModelOptions( name='category', opt...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import cross_val_score from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.neighbor...
import pyaudio import wave import uuid import sounddevice as sd import json import numpy as np #remove import paho.mqtt.client as mqtt class LiveRecorder: def __init__(self, mqtt_client): self.mqtt_client = mqtt_client self.recording = False self.p = pyaudio.PyAudio() self.chunk = ...
def allZeros(occ): for key,val in occ.items(): if(val > 0): return False return True n=int(input()) radius = list(map(long,input().split(' '))) occ = dict() for i in range(n): if radius[i] in occ: occ[i] += 1 else: occ[i] = 1 total = 0 while(not allZeros(occ)): # decreament all occ by one for key,c...
#!/usr/bin/env python3 import argparse import pathlib import sys import time import dreamtests try: import dreamtests except: sys.path.append(pathlib.Path(__file__).parent.absolute()) import dreamtests try: import DREAM except ImportError: sys.path.append(str((pathlib.Path(__file__).parent / '.....
def solution(arr): answer = arr[0] for i in range(1, len(arr)): for j in range(max(answer, arr[i]), answer * arr[i] + 1): if j%answer == 0 and j%arr[i] == 0: answer = j break return answer
import unittest import ctypes from test.util import ClangTest '''Test if pointers are correctly generated in structures for different target archictecture. ''' class Pointer(ClangTest): #@unittest.skip('') def test_x32_pointer(self): flags = ['-target', 'i386-linux'] self.convert('''typedef...
# api/views.py from django.http import HttpResponse from rest_framework import status from rest_framework import viewsets from rest_framework import permissions from rest_framework.views import APIView from rest_framework.response import Response import book.barcode as bc #import from Django Project from .serializers ...
#!/usr/bin/python3 from BWCommon import * from BWControl import * import wx import sys import getopt import os import ctypes import wx.py as py osp = 'linux' if sys.platform.startswith("win"): osp = 'win' def main(): if not os.access('db', F_OK): os.mkdir('db') app = wx.App(False) ...
import re from helper import * def parseHostsFile(filename): lines = open(filename).readlines() category = 0 # 0=none/1=servers/2=clients servers = [] clients = [] for line in lines: # Ignore Comment lines if line[0] == '#': continue line = line.strip() ...
def main(): print("This program changes the names in a file to all capital letters") infileName = input("What files are the names in? ") outfileName = input("Place names in this file: ") infileName = open(infileName, "r") outfileName = open(outfileName,"w") for line in infileName: line...
def reverse(times): c=a.readline().split() d=[c[i] for i in range(len(c)-1,-1,-1)] b.write("Case #{}: ".format(times+1)) for item in d: b.write("{} ".format(item)) b.write("\n") if __name__ == '__main__': a=open('in.txt','r'); b=open('out.txt','w') for time in xrange(0,int(a.read...
import re import unittest from katas.kyu_5.mod4_regex import Mod class Mod4RegexTestCase(unittest.TestCase): """ assertRegexpMatches doesn't seem to work properly for the tests since Mod.mod4 is a compiled regex object already, not just a string. To match the tests used on the Codewars kata, I used asser...
#create feature based on WN Domain dataset #WordNet Domain dataset; two datafile, one for WN1.6, one for WN2.0 #Snow didn't mention which one they use, but I use WN1.6, since I mapped 2.1 to 1.6 #Snow created two features, but I only created the first one, since I was not sure about #the second one. #- "wn-domains-2.0-...
def main(): print ("Pig latin game.") print("") name = raw_input('Pleae enter your name: ') print 'Hello,', name, '! Welcome to pig latin game.' print("") vowels = ('a', 'e', 'i', 'o', 'u','A', 'E', 'I', 'O', 'U' ) with_vowels = "yay" without_vowels = "ay" end = "Q", "q", "Quit", "quit" word = "" while (w...
class Node: def __init__(self, key): self.key = key self.child = dict() self.count_leaf = 0 # 파생 단어 개수(leaf 노드 개수) class Trie: def __init__(self): self.head = Node(None) self.word_count = 0 def insert(self, word): curr = self.head ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import random origin = [0, 0] # 设定原点[0, 0] def create(pos=origin): def move(direction, step): # new_x = pos[0] + direction[0]*step # new_y = pos[1] + direction[1]*step # pos = [new_x, new_y] 这种赋值的方式会报错 pos[0] += direction[0] * step ...
# models.py from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=False, created=Fa...
from functools import reduce import operator def max_product(lst, n_largest_elements): return reduce(operator.mul, sorted(lst)[-n_largest_elements:]) ''' Introduction and Warm-up (Highly recommended) Playing With Lists/Arrays Series Task Given an array/list [] of integers , Find the product of the k maximal numb...
class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: result = ListNode(0) dummy = result while list1 and list2: if list1.val < list2.val: dummy.next = list1 list1 = list1.next ...
''' Log generation simulation with different durations and rates. ''' import os import time import random from time import sleep from datetime import datetime import logging log_format = '%(asctime)s %(levelname)s %(message)s' logging.basicConfig(format=log_format, level=logging.INFO) class LogGenerator: ''' ...
# -*- coding: utf-8 -*- from app.models import Result, Season, Tournament from app.tests import dbfixture, ResultData, TournamentData from app.tests.models import ModelTestCase from web import config class TestResult(ModelTestCase): def setUp(self): super(TestResult, self).setUp...
from __future__ import print_function, unicode_literals import re import os import sys import string import argparse import subprocess from . import __version__, utils, results, bundles, testenv, formatters class Unsupported(Exception): pass class ProcessFailed(Exception): pass class UnexpectedOutput(Ex...
# My Original Code # def replace_exclamation(s): # vowels = ('a','e','i','o','u') # for i in s: # if i.lower() in vowels: # s = s.replace(i, '!') # return s #Best Practice def replace_exclamation(s): return "".join("!" if i in "aeiouAEIOU" else i for i in s)
import gspread from oauth2client.service_account import ServiceAccountCredentials # use creds to create a client to interact with the Google Drive API scope = ['https://spreadsheets.google.com/feeds' + ' ' +'https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name('clien...
# coding:utf-8 def script(s, player=None): from NaoQuest.objective import Objective from NaoCreator.setting import Setting from NaoCreator.Tool.speech_move import speech_and_move if not player: Setting.error("Error in execution of post_script of objective \"q1\": player is None") retur...
import tensorflow as tf from tensorflow import keras from tensorflow.keras import backend from tensorflow.keras import layers import pandas as pd def model(embedding_size, field_vocab_size=[], hidden_units=[4,4,4], dropout=0.5): F = len(field_vocab_size) # prepare embeddings inputs = [] embed_list = [...
from django.shortcuts import render def code(request): context = {"code": request.session['user_id']} return render(request, "turk/code.html", context)
from src.mongo import Mongo from src.etl.aggregate_card_deck_occurrences.card_deck_occurrence_aggregator import CardDeckOccurrenceAggregator def handler(event=None, context=None): mongo = Mongo() CardDeckOccurrenceAggregator(mongo).run() if __name__ == '__main__': handler()
from .gcn import GCN from .sgc import SGC from .gat import GAT
# Generated by Django 2.1.3 on 2019-01-19 19:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('student', '0001_initial'), ] operations = [ migrations.CreateModel( name='DatesAvailable', ...
from django.conf.urls import patterns, include, url from apps.main.views import IndexView, NewsView, ArticleView, NewsinView, ArticleinView, ContactsView, SearchView """ autocomplete_light.autodiscover() BEFORE admin.autodiscover()""" import autocomplete_light autocomplete_light.autodiscover() from django.con...
TEST = 'woo' PATH = 5
from django.shortcuts import render from .models import ServicesData,FeedbackData,EnquiryData from .forms import FeedbackForm,EnquiryForm from django.http.response import HttpResponse import datetime as dt date1 = dt.datetime.now() def home_view (request): return render(request,'durgasoft_home.html') def services...
from abc import ABC, abstractmethod import torch from torch import nn, Tensor from torch.nn.modules.loss import _Loss from parseridge.utils.logger import LoggerMixin class Loss(ABC, LoggerMixin): @abstractmethod def __call__( self, pred_transitions: Tensor, pred_relations: Tensor, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 9 10:14:20 2020 @author: ritambasu """ #writing the code: import numpy as np a = np.array([[1,0.67,0.33],[0.45,1,0.55],[0.67,0.33,1]]) b = np.array([2,2,2]) x = np.linalg.solve(a,b) true_solved_solution = np.array([1.0,1.0,1.0]) print (x) #checking...
from decoder_29628792 import Decoder from character_29628792 import CharacterAnalyser from word_29628792 import WordAnalyser from sentence_29628792 import SentenceAnalyser def get_input(): encoded = input("Enter a sequence of morse code: ") if encoded.count("***") == 0 : # To ensure every input has at least o...
import json embassy = {} i = 0 # change vary on len of dict with open('mood.json') as data: data = json.load(data) #for i in data['embassies']: loop thru every country email = data['embassies'][i]['email'] whom = data['embassies'][i]['title'] print(whom) print(email) if email and whom: ...
import unittest from katas.kyu_8.jennys_secret_msg import greet class GreetTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(greet('James'), 'Hello, James!') def test_equals_2(self): self.assertEqual(greet('Johnny'), 'Hello, my love!')
import scrapy class QuotesSpider(scrapy.Spider): name = "a" def start_requests(self): urls = [ 'https://sh.lianjia.com/ershoufang/pudong/' ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): for a in res...
from django.urls import path from quest import views urlpatterns = [ path('1',views.V1,name ='inizio'), path('2',views.ProvaView,name ='login_utenti' ), # path('3',), path('4',views.RegistrationView,name ='registrazione_utenti'), path('5...
while True: try: x = list(map(int,input())) except: break for i in range(10,1,-1): for n in range(1,i): x[n-1] = (x[n-1] + x[n]) % 10 print(x[0])
import unittest import copy import json from pprint import pprint from manage_notes_annotation import load_task_data, manage_notes_annotation TASK_ADD_NO_NOTES = { "uuid": "test-uuid", } TASK_ADD_WITH_NOTES = { "uuid": "test-uuid", "notes": "test notes", } NOTE_ANNOTATION_NO_NOTES_BEFORE = { "annotations": ...
import sys import collections if len(sys.argv) == 1: print('Code example \n') print('... \n') class Molecule: def __init__(self, structure1, filds1): self.structure1 = [] self.filds1 = collections.OrderedDict() filename2 = sys.argv[1] # small sdf idnumber_small = sys.argv[2] # idnumber ...
from spack import * from glob import glob from string import Template import re import fnmatch import shutil from spack.util.executable import Executable import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import relrelink class CmsswScram(Package): """CMSSW bu...
import numpy as np import json import os from mea import auxfn from mea.model.io_triangle import IOTriangle as green from mea.model.triangle import Triangle as Model from mea.transport import sigmadc from scipy.integrate import simps cwd = os.getcwd() with open("statsparams0.json") as fin: params = json.load(f...
s = float(input()) if s <= 400: p = '15 %' r = 0.15 * s s += r elif 400 < s <= 800: p = '12 %' r = 0.12 * s s += r elif 800 < s <= 1200: p = '10 %' r = 0.10 * s s += r elif 1200 < s <= 2000: p = '7 %' r = 0.07 * s s += r else: p = '4 %' r = 0.04 * s s += r print('Novo salario: {:.2f}\nReajuste ganho:...
def workerStrike(): print("Workers are striking and half your resources have been stealing") def factoryFire(): print("Your factory is on fire") def worldWar(): print("The world falls into total war") def theGreatDepression(): print("The great Depression") def theSnap(): print("Snaps half of your re...
import subprocess file = subprocess.Popen("C:\\Users\\ikira\\AppData\\Local\\WhatsApp\\WhatsApp.exe")
import os from abc import ABC, abstractmethod import numpy as np from scipy import sparse as sp from scipy.sparse.linalg.eigen.arpack import eigsh from app.utils.constant import GCN, NETWORK, LABEL, FEATURE,SYMMETRIC, GCN_POLY from app.utils.util import invert_dict, map_set_to_khot_vector, map_list_to_floats class ...
print(200000) for i in range(200000): print('a', end='')
#!/bin/python3 from __future__ import print_function import sys from operator import add from pyspark.sql import SparkSession if __name__ == "__main__": if len(sys.argv) < 3: print("Usage: zad6 <file> <col_name> [<col_name_2>...<col_name_n.]", file=sys.stderr) exit(-1) spark = SparkSession\ ...
from django.shortcuts import render # Create your views here. def homeview(request): question="Hello" data={ 'quest':question, } return render(request,"index.html",data)
import random import math import turtle import copy from functools import * def generate_map_point(x_range, y_range, loc): #generates a random point #print("generating location point: " + str(loc)) return (random.randint(-(x_range), x_range), random.randint(-(y_range), y_range)) def generate_map_poi...
def update_dictionary(d, key, value): if d.get(key) is None: if d.get(2 * key) is None: d[2 * key] = [value] else: d[2 * key].append(value) else: d.get(key).append(value) d = {} print(update_dictionary(d, 1, -1)) print(d) update_dictionary(d, 2, -2) print(d) upd...
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python ######################################################################################### # # # hrc_dose_plot_exposure_stat.py: plotting trendings of avg, mi...
from __future__ import annotations from rubicon_ml.domain.artifact import Artifact from rubicon_ml.domain.dataframe import Dataframe from rubicon_ml.domain.experiment import Experiment from rubicon_ml.domain.feature import Feature from rubicon_ml.domain.metric import Metric from rubicon_ml.domain.parameter import Para...
from rest_framework.serializers import Serializer from .models import Employee,EmployeeSerializer from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from rest_framework.authentication import BasicAuthentication,SessionAuthentication from rest_framework.permissions import IsAuthent...
""" Created by hzwangjian1 on 2017-07-25 """ import json import os import traceback import pymysql from ddzj.util import db from alexutil import configutil from alexutil import dateutil from alexutil import dbutil from alexutil import logutil config_path = os.path.join(os.getcwd(), "config") log_path = os.path.join...
# Uma empresa vende o mesmo produto para quatro diferentes estados. Cada estado possui uma taxa de imposto sobre o produto (MG 7%; SP %12; RJ 15%; MS 8%). # Faça um programa em que o usuário entre com o valor e o estado de destino do produto e o programa retorne o preço final do produto acrescido do imposto do estado ...
#http://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html while True: try: num = int(input ("Introduzca un número entero: ")) divisor = int(input ("Introduzca un divisor: ")) break except ValueError: print("Eso no parecen números enteros ¬¬ ") if (num%2 == 0): ...
#!/usr/bin/python26 import sys import MySQLdb CONFIG_PATH = '/scripts' sys.path.append(CONFIG_PATH) # explictly state what is used from TARDIS codebase, no ``import *`` from db_queries import (AUDIT_SELECT, AUDIT_UPDATE_STATUS, QUERY_ALL, QUERY_DATA, QUERY_NO_PROXY_DATA, QUERY_PROXY) from con...
import json from helpers import _clear,_setTitle,_printText,_readFile,_getCurrentTime,_getRandomUserAgent,_getRandomProxy,colors from threading import Thread,active_count, current_thread from time import sleep from datetime import datetime import requests class Main: def __init__(self) -> None: _setTitle('...
import logging from log import log import submodule # this is a standard method for creating a logging object LOG = logging.getLogger(__name__) if __name__ == '__main__': # we set up the logging configuration # additionally, the logging.yaml has a console handler, so all logs will be emitted to # stdout ...
import os import sys def setup(): global fileHandle, fileData filename = input("Enter an input file name: ") exists = os.path.isfile("./%s" % filename) notEmpty = os.path.getsize("./%s" % filename) > 0 if exists and notEmpty: fileHandle = open ("./%s" % filename, "r") else: pr...
import cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob from keras.utils import np_utils from sklearn.datasets import load_files # 加载数据集函数 def load_dataset(path): data = load_files(path) dog_files = np.array(data['filenames']) dog_targets = np_utils.to_categorical(np.array(data...
# Generated by Django 1.10.5 on 2017-02-15 12:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('admin', '0009_auto_20170215_0948'), ] operations = [ migrations.AddField( model_name='domain', name='quota', ...
import os import sys import glob import cv2 import numpy as np import argparse from timeit import default_timer as timer ''' Usage : ./db_indexing.py -d "database_name" Example : ./db_indexing.py -d "base1" ''' ######## Program parameters parser = argparse.ArgumentParser() ## Database name pa...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ This script is a simplified version of the training script in detectron2/tools. """ import os import random import numpy as np import torch import time import math import logging from collections import def...
from rest_framework import serializers from frontend.models import Frontend class FrontendSerializer(serializers.ModelSerializer): class Meta: model = Frontend fields = ('title' , 'email','message') # fields = '__all__'