text
stringlengths
8
6.05M
import argparse, glob, sys, json, ast, copy import random import tensorflow as tf from data_provider import generate_data from lstm_model import LSTM_model import numpy as np parser = argparse.ArgumentParser(prog="yikes_lolintator", description="Send a sample text file to the yikes lol...
#! /usr/bin/python3 import sys import os sys.path.insert(0, os.path.abspath('../models')) import numpy as np import matplotlib.pyplot as plt import sys from LIF import * from spike_train import plot_spike_trains # Sinusoidal input def I_sin(f): def I(t): return 1 + np.sin(2*np.pi*f*t) return I #1 def sti...
import time x=17 n=int(input("Please enter the number you want to subtract with 17 :")) if n>x: absol_diff = -(n-x) result=2*(absol_diff) print("As",n,"is greater than",x,",calculating double to absolute diff ...") time.sleep(1) print("Result is :",result) else: print("As", n, "is smaller than"...
from .user import users from .contact import contacts
# -*- coding: utf-8 -*- from zeam.form.base.markers import NO_VALUE, Marker from zeam.form.base.widgets import FieldWidget from zeam.form.base.widgets import WidgetExtractor from zeam.form.ztk.fields import Field, registerSchemaField from zeam.form.ztk.interfaces import IFormSourceBinder from grokcore import componen...
import logging import os import sys import time from functools import wraps def time_logger(func): """ decorator for logging start and end time of function runs :rtype: """ logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # tries creating a directory named...
import random print("Welcome to CardDraw") deck = input("Please enter (s)tandard or (t)arot:") if deck.lower() == "s": suits = ["Spades", "Hearts", "Clubs", "Diamonds"] ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] my_suit = random.choice(suits) my_rank = random.choice(ra...
from gensim.models import KeyedVectors as Word2Vec import numpy as np from embeddings import embedding_utils from utils import file_utils import os, re import logging DEBUG = False class Model_Constants(object): word2vec = "word2vec" char2vec = "char2vec" private_word2vec = "private_word2vec" elmo =...
from werkzeug.serving import run_simple from flask import Flask,json,request,Response from nfd_vnfm import NFD_VNFM import sys from threading import Thread import time import copy import logging from logging.handlers import RotatingFileHandler logger = logging.getLogger() logger.setLevel(logging.DEBUG) formatter ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param A : head node of linked list # @param B : head node of linked list # @return the head node in the linked list def addTwoNumbers(self, A, B): ...
""" Model objects for the Valkyrie mimic. """ from __future__ import absolute_import, division, unicode_literals import attr from json import dumps from mimic.util.helper import random_hex_generator class AccountContactPermission(object): """ An intersection object representing a certain contact's permissi...
# Docstring (__doc__) is short for documentationstring # A docstring is always written with """ # It's the first string that occurs as a statement in a module, function, class or method definition def double(num): """Function to double the value""" return 2*num
import numpy as np import tensorflow as tf import tensorflow.keras as keras tf.random.set_seed(1) X=np.array([[0,0],[0,1],[1,0],[1,1]]) #0=False, 1=True y=np.array([0,0,0,1]) print(X.shape) model = keras.Sequential([ keras.layers.Dense(4, input_shape=(X.shape[1],)), keras.layers.Dense(8), keras.layers.Den...
#!/usr/bin/env python3 from threading import Thread, Condition ''' 1114. Print in Order https://leetcode.com/problems/print-in-order/ ''' class Foo(object): def __init__(self): self.exec_condition = Condition() self.order = 0 self.first_finish = lambda: self.order == 1 self.second_f...
class Value: """Дескриптор данных, который устанавливает и возвращает значение после вычитания комиссии. """ def __init__(self, amount=0): self.amount = amount def __get__(self, obj, obj_type): return self.amount def __set__(self, obj, value): self.amount = value * ...
# -*- coding: utf-8 -*- #吳驊涓/106111123 #第一題 """ num=int(input("請輸入一個整數:")) if (num % 3 == 0) and (num % 5 == 0): print("%d 是三且五的倍數"%num) elif num % 3 == 0: print("%d 是三的倍數"%num) elif num % 5 == 0: print("%d 是五的倍數"%num) else: print("%d 非三與五的倍數"%num) input() """ num=int(input("請輸入一個整數:")) if (num % 3) ==...
# -*- coding: utf-8 -*- ''' Crea un alumno en la base de datos. cat /tmp/archivo.csv | PYTHONPATH="../../../python/model" python3 importStudents.py ''' from model.connection import connection from model.registry import Registry import sys if __name__ == '__main__': import inject #inject.configure() ...
from big_xo.libs import * class Player: def __init__(self, bot, chat_id, name='Human'): self.name = name self.player_type = None self.game = None self.bot = bot self.chat_id = chat_id def set_type(self, player_type): self.player_type = player_type def set_...
import discord def getIdFromName(server : discord.Server, name : str) -> str: for member in server.members: if member.name == name: return member.id return "" def getDiscriminatorFromName(server : discord.Server, name : str) -> str: for member in server.members: if member.name ...
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print(counter) print(miles) print(name) print("Aum") mystring="Don't worry about spostrophes" print(mystring) hello="hello" world="world" helloworld=hello + " " + world print(hellow...
import txt2hpo, sys import pickle import os class HPO_Class: def __init__(self, _id=[], _name=[], _alt_id=[], _def=[], _comment=[], _synonym=[], _xref=[], _is_a=[],_alt_Hs={}, _chpo=[],_chpo_def=[]): self._id = _id self._name = _name self._alt_id = _alt_id self._def = _def ...
""" from finance import views try: # django 2.0 from django.urls import path except: # django 1.6 from django.conf.urls import url as path urlpatterns = [ path('finance/finance/budgetslist/', views.budgetslist, name='budgetslist'), path('finance/budgetslist/finance/importbudgets/<str:docname>/...
from django.db import models from login.models import NcUser # 공지사항 + 개발로그 게시판 class NoticeDev(models.Model): # primary_key id = models.AutoField(auto_created=True, primary_key=True) # 공지사항 게시판과 개발로그 게시판을 하나의 모델로 하고 board_name으로 구분한다. noticedev_board_name = models.CharField(max_length=32, default='공지사...
# count function def count(str1, str2): set_string1 = set(str1) set_string2 = set(str2) matched_characters = set_string1 & set_string2 print("No. of matching characters are : " + str(len(matched_characters)) ) # Main function def main(): str1 ='3592' # first string str2 ='1572' # s...
class Solution: def calculate(self, s: str) -> int: return self.eval(s,0)[0] def eval(self,s,i): op = '+' res = 0 while i < len(s): char = s[i] if char in ('+','-'): op = char else: val = 0 if c...
#!/usr/bin/env python #-*-coding:utf-8-*- # @File:Segment.py # @Author: Michael.liu # @Date:2019/2/12 # @Desc: NLP Segmentation ToolKit - Hanlp Python Version print("Hello World!") print("this is search & rec")
#!/usr/bin/python from models.base import Base import json import unittest from models.square import Square from models.rectangle import Rectangle import pep8 from os import path class TestCodeFormat(unittest.TestCase): def test_pep8_conformance(self): """Test that we conform to PEP8.""" pep8styl...
from app.utils.constant import GCN_VAE, SUPPORTS, MODE, TRAIN, NORMALISATION_CONSTANT, LOSS, ACCURACY from app.model.aemodel import base_model from app.layer.GC import SparseGC from app.layer.IPD import InnerProductDecoder import tensorflow as tf import numpy as np class Model(base_model.Base_Model): '''Class fo...
from datetime import datetime def timer(func): def wrapper(*args, **kwargs): start = datetime.now() result = func(*args, **kwargs) # result = func(*args, **kwargs) end = datetime.now() print(func.__qualname__, args, "took \t\t", (end-start).total_seconds() * 100...
# -*- coding: UTF-8 -*- import datetime from urllib import request from bs4 import BeautifulSoup if __name__ == "__main__": url = 'https://petitions.whitehouse.gov/' req = request.Request(url) response = request.urlopen(req) html = response.read().decode('utf-8') # 创建Beautiful Soup对象 soup = Be...
# Generated by Django 2.1.3 on 2018-11-06 10:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0017_staff'), ] operations = [ migrations.AddField( model_name='staff', nam...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 3 01:36:01 2018 @author: Iswariya Manivannan """ import os, sys def maze_map_to_tree(maze_map): """Function to create a tree from the map file. The idea is to check for the possible movements from each position on the map and encode it...
# -*- coding: utf-8 -*- import NaoCreator.Tool.wikipediator as w import NaoCreator.Tool.speech_move as sm import NaoCreator.SpeechToText.nao_listen as nl import NaoSensor.outils as o import NaoSensor.plant as p def get_wikipedia_answer(info): """ Permet de faire la recherche sur wikipédia et de donner la pre...
data = [13, 15, 14, 17, 18, 16, 16] d = 2 k = 1 answer = [] del_count = 0 pre_data = 0 for i, da in enumerate(data): if i == 0 : answer.append(da) continue if pre_data == 0: pre_data = da else: if del_count > k: answer.append(pre_data) pre_data =...
# -*- coding: utf-8 -*- # !/usr/bin/env python """ This script computes smatch score between two AMRs. For detailed description of smatch, see http://www.isi.edu/natural-language/amr/smatch-13.pdf """ import sys, json, argparse from fast_smatch import amr from fast_smatch._smatch import get_best_match, compute_f fro...
''' 238. Product of Array Except Self Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Constraint: It's guaranteed that the product of the elements of any prefi...
import unittest from katas.kyu_7.summing_a_numbers_digits import sumDigits class SumDigitsTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(sumDigits(10), 1) def test_equals_2(self): self.assertEqual(sumDigits(99), 18) def test_equals_3(self): self.assertEqual...
import pygame from random import randint import math class Particle(object): gravity_switch = True gravity = (math.pi / 2, 0.5) elastic = 0.8 def __init__(self, coordinate, radius, velocity, thickness=4): self.x, self.y = coordinate self.radius = radius self.mass_density = 100...
from .info import get_alliance_info as get_info
# vim:fenc=utf-8 ff=unix ft=python ts=4 sw=4 sts=4 si et import unittest from bleach_allowlist.bleach_allowlist import ( markdown_tags as allowlist_markdown_tags, markdown_attrs as allowlist_markdown_attrs ) from mkdocssafetext.config import SafeTextPluginConfig class TestSafeTextPlugin(unittest.TestCase): ...
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
# 用戶定义类,数字常量和内置数学工具和扩展,表达式操作符递归阶乘 __author__ = 'bilaisheng' '''  1.类的定义  2.父类,子类定义,以及子类调用父类  3.类的组合使用  4.内置功能 ''' # 类的定义 # class Hotel(object): # # 构造函数 # def __init__(self, room, cf=1.0, br=15): # self.room = room; # self.cf = cf; # self.br = br; # # def calc_all(self, days=1)...
#!/usr/bin/env python """ Find the minimun element in a Python List using recursion. """ def min_element(arr, last): if len(arr) == 1: return last else: if arr[0] < last: new_min = arr[0] else: new_min = last return min_element(arr[1:], new_min) print(mi...
import os import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc # app = dash.Dash( # __name__, # external_stylesheets=[dbc.themes.BOOTSTRAP], # meta_tags=[ # {'name': 'viewport', # 'content': 'width=device-width, initial-scale=1.0'} # ...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json from twisted.enterprise import adbapi from scrapy import log import MySQLdb import MySQLdb.cursors class DoubanP...
from flask import Flask from flask import jsonify from flask import request from flask_pymongo import PyMongo import config import json from bson import ObjectId app = Flask(__name__) app.config["MONGODB_DB"] = "myFirstDatabase" app.config['MONGO_URI'] = 'mongodb+srv://admin:admin@cluster0.og2k6.mongodb.net/myFirst...
import httplib2 from apiclient import errors, discovery from oauth2client import client from apiclient.http import BatchHttpRequest class GmailService(object): def __init__(self, credentialsJson): credentials = client.OAuth2Credentials.from_json(credentialsJson) http_auth = credentials.authorize(h...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_project-skeleton ---------------------------------- Tests for `project-skeleton` module. """ import unittest from project-skeleton import project-skeleton class TestProject-skeleton(unittest.TestCase): def setUp(self): pass def tearDown(self...
# -*- coding: utf-8 -*- import os import subprocess from pieprompt.parts import Part from pieprompt.util import Color from pieprompt.util import colorize from pieprompt.util import run_command def get_git_part(): # TODO: Move this checking logic elsewhere no_git = os.environ.get('PIEPROMPT_NO_GIT', '') no...
from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model from django.utils import timezone # Create your models here. class Message(models.Model): author = models.ForeignKey(User, related_name='author_messages', on_delete=models.CASCADE) content =...
# ***** BEGIN LICENSE BLOCK ***** # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # The Initial Developer of the Original Code is the Mozilla Foundation. # Portions cre...
""" The example returns a JSON response whose content is the same as that in ../resources/personality-v3-expect2.txt """ from __future__ import print_function import json from os.path import join, dirname from watson_developer_cloud import PersonalityInsightsV3 personality_insights = PersonalityInsightsV3( versi...
from flask import Blueprint, jsonify, request root_api = Blueprint("root_api", __name__) @root_api.route("/api/recent") def get_recent_nodes(): # nodes, references = recent_papers_and_references() return jsonify({"nodes": None, "references": None})
def fantasy(): import nflgame x=int(input("What year?: ")) y=int(input("What week?: ")) z=int(input("How many players?: ")) print() if x>=2009: if x<2020: if y>0: if y<=17: games = nflgame.games(x, week=y) players = nf...
import pytest import palindrome # Successful test def test_empty(): assert palindrome.palindrome("") == False, "Empty string failed" # Successful test def test_racecar(): assert palindrome.palindrome("racecar"), "racecar failed" # Failed test def test_Anna(): assert palindrome.palindrome("Anna"), "Anna...
# coding: utf-8 import requests import threading import os import sys import time import datetime lock = threading.Lock() class downloader: # 构造函数 def __init__(self): # 设置url self.url=sys.argv[1] # 设置线程数 self.num=8 # 文件名从url最后取 self.name=self.url.split('/')[-1] ...
import warnings from numbers import Number from typing import Union from phi import math, field from phi.field import CenteredGrid, StaggeredGrid, PointCloud, Field, mask from phi.geom import Box, GridCell, Sphere, union, assert_same_rank from phi.geom import Geometry from phiml.math import Tensor, channel, instance f...
from django.shortcuts import render from django.http import HttpResponse from .tasks import send_email_task # Create your views here. def email_sender(request): send_email_task() return HttpResponse('Wysłane!')
class Profile: pi = 3.14 def __init__(self, theName, myAge): self.name = theName self.age = myAge def growOlder(self): self.age += 1 def greet(self, language): if language=="English": return "Greetings, %s" % self.name else: ...
def new_node_id(node_name, node_counts): uid = node_counts[node_name] node_counts[node_name] += 1 return node_name + '-' + str(uid) def add_node_instance(graph, node, node_counts, regions = None): node_id = new_node_id(node.node_name, node_counts) region_list = frozenset() if regions == None else f...
from errors.CooldownError import CooldownError from errors.ExecutionError import ExecutionError from errors.PermissionError import PermissionError class Command: def __init__(self, parent, script_name, command_key, permission, ...
import cv2 import numpy as np import os nomb = input("Introduzca su nombre: ") DirectoryPath = 'Database/'+str(nomb) os.mkdir(DirectoryPath) input("Presione enter para generar su carpeta de datos") cam = cv2.VideoCapture(0) cascPath = "Cascades/haarcascade_frontalface_default.xml" faceCascade = cv2.Cas...
idc = {}
# This file contains some random but maybe useful stuff import numpy as np from .out_utils import id_mapping def get_fraction(gene_ids, FPKM, ignoreNan=False): """Get the fraction from FPKM""" idx0 = 0 frac = np.zeros(len(FPKM)) for i in range(len(FPKM)+1): if i >= len(FPKM) or gene_ids[idx0] ...
import unittest from tests.login_test import LoginTestCase ltc1 = unittest.TestLoader().loadTestsFromTestCase(LoginTestCase) sanityTestSuite = unittest.TestSuite([ltc1]) unittest.TextTestRunner(verbosity=2).run(sanityTestSuite)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' from functools import wraps from sanic.request import Request from web_backend.nvlserver.module.request_logger.service import create_request_log_element def request_logger(func): """ Login required decorator used in api views. :param fun...
def inint(): return int(input()) def inlist(): return list(map(int,input().split())) count=0 a1=0;b1=0;c=str();num=0 def work(i,m1,n1,carry=0,m='',n=''): global count,a1,b1,num,c #print('index-',i,';c-',c,carry,n,'m1-',m1,'n1-',n1) if i == num+1 : if m1==a1 and n1==b1: if m not i...
# ------------------------------------------------------------------ # imports # ------------------------------------------------------------------ from shared.utils import HMILog from shared.utils import tel_ids, redis_port import threading import time from collections import Counter import redis import json import js...
# coding: utf-8 import os import base64 import uuid import json import tornado.auth import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, options from tornado.web import url from sqlalchemy import create_engine from sqlalchemy.orm import scoped_...
""" Usage: 1. put this file to the directory that you want to use in `path_deploy()` 2. change the app name if needed 3. run this file. """ import os from os import path from tornado import template from pywebio.output import * from pywebio.platform.path_deploy import filename_ok from pywebio.session import * #Chang...
import unittest import os from gmc.conf import settings from gmc.core import handler class TestSettings(unittest.TestCase): def setUp(self): handler.execute_from_command_line(['', 'setting.py'], quiet=True) def test_settings_loader(self): self.assertEqual(settings.DATASET_DIR, '/home/kapil')
#!/usr/bin/env python import socket import subprocess import sys # Ask for input remoteServer = raw_input("Enter a remote host to scan: ") remoteServerIP = socket.gethostbyname(remoteServer) remoteServerEx = socket.gethostbyname_ex(remoteServer) remoteok = True print "-" * 60 print "Please wait, scanning remo...
import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt import math as math # Based on a matplotlib example at: # https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html def plotspiral(x_rot, y_rot, z_rot, scale): mpl.rcParams['legend.fontsize'] = 10 fig...
from elasticsearch import Elasticsearch es = Elasticsearch() # Module to Include the Bulk Indexing Api from elasticsearch import helpers import csv import time host = "localhost" port = 9200 index = "medical" type = "hcpc" filePath = "/home/matrix/ELK/data/hcpc.csv" bulk_size = 500 actions = [] def readCsv(filePa...
# Stephanie Gillow # CS110 # I pledge my honor I have abided by the Stevens honor system. import datetime def checkDate(datestring): try: datetime.datetime.strptime(datestring, '%m/%d/%Y') except ValueError: raise ValueError("Invalid date, or incorrect format.") inputdate = input("Enter the...
from base.recommender import Recommender from tool import qmath from structure.symmetricMatrix import SymmetricMatrix from collections import defaultdict class UserKNN(Recommender): def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'): super(UserKNN, self).__init__(conf,trainingSet,testSet,fold...
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
import numpy as np class ECE: def __init__(self, n_bin, dynamic=False): self.n_bin = n_bin self.dynamic = dynamic if dynamic: self.list = [] self.bin_lowers = np.zeros(n_bin) self.bin_uppers = np.zeros(n_bin) else: bin_boundaries = np.linspace(0, 1, n_bin+1) self.bin_lo...
from pyasn1.type.namedtype import NamedType, NamedTypes, OptionalNamedType, DefaultedNamedType from pyasn1.type.namedval import NamedValues from asn1PERser.classes.data.builtin import * from asn1PERser.classes.types.type import AdditiveNamedTypes from asn1PERser.classes.types.constraint import MIN, MAX, NoConstraint, E...
import cv2 resizeFactor = 0.5 circle_radius = 2 def draw_points(means, image_filename, output_filename, color): orig = cv2.imread(image_filename) resize = cv2.resize(orig, (0, 0), fx=resizeFactor, fy=resizeFactor) for mean in means: x, y = mean[0], mean[1] cv2.circle(resize, (x, y), circl...
def find_indices(N,m): # first find the semi triangle # number in first row is N-2 # ALL INDICES ARE ARRAY STYLE, 0,1,..,M-1 # N is how many actual SNPs the search is going through, so it goes (0,1,2),...,(0,1,N-1) # m is how many triples each thread will be searching. m_orig = m triang...
from sqlalchemy import Column, Integer, String from bitcoin_acks.database.base import Base class PullRequestsLabels(Base): __tablename__ = 'pull_requests_labels' id = Column(Integer, primary_key=True) pull_request_id = Column(String) label_id = Column(String)
list=[10,20,30,40,50] sum=int() for x in list: sum=sum+x print(sum)
l = ["Bob", "Rolf", "Anne"] t = ("Bob", "Rolf", "Anne") # Can't modify a tuple s = {"Bob", "Rolf", "Anne"} # Can't have duplicate elements # Order is not guaranteed l.append("Smith") # t.append("Smith") # Tuples cannot be modified s.add("Smith") s.add("Bob") # Only 1 bob will be printed, curiously, first bob was ...
import numpy as np import os import cv2 import scipy.io as sio import sklearn.metrics.pairwise as pw from scipy.spatial import distance_matrix import matplotlib.pyplot as plt from Cluster import Kmeans, NormCut def displayImageGT (f): path = img_dir + f # get full path...
# -*- coding: utf-8 -*- print '---------------------------------------------------' print 'bu script aeren7318 tarafından yapıldı calanların amk' print 'hiçbir sorumluluk bana ait degil' print '---------------------------------------------------' import urllib2 import sys import threading import random impor...
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.common.action_chains import ActionChains import time #change my name to your username driver_path = "/Users/giannaa...
from sys import argv script, input_file = argv def print_all(f): print f.read() def rewind(f): # moves to new file position in bytes (i.e. 0th byte) # there is a second optional argument which dictates the mode of # offset (the first argument). Default is offset from beginning of file # but if se...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/9/30 14:47 # @Author : Jason # @Site : # @File : xmlparse.py # @Software: PyCharm import xml.etree.ElementTree as ET import sys import os.path class XmlParse: def __init__(self, file_path): self.tree = None self.root = None ...
from optparse import OptionParser from ..util import defines from ..old_extractors import features from ..util import file_handling as fh def main(): # Handle input options and arguments usage = "%prog" parser = OptionParser(usage=usage) parser.add_option('-d', dest='dataset', default='', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # flickrbird.py # # Copyright 2010 Abhinay Omkar <abhiomkar AT gmail DOT com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software ...
import numpy as np import cv2 from matplotlib import pyplot as plt from scipy.spatial import distance as dist def show(imgs, h=8): n = len(imgs) if n == 1: plt.figure(figsize=(h, 6), dpi=80) plt.axis("off") plt.imshow(cv2.cvtColor(imgs[0], cv2.COLOR_BGR2RGB)) return f, axs =...
"""PDF Credentials API v2 views.""" import os from django.utils.translation import gettext as _ from django.http import HttpResponse from rest_framework import permissions from rest_framework.views import APIView from modoboa.admin.models import Domain from modoboa.lib.throttle import UserLesserDdosUser from .seri...
from airflow.contrib.hooks.aws_hook import AwsHook from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class StageToRedshiftOperator(BaseOperator): ui_color = '#f8a5c2' ui_fgcolor = '#000000' template_fields = ("s3...
from __future__ import division, print_function import mock import unittest from smqtk.representation import DataSet class DummyDataSet (DataSet): @classmethod def is_usable(cls): return True def __init__(self): super(DummyDataSet, self).__init__() def __iter__(self): pass ...
from django.contrib import admin from .models import Profiles admin.site.register(Profiles)
from collections import Counter from argparse import ArgumentParser from sys import argv def read_text_from_file(filepath): with open(filepath) as text_file: return text_file.read() def remove_nonalpha_chars(text, ignore_list=[]): filtered_list = [char for char in list(text) if char.isalpha() or cha...
file = "Day7/inputnaomi.txt" from itertools import permutations with open(file,'r') as f: initial_intcode = list(map(int,f.read().split(','))) f.close() def get_param(pos_mode,number,ic): if pos_mode: return ic[number] return number def advance_intcode(inputs,ip,intcode,get_phase=True): i...
import requests # 读取的文件目录 reader_file = "/Users/yanmeng/Downloads/test.txt" # 存放的文件夹路径 output_dictionary = "/Users/yanmeng/Downloads/chenzijuan/" def download(url,index): r = requests.get(url) with open(output_dictionary+str(index)+str(url.split('?')[0].split('/')[-1]), "wb") as code: code.write(r.co...