text
stringlengths
38
1.54M
import random import json from pico2d import * class Astronaut: image = None life_image = None # 거리 환산 PIXEL_PER_METER = (1 / 0.03) # 1 pixel 3 cm # 걷는 속도 RUN_SPEED_KMPH = 25 # Km / Hour RUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.0) RUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0) RUN_...
# -*- coding:utf-8 -*- import sys, socket, json, threading, random from PyQt5.QtWidgets import (QApplication, QWidget, QDesktopWidget, QMessageBox, QPushButton, QTextEdit, QLineEdit, QToolTip, QLabel, QTextEdit, QMessageBox, QProgressDialog, QComboBox, ...
# -*- coding: utf-8 -*- import nltk if __name__ == '__main__': # get NLTK stopwords nltk.download("stopwords") # get VADER lexicon nltk.download('vader_lexicon')
# source: Internet def r(a): i = a.find('0') ~i or exit(a) [m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import * r(argv[1]) # inp: 530070000600195000098000060800060003400803001700020006060000280000419005000080079
from classes.Controller.Scanner_Controller import * from classes.View.Scanner_View import * from classes.Model.Scanner_Model import * class PortscanMain: def __init__(self): self.model = dataObject() self.controller = dataHandler(self.model) self.view = Window(self.controller, self.model) ...
import pickle,os,random class newacc: def __init__(self): self.user="null" self.password="null" self.acctype=0 self.accno=0 self.name="null" self.gender="null" self.income=0 self.email="null" self.dob="null" self.address="nu...
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # # VanyaD - Copyright - Ektanoor <ektanoor@bk.ru> 2012 # # This 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 Foundation in version 2. VanyaD is di...
import numpy as np ### For IMS data # https://github.com/aelias-c/SCD_project/blob/1a5eb5100ee88bf9968b54a7570693c0422f6b1b/SCD_anomaly_calc.py#L92 ALEKSANDRA_SLICE = np.index_exp[158:867] # details from https://nsidc.org/data/g02156#ancillary IMS_24KM_UL_CORNER = (-12126597.0, 12126840.0) # note that this is the co...
#!/usr/bin/env python import operator import StringIO import textwrap import unittest from testmaster import compare_metrics # Sample E2E CSV results OLD_CSV = '''filename,total_duration,c2s_throughput,c2s_duration,s2c_throughput,s2c_duration,latency,error,error_list ubuntu14.04-chrome49-banjo-2016-11-29T140016Z-res...
class Command: def __init__(self, velocity: float, angular_velocity: float) -> None: assert isinstance(velocity, float) assert isinstance(angular_velocity, float) self.__velocity: float = velocity self.__anglular_velocity: float = angular_velocity @property def velocity(self...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-02-23 01:08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses_app', '0002_auto_20180222_2332'), ] operations = [ migrations.AlterFi...
import logging from imp import reload import hashlib class TrustManagerLog: def __init__(self): self.filename= "log/trustmanager.log" def configTrustManagerLog(self,logging_level): reload(logging) logging.basicConfig(filename=self.filename , level= logging_level\ # ,filemode='w' \ ,format='%(asctime)...
# This file is part of ts_scheduler. # # Developed for the Rubin Observatory Telescope and Site Systems. # This product includes software developed by the LSST Project # (https://www.lsst.org). # See the COPYRIGHT file at the top-level directory of this distribution # for details of code ownership. # # This program is ...
#!/usr/bin/env python3 from baseline_np import decode, EXTENSION import os import glob from zipfile import ZipFile import time VALOUTZIP = 'valout.zip' VALOUTDIR = 'valout' def get_files_info_string(): ps = os.listdir('.') non_png = [p for p in ps if '.png' not in p] png = [p for p in ps if '.png' in ...
#!/usr/bin/env python # Test this by entering the search string "election" on a command line like this: # /home/wevote/WeVoteServer/search/query_test_script.py election from elasticsearch import Elasticsearch import sys es = Elasticsearch(["172.31.24.246:9200"], timeout = 120, max_retries = 5, retry_on_timeout = True...
import pyxel import random # o jogo em si class jogo(): def __init__(self): pyxel.init(256,256) self.fruta1 = Entidade('fruta',random.randint(0,255),random.randint(0,255),8) self.criatura1 = Entidade('criatura',100,100,9) self.jogador1 = Entidade('jogador',128,128,3) self.e...
class washer(object): """洗衣机图纸""" def __init__(self,modleName,width,height): """初始化 modleName:型号名称""" self.modleName = modleName self.width = width self.height = height def print_info(self): print(f"洗衣机的型号是{self.modleName},高度是{self.height},宽度是{self.width}") ...
# coding=utf-8 import math import torch from torch.nn.parameter import Parameter from torch.nn.modules.module import Module from torch.nn.modules.utils import _pair from function_copy import conv import torch.nn.functional as F from .errorInsert import insertError,f2Q,Q2f from collections import Counter impor...
from ssg.utils import parse_template_boolean_value def preprocess(data, lang): data["missing_parameter_pass"] = parse_template_boolean_value( data, parameter="missing_parameter_pass", default_value=False) is_default_value = parse_template_boolean_value( data, parameter="is_default_value", def...
import psycopg2 import pandas as pd host_version = "local" #host_version = "trindade" in_file_path = "ts_to_be_inserted.csv" try: conn = psycopg2.connect("dbname='from_unsupervised_to_supervised' user='postgres' host='localhost' password='admin'") conn.autocommit = True except: print "unable to connect to the da...
#==================================================================== # Motor class that remembers parameters for sizing #==================================================================== class motors: def __init__(self, data={}, nseg=0): self.ngroups = 0 self.groups = {} ngrp ...
from perf.model.configuration import Configurations from utility import fab_util class DistributeEnv(Configurations): def __init__(self, config_file, **kwargs): '''@param config_file: configuration file, must be a properties file''' super(DistributeEnv, self).__init__(config_file, **kwargs) ...
import db def proccessDiagnosis(userSymptoms): results = [] for illness in db.illnesses: title = illness['title'] symptoms = illness['symptoms'] # verificar sintomas da doenca com os do usuario, e retornar somente sintomas que coincidem matches = list(set(symptoms) & set(us...
#!/usr/bin/python # Checks whether the given string can be a valid palindrome or not def isvalidpalindrome(s): map = {} for literal in s: if literal not in map: map[literal] = 1 else: map[literal] *= -1 odd = 0 for item in map: if map[item] ==...
# -*- coding: utf-8 -*- # @Author : 杨佳 # @Time : 2020/11/18 15:44 # @File : test_company.py import pytest import time from common.deal_excel import DealExcel from pages.company_page import CompanyPage from common.log import do_log import common.file_contrast as fc # do_excel = DealExcel() # test_data = do_excel.read...
import math as m from scipy import signal import control as c class General_aprox(object): def normalizacion(self): if (self.tipo == "LP"): self.wsn=((self.ws)/(self.wp)) elif (self.tipo == "HP"): self.wsn=((self.wp)/(self.ws)) elif(self.tipo == "BP"): s...
##In Two ways we can check the number is even or odd: """ num=int(input("enter the number:")) number=int(num/2)*2 if number==num: print("its even number",num) else: print("its odd number",num) """ num=int(input("enter the number:")) number=int(num/2)*2 num1=num-number if num1==0: print("its e...
#! /usr/bin/env python2.7 from django.views.generic import TemplateView from django.shortcuts import redirect from django.forms import ModelForm from gifsong.models import gifsong class GifSongForm(ModelForm): class Meta: model = gifsong fields = ['image_url', 'audio_url'] class showgifsong(...
import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt def main(): filename1 = sys.argv[1] filename2 = sys.argv[2] File1CSV = pd.read_csv(filename1, sep=' ', header=None, index_col=1,names=['lang', 'page', 'views', 'bytes']) data1 = File1CSV.sort_values(by=['views'], ascendi...
import array import urllib2 as url2 import urllib as url1 import sys import dropbox #from Selenium import webdriver fileName = sys.argv[1] app_key = 'uqzp24pob7zakxn' app_secret = 's3pdcfy7zhycxcv' access_type = "dropbox" flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret) authorize_url = flow.st...
from django.shortcuts import render # Create your views here. from django.shortcuts import HttpResponse # Create your views here. def home(request): return HttpResponse("hello India - welcome -!! Its jangp webpage")
import os import time import shutil PHOTO_EXT = ("jpg", "jpeg", "png", "psd", "tif") VIDEO_EXT = ("mp4", "avi", "mov") DOCUMENT_EXT = ("pdf", "docx", "doc", "txt") def main(): magic_folder_path = "/Users/derek/Desktop/test" # while not os.path.exists(magic_folder_path): # magic_folder_path = input("P...
import operator from django.shortcuts import render from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication impo...
import numpy as np import matplotlib.pyplot as plt x = np.linspace(-5, 5, 101) #-5부터 5까지 사이를 101등분하기 print(x) y = (1 / np.sqrt(2 * np.pi)) * np.exp(- x ** 2 / 2 ) #평균이 0, 분산이 1일 때 정규분포의 y축 값 print(y) plt.figure(figsize=(10, 6)) # 플롯 사이즈 지정 plt.plot(x, y) plt.xlabel("x") ...
# Uses pretrained VGG16 model as a feature extractor from tensorflow.keras.applications import VGG16 from tensorflow.keras.applications import imagenet_utils from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.preprocessing.image import load_img from sklearn.preprocessing import LabelEn...
# -*- coding: utf-8 -*- """ Created on Tue May 1 20:51:38 2018 @author: Administrator """ # Numpy 构造函数 # numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0) # dtype : 数组所需的数据类型 # copy : 对象是否被复制 # order : 排序方式 # ndmin : 指定返回数组的最小维度 # Numpy 的运算单位 数组 # 数组的算数和逻辑运算 # 傅里叶变换 # 与线性代数有关的操作 ...
# -*- coding: utf-8 -* from __future__ import absolute_import import geocoder import httplib2 import os import re import requests import sys import time from BeautifulSoup import BeautifulSoup from bot.models import Cities, CityPhotos from django.core.management.base import BaseCommand from TelegramBot.settings impor...
from sklearn.ensemble import GradientBoostingClassifier from sklearn.pipeline import Pipeline import pandas as pd import pickle customer_behavior_model = pickle.load(open('/home/cdsw/models/final_model.sav', 'rb')) #Inputs: #recency int64 #history float64 #used_discount int64 #used_bogo ...
import numpy as np import os.path import csv import pandas as pd import nres_comm as nr def stds_addline(types="",fnames="",navgs="",sites="",cameras="",jdates="",flags=""): ''' Reads the standards.csv file, appends a line containing the data in the argument list, sorts the resulting list into increasing ...
values = open('08.in', 'r').read()[:-1] width = 25 height = 6 no_of_layers = len(values) // (width * height) layers = [] for i in range(0, no_of_layers): start = i * width * height end = (i + 1) * width * height layers.append([x for x in values[start:end]]) min_i = 0 for i in range(0, no_of_layers): ...
import torchvision import torch model = torchvision.models.resnet18(pretrained=False) model.fc = torch.nn.Linear(512, 2) model.load_state_dict(torch.load('best_steering_model_xy.pth')) device = torch.device('cuda') model = model.to(device) model = model.eval().half() import torchvision.transforms as transforms impo...
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('index', views.index, name='index'), path('signup', views.register, name='signup'), path('home', views.home, name='home'), path('logout', views.logout, name='logout'), path('update', views...
# Copyright (c) 2014 Mirantis, Inc. # # 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...
import sys import json import re #assert sys.version_info >= (3, 5) # make sure we have Python 3.5+ from pyspark.sql import SparkSession, functions, types spark = SparkSession.builder.appName('example code').getOrCreate() assert spark.version >= '2.3' # make sure we have Spark 2.3+ # sc = spark.sparkContext # add mor...
from django import forms from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class registerform(UserCreationForm): username = forms.CharField(max_length=100, required=True, help_text='', ...
# OOPs concepts / properties # - abstraction # --- ATM --- # -- hiding implementation -- user is not interested at all in process # python -- private public ---- var # var = 10 -- public # _var = 10 --- protected - single underscore # __var = 10 -- private -- strictly protected -- doub...
from django.conf.urls import url from django.contrib import admin from core import views from . import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.index, name="home"), url(r'^admin/', admin.site.urls), url(r'^select/role/', views.select_role, name='select-role'), ...
#encoding UTF-8 #def body <div class="row"> <h1>Accommodations</h1> <p class="left">The wedding ceremony and reception will be at Transmitter Park in Greenpoint, Brooklyn (see: <a href="${ROOT_URL}/map">Map</a>) at 12 noon. It's a small, waterfront park and it will be obvious as soon as you enter w...
from __future__ import division import numpy as np from sklearn.svm import SVC from scipy.special import expit import copy from scipy.stats import norm from background_check import BackgroundCheck class OcDecomposition(object): def __init__(self, base_estimator=BackgroundCheck(), normalization=...
# PoolEvaluator.py from SingleNetworkEvaluator import * import sys IS_PY2 = sys.version_info < (3, 0) if IS_PY2: from Queue import Queue else: from queue import Queue from threading import Thread class Worker(Thread): """ Thread evaluating individuals from a given individuals queue """ def __init__(self...
def datos(): nombres = { 'Nombre': 'Maria' } return nombres def pedir_nombre(): nombre = raw_input('Ingrese un nombre: ') diccionario_prueba = datos() if nombre in diccionario_prueba: print('la llave existe') else: print('la llave no existe') if __name__ == '__main_...
# -*- coding: utf-8 -*- import lucene lucene.initVM() from lupyne import engine import operator import codecs import nltk import pickle import math as m import json import re from nltk.collocations import * import networkx as nx import matplotlib.pyplot as plt import numpy as np import csv from networkx.readwrite impor...
def CountPoints(word): dic={"e":1,"a":1,"i":1,"o":1,"n":1,"r":1,"t":1,"l":1,"s":1,"u":1, "d":2,"g":2, "b":3,"c":3,"m":3,"p":3, "f":4,"h":4,"v":4,"w":4,"y":4, "k":5, "j":8,"x":8, "q":10,"z":10} word=word.lower() score=0 for ind in word: ...
from firebase_admin import db from datetime import date, timedelta from .follow import get_user_following_uid_list # NEWSFEED 데이터베이스 구조 """ 'NEWSFEED': { 'uid': { 'nickname': '닉네임', 'snapshot': [timestamp1, timestamp2, ...] }, ... } """ # follow 목록을 가져와서 # 내가 follow하는 사람만 다 가져와서 # tim...
from bs4 import BeautifulSoup from urllib2 import urlopen import csv base_url = ("http://espn.go.com/college-football/rankings") soup = BeautifulSoup(urlopen(base_url).read()) teams = soup.find_all("td", "align-left team") team_urls = [td.a["href"] for td in teams] with open("data/src-ESPN_NCAAF_teams.tsv", "w") as...
__author__ = 'sujunfeng' user_info_dict = { 'jfsu':{ 'password':'abc123!', 'salary':30000, 'buying_list':[] }, 'mmm':{ 'password':'123123', 'salary':50000, 'buying_list':[] } } with open('user_info_list.txt','w',encoding="utf-8") as f_init: f_init.wri...
import Ntreefunctions as nt import matplotlib.pyplot as plt import U_Eigenvalues as egn import Regression_Fits as rg from numpy import * ''' This code is for generating A(M),B(M),Rho,Gamma for the function epsilon(N,M) The user specifies the min/max values for N and M The code generates the matrix U's, fi...
print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") count1 = 0 count2 = 0 combined_string = name1 + name2 lower_case_string = combined_string.lower() # T t = lower_case_string.count("t") r = lower_case_string.count("r") u = lower_case_string.count("...
# Source: https://www.reddit.com/r/dailyprogrammer/comments/65vgkh/20170417_challenge_311_easy_jolly_jumper/ # Not currently done def jumper(jolly): differences = [] for number in range (jolly[1],len(jolly)): differences.append(jolly[number]-jolly[number+1]) for changes in range(len(differences)-1)...
from django.core.cache import cache from django.db import models # Create your models here. from main.utils.custom_fields import ContentTypeRestrictedFileField class Course(models.Model): """ Represents a Course that Students registered for. Related to :model:`Lab Group`. """ course_code = models.Ch...
import sys from scrapy import cmdline sys.path.append("../") # cmdline.execute(["scrapy", "crawl", "douban_spider"]) cmdline.execute(["scrapy", "crawl", "douban_spider", "-o", "mingyan.json"])
#!/usr/bin/env python from os import path, makedirs import errno from time import sleep from argparse import ArgumentParser server_default_path = '/usr/local/bin/' file_extensions = ['csv','txt'] parser = ArgumentParser(description='Automatizacao dos script de cria_lista em shell') parser.add_argument('-e','--exten...
# 6kyu - Number , number ... wait LETTER ! """ Your task is to write a function named do_math that receives a single argument. This argument is a string that contains multiple whitespace delimited numbers. Each number has a single alphabet letter somewhere within it. Example : "24z6 1x23 y369 89a 900b" As shown ab...
{ "targets": [{ "target_name": "lwip_encoder", "sources": [ # LWIP: ####### "src/encoder/init.cpp", "src/encoder/jpeg_worker.cpp", "src/encoder/png_worker.cpp", "src/encoder/gif_worker.cpp", # LIB JPEG: #...
from o3seespy.command.nd_material.base_material import NDMaterialBase class FluidSolidPorous(NDMaterialBase): """ The FluidSolidPorous NDMaterial Class FluidSolidPorous material couples the responses of two phases: fluid and solid. The fluid phase response is only volumetric and linear elastic. T...
import urllib3 from manga_py.provider import Provider from .helpers.std import Std class MangaTownCom(Provider, Std): def get_archive_name(self) -> str: idx = self.get_chapter_index().split('-') return 'vol_{:0>3}-{}'.format(*idx) def get_chapter_index(self) -> str: idx = self.re.se...
''' Why does a destructor in a base class need to be declared virtual? Hints: 421, 460 ''' def virt_baseclass(s): pass if __name__ == '__main__': assert virt_baseclass('') == assert virt_baseclass('') == assert virt_baseclass('') == assert virt_baseclass('') == assert virt_baseclass('') ==
from tkinter import * # ---------------------------- PASSWORD GENERATOR ------------------------------- # # ---------------------------- SAVE PASSWORD ------------------------------- # # ---------------------------- UI SETUP ------------------------------- # windows = Tk() windows.title ("Password Manager") window...
import payconiq import requests from .exceptions import PayconiqError requests.adapters.DEFAULT_RETRIES = 5 class Transaction: @classmethod def get_base_url(cls): return '{base_url}/transactions'.format( base_url=payconiq.get_base_url() ) @classmethod def get_url(cls, i...
import cv2 import random import matplotlib.pyplot as plt import matplotlib.patches as patches import pickle from glob import glob import imgaug as ia from config import * import os import glob import pandas as pd import xml.etree.ElementTree as ET def display_img(img, polygons=[], channels="bgr", size=9): """ ...
from tetpyclient import RestClient import json import urllib3 # Access vars API_ENDPOINT="https://plx.cisco.com" CREDENTIALS_FILE='./api_credentials.json' urllib3.disable_warnings() rc = RestClient(API_ENDPOINT, credentials_file=CREDENTIALS_FILE, verify=False) resp = rc.get('/openapi/v1/applications/') #Print all a...
class Solution(object): def maxAreaOfIsland(self, grid): """ :type grid: List[List[int]] :rtype: int """ ans = 0 for x in range(len(grid)): for y in range(len(grid[0])): if grid[x][y]: ans = max(ans, self.bfs(grid, x, y)...
# 1249. Minimum Remove to Make Valid Parentheses # Given a string s of '(', ')' and lowercase English characters. # Your task is to remove the minimum number of parentheses('(' or ')', in any positions) so that the resulting parentheses string is valid and return any valid string. # Formally, a parentheses string is v...
import matplotlib.pyplot as plt def row_map(row): return list(map(int, row)) with open("image-output/img-4000-40.txt", "r") as f: d = f.readlines() data = [row.split(',') for row in d[0][:-1].split(';')] #print(data) int_data = list(map(row_map, data)) plt.imshow(int_data, cmap="inferno") plt.axi...
from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User) timestamp=models.DateTimeField(auto_now=False, auto_now_add=True) updated=models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self):...
nvar = 4 # conserved variables -- we set these when we initialize for they match # the ccData2d object idens = -1 ixmom = -1 iymom = -1 iener = -1 # for primitive variables irho = 0 iu = 1 iv = 2 ip = 3
import pyblish.api from avalon import io from reveries.maya import utils from maya import cmds class _ValidateModelConsistencyOnLook(pyblish.api.InstancePlugin): """(Deprecated) Ensure model UUID consistent and unchanged in LookDev """ order = pyblish.api.ValidatorOrder hosts = ["maya"] label =...
import pyttsx3 engine = pyttsx3.init() print("A B XC D E F G H I J ") engine.say('A B XC D E F G H I J') engine.runAndWait()
# Generated by Django 2.0.7 on 2018-07-31 15:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('yomarket', '0001_initial'), ] operations = [ migrations.AddField( model_name='shop', name='address', fie...
# Standard library imports import json import threading import logging import time # Third party imports from kafka import KafkaConsumer # Local application imports from Config.config import NiktoAgents, KafkaTopicNames, KafkaConfig, KafkaGroupIds from Module.AgentCaller.niktoCaller import NiktoCaller class NiktoSca...
""" The DESDM single-CCD image masking module. """ import os __author__ = "Felipe Menanteau, Alex Drlica-Wagner, Eli Rykoff" __version__ = '3.0.3' __revision__= '0' version = __version__ from . import immasklib from .immasklib import cmdline from .immasklib import elapsed_time
def etabar(t,per,A=1): n=A*numpy.sin(2*t*numpy.pi/per) return n def noisify(arr): A=numpy.max(arr) eps=numpy.random.normal(0,0.04*A,len(arr)) arr=arr+eps return arr,eps def der(arr,t): d=(arr[2:]-arr[:-2])/(2*(t[2:]-t[:-2])) return d def d2(arr,t): d=(arr[2:]-2*arr[1:-1]+arr[:...
import cv2 a = cv2.imread("D:/paper/IEEE model/0 2019 paper/picture/3shatian6_frame_10_1.png") b = cv2.resize(a,(1080,720),interpolation=cv2.INTER_AREA) cv2.imshow("b",b) cv2.imwrite("3shatian6_frame_10_2.png", b) cv2.waitKey(0) #等待按键
#!/usr/bin/env python3 # # Evaluate an assembly file # (not the same as running the virtual machine) # import sys from meta import register_names, flag_names from utils import remove_comment import core def get_operation_by_name(name): module = sys.modules['core'] return getattr(module, 'op_' + name) def par...
from django.conf.urls import url from ..views import introduction urlpatterns = [ url(r'^new$', introduction.new, name='introduction_new'), url(r'^(?P<pk>\d+)/update$', introduction.update, name='introduction_update'), url(r'^get$', introduction.get, name='introduction_get'), ]
from imports import * from data_loading import * def make_rand_attacks(name, x, y, model, method, step_size, chunk=50, epsilon=0.1, n_steps=1): x_aug = [] idx = 0 while idx < len(x): if (idx + chunk < len(x)): x_aug.extend(gen_rand_attack(x[idx:idx + chunk], ...
#!/usr/bin/env python 2.7 # -*- coding: utf-8 -*- import env import detect_engines.pdf.lib.classifier as classifier import detect_engines.pdf.lib.get_pdf_features as gpf def detect(data, filename): try: vector = gpf.get_pdf_features(data, filename) clf = classifier.get_pdf_classifier() re...
# -*- coding: utf-8 -*- """ biosppy.signals.bvp ------------------- This module provides methods to process Blood Volume Pulse (BVP) signals. -------- DEPRECATED -------- PLEASE, USE THE PPG MODULE This module was left for compatibility ---------------------------- :copyright: (c) 2015-2018 by Instituto de Telecomun...
import numpy as np import pandas as pd from contextlib import contextmanager import warnings from scipy.spatial.distance import pdist, squareform from enum import Enum class SymbolType(Enum): Stock=1, ETF=2 # General purpose utility functions for the simulator, attached to no particular class. # Available to ...
# Zero Matrix # Write an algorithm such that, if an element in an M x N matrix is 0, its entire row and column are set to 0.
#!/usr/bin/env python # coding=utf-8 a = int(input()); try: print('start trying...') r = 10 / a print('result:',r) except ZeroDivisionError as e: print('except:',e) finally: print('error!') print('END')
import logging import statistics import time from math import ceil from typing import List, Tuple, Optional, Dict from gensim.models import KeyedVectors class SimDimClusterWorker: def __init__(self, model: KeyedVectors): self._model: KeyedVectors = model self._minimum_cluster_size: int = max(10,...
import os import pygame from pygame import surface class ActorCharacter: """This class manages the actor character""" def __init__(self, actor_controller, actor_image=os.environ['test_image'], twitter_word='Default', twitter_sentiment_colour=(0, 0, 230), starting_position=(600, 600, 100, 100)...
#!/usr/bin/python # -*- coding: utf-8 -*- #### # 10/2010 Bernd Schlapsi <brot@gmx.info> # # This script 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 Foundation; either version 3 of the License, or # (at your option) an...
import numpy as np import scipy as sp def read_xray_image(): # use sp.misc.imread(path) pass def write_xray_image(): pass
#!/usr/bin/python import sys snpmer_keys_file = sys.argv[1] min_edge_coverage = int(sys.argv[2]) stride = int(sys.argv[3]) # read snp paths from stdin # graph to stdout snpmer_coverages = {} snpmer_name_mapping = {} with open(snpmer_keys_file) as f: for l in f: parts = l.strip().split(',') start_pos = int(parts...
# -*- coding: utf-8 -*- """ Course: CS 2302 Author: Wenro Osaretin Instructor: Diego Aguirre T.A.: Anindita Nath Date of Last Modication: November 4, 2018 """ ############################################################################### # Binary Search Tree ...
import logging import colorgram logging.basicConfig(level = logging.DEBUG) def main(): """ gets the top 13 colors from an image :return: list of tuple of rgb colors """ colors = colorgram.extract('hirst-image.jpeg', 5) color_list =[] print('colors = \\\n[') for color in colors: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 10 15:53:44 2019 @author: Dian, Aubert-Kato This is a smart shoes program. Start from reading the calibrated data Filtration, normalizing, window cutting, feature extraction, ML program """ import scipy from scipy import signal import scipy.signa...
import ssl import pytest import aiohttp from hailtop.auth import service_auth_headers from hailtop.config import get_deploy_config from hailtop.tls import _get_ssl_config from hailtop.utils import retry_transient_errors deploy_config = get_deploy_config() @pytest.mark.asyncio async def test_connect_to_address_on_po...