text
stringlengths
8
6.05M
# 모델 : RandomForestClassifier import numpy as np from time import time from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV from sklearn.utils import all_estimators from sklearn.metrics import accuracy_score, r2_score from sklearn.ensembl...
# -*- coding: utf-8 -*- from rest_framework import permissions class IsAccountOwner(permissions.BasePermission): """ Este es un permiso bastante básico. Si hay un usuario asociado con la petición actual, comprobamos si el usuario es el mismo objeto que account. Si no hay ningún usuario asociado a esta solici...
import os class FileManager(): """ A specific object used to interact with file management""" def __init(self): self.__current_directory = os.curdir # get a list of all pcap files in the current directory def get_pcap_files(self): fileList = list() fileList.extend([f ...
''' Input: a List of integers Returns: a List of integers ''' # def product_of_all_other_numbers(arr): # # Your code here # new_calc_array = [] # temp_array = [] # total = 0 # current = 0 # current_next = 1 # # find the product of all of the other numbers of an array input # # iterate through t...
# 럭키 스트레이트 # 점수를 반으로 나누어 왼쪽 합과 오른쪽 합이 같은지 체크하는 문제 # 1. 반으로 나눈다 -> 길이를 반으로 나눈다는 접근 -> len()//2 - 1 이 기준 # 2. 슬라이싱 해서 -> 좌우합을 구해주면 되겠다라는 아이디어 # 1차시도 runtime error # len()함수안에 변수를 넣지 않은것 # int형으로 변환 x # right_N에서 슬라이싱할때 끝부분을 -1한 것 N = list(map(int, input())) # 123456 문자열로 저장 left_N = N[0:len(N)//2] right_N = N[len(N)/...
from tkMessageBox import * if showerror('Error', 'This is an error!') == 'OK': sys.exit(1)
from os import getcwd from http.server import HTTPServer, BaseHTTPRequestHandler from logging import getLogger import urllib.request import subprocess class AgentServer(BaseHTTPRequestHandler): logger = getLogger(__name__) ''' member of BaseHTTPRequestHandler class client_address = client's addr...
import hashlib import hmac import json from io import BytesIO from pathlib import Path from time import time import boto3 import pytest import requests from PIL import Image from tcsocket.app.models import sa_con_skills, sa_contractors, sa_labels, sa_qual_levels, sa_subjects from .conftest import count, get, select_...
#!/usr/bin/python # Example of 3-layer neural network (original code: https://github.com/makeyourownneuralnetwork/makeyourownneuralnetwork) # Dataset: MNIST (short version) # Original MNIST dataset: http://yann.lecun.com/exdb/mnist/, full dataset in CSV: https://pjreddie.com/projects/mnist-in-csv/ import numpy import...
import re import random from typing import Optional from .accent import Accent def honk(m: re.Match) -> Optional[str]: return f"{' HONK' * random.randint(1, 4)}!" # https://github.com/unitystation/unitystation/blob/cf3bfff6563f0b3d47752e19021ab145ae318736/UnityProject/Assets/Resources/ScriptableObjects/Speech...
import unittest from gocdapi.go import Go from gocdapi.pipeline import Pipeline from gocdapi.stage import Stage class TestStage(unittest.TestCase): DATA0 = { "stages": [ { "name": "Deploy" }, { "name": "tests" } ], ...
# Generated by Django 2.2 on 2019-05-02 17:36 import datetime from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Articles', fields=[ ('id', mo...
# Generated by Django 3.1.4 on 2020-12-28 23:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reframery', '0005_auto_20201228_2337'), ] operations = [ migrations.AlterField( model_name='customuser', name='valid...
from multiprocessing import Pool, cpu_count from os import listdir, makedirs from re import search from time import time import cv2 ALPHA_BIAS = 0.5 BLUR_STRENGTH = 69 PROCESSES = [12, 9, 6, 4, 3, 2, 1] cv2.setNumThreads(1) # For OpenCV def main(): data_sets = ['data/{:s}'.format(set) for set in listdir('data')...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'bpmacmini01' from PIL import Image im = Image.open('/Users/bpmacmini01/Desktop/100.jpeg') print(im.format, im.size, im.mode) im.thumbnail((50, 50)) im.save('x.jpg', 'JPEG')
import iris as i import matplotlib.pyplot as plt import iris.plot as iplt from matplotlib import animation from matplotlib.animation import ArtistAnimation import cartopy.crs as ccrs from sys import argv from numpy import linspace from os import makedirs i.FUTURE.netcdf_promote = True color_map = plt.get_cmap('infern...
# create class polygon and rectangle class Polygon: def __init__(self, no_of_sides): self.n = no_of_sides self.sides = [0 for i in range(no_of_sides)] def inputSides(self): self.sides= [float(input("Enter side"+str(i+1)+":"))for i in range(self.n)] def dispSides(self): ...
# -*- coding: utf-8 -*- import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from MySQL import Database class Controller(QObject): db = None def __init__(self,*args): QObject.__init__(self,*args) self.db = Database() def getFullInfo(self): query = self.getQuery(None) self.emit(SIGNAL(...
''' author: juzicode address: www.juzicode.com 公众号: juzicode/桔子code date: 2020.6.5 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: juzicode/桔子code\n') print('dict 内置方法/函数实验:') d={'juzi':10,'code':'orange','com':(1,2,3)} print('d :',d) print('d.keys() : ',d.keys()) print('d.keys()类型 : ',type(d.key...
def is_prime(n): if n <= 1: return False for devisor in range(2, n): if n % devisor == 0: return False return True def goldbach(n): if n % 2 != 0 or n < 2: return [] result = [(number, n - number) for number in range(n) if is_prime(number) and is_p...
import os import time import urllib.request import pytest bs4 = pytest.importorskip('bs4') # noqa pytest.importorskip('lxml') # noqa import teek from teek.extras.soup import SoupViewer pytest.importorskip('teek.extras.image_loader') DATA_DIR = os.path.join( os.path.dirname(os.path.dirname(os.path.abs...
import common_vars as cvars import pandas as pd df = pd.read_csv(cvars.train_file) print (df.columns.values) print (len(df)) df['Browser_Used'] = df['Browser_Used'].apply(lambda x: cvars.browser_dict[x]) for col in df.columns.values: print (col, len(df[col].unique())) print (df.groupby(['Is_Response']).count()....
from tkinter import * CELL_LENGTH = 60 CELL_WIDTH = 60 FENCE_LENGTH = 60 FENCE_WIDTH = 15 TABLE_LENGTH = 9 TABLE_WIDTH = 9 NAME_CELL = 'C' NAME_FENCE = 'F' NAME_HORIZONTAL = 'H' NAME_VERTICAL = 'V' X1, Y1, X2, Y2 = 4, 8, 4, 0 colour_default = 'brown' picture_background_direction = 'floor.png' picture_button_default...
#encoding: utf8 from splitdata import splitdata from improve_cos import improve_cos from user_cf import user_cf from precision_recall import precision,recall from coverage import coverage from popularity import popularity import time from settings import * def load_data(name): records = [] # key => items f = o...
class Exemple3: def __init__(self, long=45,larg=23): self.longueur = long self.largeur = larg def aire(self): print("L'aire de ce rectangle est de ", self.longueur,"X",self.largeur,"=",self.longueur*self.largeur) # suite de l'exemple dans le fichier main.py
a=10 b=20 if(a==b): print'true' else: print 'false' print"-------------" if(a!=b): print'true' else: print 'false' print"-------------" if(a<>b): print'true' else: print 'false' print"-------------" if(a>b): print'true' else: print 'false' ...
""" distutilazy.command.clean_pyc ----------------------------- Command to clean compiled python files :license: MIT. For more details see LICENSE file or https://opensource.org/licenses/MIT """ import distutilazy.clean class clean_pyc(distutilazy.clean.CleanPyc): pass
import numpy as np import cv2 import psutil import Image import ImageGrab import matplotlib.pyplot as plt from threading import Timer import win32api, win32con import time from itertools import izip import os import sys from boto.dynamodb.condition import NULL from networkx.generators.community import caveman_graph fro...
a=int(input("entre first number :")) b=int(input("enter sec number :")) print(a,b) min=a if a<b else b print("mim value :",min)
__version__ = "1.11.1" from .pyNetwork import pyNetwork from .pyGeo import pyGeo from .pyBlock import pyBlock from .constraints import DVConstraints from .parameterization import DVGeometry from .parameterization import DVGeometryAxi try: from .parameterization import DVGeometryVSP except ImportError: pass tr...
# encoding: utf-8 """ Created on 2016-12-9 @author: Kyrie Liu @description: init relay """ from Relay import * import time import os import sys import pickle import win32com.client class InitRelay(Relay): def __init__(self, sn): Relay.__init__(self, sn) from RelayConst import Const self...
import sys sys.path.append('../') import torch import torch.nn as nn from openai_transformer.model_pytorch import TransformerModel from openai_transformer.model_pytorch import load_openai_pretrained_model, DEFAULT_CONFIG class TransformerSentenceEncoder(nn.Module): def __init__(self, n_special, n_ctx=512, transfo...
import json from datetime import datetime from typing import Any, Dict, List, cast from covid19_sfbayarea.utils import dig, parse_datetime from .cases_by_age import CasesByAge from .cases_by_ethnicity import CasesByEthnicity from .cases_by_gender import CasesByGender from .meta import Meta from .deaths_by_age impor...
all_repos_to_get = dict() set1 = set() with open("/Users/davidwu/Desktop/cs221/cs221_github_project/davids_stuff/input_data/featurized-repos-2.txt") as input_file: for line in input_file: if "owner.login_name owner.type open_issues_count has_wiki has_downloads has_projects archived size fork owner_popularit...
import argparse #parse arguments parser = argparse.ArgumentParser(description="Experiemts for ZP resolution (by qyyin)\n") parser.add_argument("-data",default="None",help="specify data file") parser.add_argument("-type",default="None",help="azp:Get azp feature ***\n\r res:Get res feature") parser.add_argument("-res_t"...
# 忽略警告提示 import warnings warnings.filterwarnings('ignore') # 导入数据分析包 import pandas as pd import numpy as np # 导入数据可视化包 import matplotlib.pyplot as plt import seaborn as sns # 导入数据 train_df = pd.read_csv('./titanic/train.csv',encoding='gbk') test_df = pd.read_csv('./titanic/test.csv',encoding='gbk') print('训练数据集:',tr...
''' Author : Dhruv B Kakadiya ''' import random as rd from math import sqrt def getPrimeFactors(n): factors = [] # If 2 is a factor if (not n & 1): factors.append(2) while (not n & 1): n = n >> 1 # If prime > 2 is factor for i in range(3, int(s...
import Sample as S sample = S.Sample() resp = sample.query_unread() # print(resp) for x in resp: print(x) # sample.delete(3) # print("after update") # resp = sample.query_unread() # # print(resp) # for x in resp: # print(x)
import numpy as np def convert_to_cylindrical(x,y,z): p = np.sqrt(np.square(x)+np.square(y)) phi = 1/np.tan(y/z) z = z return (p,phi,z) def reverse_1(p,phi,zee): x = p*np.sin(phi) y = p*np.cos(phi) z = zee return (x,y,z)
from django.http import Http404, HttpRequest, JsonResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from slither.models import Slither def view_index(request): return render(request, 'slither/index.html', { ...
from django.test import TestCase, Client from .models import ClientProfile, TypeUser from .forms import * import json from django.urls import reverse, resolve class TestURLS(TestCase): def setUp(self): self.client = Client() self.index_url= reverse('CM:index') self.profile_url= reverse('CM:...
# Manual stimulus used to find the receptive field position and size. # # Copyright (C) 2010-2012 Huang Xin # # See LICENSE.TXT that came with this file. from Experiments.Experiment import ExperimentConfig,ManbarExp,MangratingExp ExperimentConfig(data_base_dir='data',new_cell=True) # When a neuron is isolated in Pl...
""" .. module:: helpers :synopsis: Helper functions """ import re def null_distance_results(string1, string2, max_distance): """Determines the proper return value of an edit distance function when one or both strings are null. **Args**: * string_1 (str): Base string. * string_2 (str): The stri...
#_*_coding:utf-8_*_ from django.db import connection import logging logger = logging.getLogger(__name__) class CustomSQL(object): def __init__(self,q=None,p=[]): self.q = q self.p = p self.cursor = connection.cursor() def fetchone(self): self.cursor.execute(self.q,self.p) ...
#!/usr/bin/env python3 """Converts a directory tree containing resource topology data to a single XML document. Usage as a script: resourcegroup_yaml_to_xml.py <input directory> [<output file>] If output file not specified, results are printed to stdout. Usage as a module from converters.resourcegroup_yaml...
import torch import torch.nn as nn import torch.nn.functional as F def expand_index(mask): kernel = torch.ones((1, 1, 3, 3), device=mask.device).detach() return F.conv2d(mask.float(), weight=kernel, stride=1, padding=1)
import numpy as np import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from distributions import Categorical from replay_buffer import ReplayBuffer class OrnsteinUhlenbeckNoise(): def __init__(self, mu, sigma=0.1, theta=0.1, dt=0.01, x_0=None): ""...
#!/usr/bin/env python # coding: utf-8 # In[46]: # This Linear Regression model for Stock Market Predecting import pandas_datareader.data as web # import pandas_datareader to read data from the web - stock market import datetime as dt import pandas as pd import matplotlib.pyplot as plt # for ploting the graph f...
import cv2 as cv import numpy as np img_color = cv.imread('../test.jpg', cv.IMREAD_COLOR) # 이미지의 높이와 너비를 가져옴 print("img datatype", type(img_color)) print("real values : ", img_color) height, width = img_color.shape[:2] print("height : ", height, ", width : ", width) # 그레이 스케일 이미지 저장할 넘파이 배열 생성 img_gray = np.zeros( ...
import tensorflow as tf import tensorflow_datasets as tfds W = tf.Variable(tf.ones(shape=(2, 2), name="W")) b = tf.Variable(tf.zeros(shape=(2)), name="b") @tf.function def forward(x): return W*x+b out_a = forward([1, 0]) print(out_a)
import unittest from ..util import LazyFile class TestUtil(unittest.TestCase): def test_lazy_file(self): license_file = LazyFile('LICENSE.txt') self.assertTrue(license_file.file is None) iter(license_file) handle_0 = license_file.file iter(license_file) handle_1 = l...
# Copyright (c) 2017-present, Facebook, 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 or agreed...
# -*- coding: future_fstrings -*- # MIT License # Copyright (c) 2017 Cosmic Open Source Projects # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limit...
import datetime import time from pythonjsonlogger import jsonlogger class JsonLogFormatter(jsonlogger.JsonFormatter): def __init__(self, service_name, datacenter, env, hostname, get_tracking_info, *args, **kwargs): jsonlogger.JsonFormatter.__init__(self, *args, **kwargs) self.service_name = service...
''' Created on 2013-4-25 @author: Xsank '''
#%% import numpy as np import pandas as pd from scipy import stats import matplotlib.pyplot as plt import seaborn as sns import arviz as az from collections import Counter from scipy.interpolate import griddata import pymc3 as pm import theano as tt sns.set() #%% # Functions def sort_vals(vals, ascending = True): ...
# 실습 7 listv1 = ["A", "b", "c", "D", "e", "F", "G", "h"] listv2 = [d for d in listv1 if 97 <= ord(d) <= 122] print(listv2)
import numpy as np def root_mean_square(dots, n): # n - количество искомых коэффициентов length = int(np.size(dots) / len(dots[0])) sum_x_n = [sum([dots[i][0] ** j * dots[i][2] for i in range(length)]) for j in range(2*n - 1)] sum_y_x_n = [sum([dots[i][0]**j*dots[i][2]*dots[i...
from app import db from models import BlogPost # create the db and the db db.create_all() #insert etc db.session.add(BlogPost("Good", "I\'m good.")) db.session.add(BlogPost("Well", "I\'m well.")) db.session.add(BlogPost("postgres", "This post will mean that the postgres db is go!")) # commit the changes db.session....
from rest_framework import serializers from rest_framework.relations import SlugRelatedField, PrimaryKeyRelatedField from api.models.ApprovedFuel import ApprovedFuel from api.models.ComplianceReportSchedules import ScheduleC, ScheduleCRecord, ScheduleARecord, ScheduleA, ScheduleBRecord, ScheduleB from api.models.Expec...
#!/usr/bin/python import subprocess import sys import os import urllib import json from optparse import OptionParser import phonegap parser = OptionParser() parser.add_option("-d", "--directory", dest="directory", help="Your Phonegap www directory source") parser.add_option("--skip...
""" This GA code uses a simplified version of the gaModel where only some bins are considered. """ from numba import jit from operator import attrgetter from deap import base, creator, tools import numpy from csep.loglikelihood import calcLogLikelihood from models.mathUtil import calcNumberBins import models.model imp...
import array import bz2 from django.db import models from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext_lazy as _ class AutoGrowingList(list): """ A class to hold auto growing lists with a configurable index offset """ EMPTY = -1 INDEX_OFFSET = 1 de...
import numpy as np def findvar(ret, alpha=0.05, nbins=100): # Function computes an empirical Value-at-Risk (VaR) for return-series # (ret) defined as NumPy 1D array, given alpha # (c) 2015 QuantAtRisk.com, by Pawel Lachowicz # # compute a normalised histogram (\int H(x)dx = 1) # nbins: numbe...
from django.db import models # Create your models here. class Pawn(models.Model): xpos = models.DecimalField(decimal_places=3,max_digits=30) ypos = models.DecimalField(decimal_places=3,max_digits=30) # Splendor model objects class SplendorGame(models.Model): name = models.CharField(max_length=100) clas...
#!/usr/bin/env python import random from subprocess import call idx=0 score=0 while True: idx+=1 a=range(3,10) b=range(3,10) x=random.choice(a) y=random.choice(b) print "{0} => what's the answer of: {1} + {2}".format(idx,x,y) print "_____________________________________________" try: ...
from django.contrib import admin from . import models import logging # Register your models here. auths_log=logging.getLogger('auths') auths_log.debug('auth_log') admin.site.register(models.library) admin.site.register(models.libraryUser) admin.site.register(models.libType) admin.site.register(models.library_detail_inf...
import collections import functools import itertools import logging import os import warnings import joblib import numpy as np import pandas as pd import statsmodels.stats.proportion import tensorflow as tf from joblib import delayed, Parallel from tqdm import tqdm from questions import plot from questions import uti...
""" Calculate power distribution of laser scanning photo-activation device Laser beam symbols used are from the beam power formula: [1] en.wikipedia.org/wiki/Gaussian_beam#Power_through_an_aperture References: [2] radiantzemax.com/kb-en/Goto50125.aspx [3] leica-microsystems.com/products/light-microscopes/accessories/...
__all__ = ['public_prefixes']
# -*- coding: utf-8 -*- import typing import monotonic from bravado_core.response import IncomingResponse if getattr(typing, 'TYPE_CHECKING', False): # Needed to avoid cyclic import. from bravado.config import RequestConfig T = typing.TypeVar('T') class BravadoResponse(typing.Generic[T]): """Bravado resp...
from .models import User from .views import app __all__ = ['User', 'app']
#-*- conding:Utf-8 -*- #写一个列表,放入表示扑克牌的52张牌(不包含大小王牌) #C代表club梅花,D代表diamond方块,S代表spade黑桃,H代表heart红心,1-13分别代表A-K, poker_list = [] kind_list =["C","D","H","S"] for i in kind_list: for j in range(13): poker_list.append(i + str(j+1)) print(poker_list) print(type(poker_list)) print(len(poker_list)) print(type(p...
import unittest def compress_string(s): can_compress = False for i in range(len(s) - 2): if s[i] == s[i + 1] and s[i + 1] == s[i + 2]: can_compress = True break if not can_compress: return s count = 1 last = s[0] compressed = '' for c in s[1:]: ...
from flask import Flask from flask import abort app = Flask(__name__) @app.route('/') def index(): abort(401) return "NEVER_EXECUTED" @app.errorhandler(404) def page_not_found(error): return 'PAGE_NOT_FOUND', 404 if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
import RPi.GPIO as GPIO from time import sleep class Motor: def __init__(self, pin, frequency=50): self.frequency = frequency GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT) self.pwm=GPIO.PWM(pin, frequency) self.initializeESC() def initializeESC(self): self...
import pgzrun from settings import * from gamelib.pgzgamemanager import GameManager from gamelib.scene import Scene from flappystates import MainMenuState, GameOverState, PlayState def update(): game.update() def on_set_settings(var_name, value): globals()[var_name] = value def on_key_down(): game.ev...
""" A SOCKS HTTPConnection handler. Adapted from https://gist.github.com/e000/869791 """ from __future__ import absolute_import import socket import socks try: from http.client import HTTPConnection import urllib.request as urllib_request except ImportError: from httplib import HTTPConnection import urll...
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext from Cython.Build import cythonize ext_modules = [ Extension("my_module", ["lib/my_module.py"]), # ... all your modules that need be compiled ... ] setup( name = 'example', cmdclass = {'build...
import csv import time from fuzzywuzzy import fuzz from fuzzywuzzy import process from urllib.request import urlopen from urllib.error import HTTPError from urllib.request import urlretrieve from urllib.parse import urlencode from urllib.parse import quote from itertools import chain import inquirer # import jsonel ...
import random from base import baseEnemy class snowMan(baseEnemy): def __init__(self, name, lvl, hostile, x = 0, y = 0, ID = 0, img = 'img/enemies/snowMan.png'): super(snowMan, self).__init__(name, lvl, hostile, x, y, img, ID) self.dmg = self.lvl * 3 + random.randint(0, self.lvl) self.hp = self.lvl * 4 + random...
import copy import time from itertools import permutations from itertools import chain, combinations from utils import ( is_in, argmin, argmax, argmax_random_tie, probability, weighted_sampler, memoize, print_table, open_data, Stack, FIFOQueue, PriorityQueue, name, distance ) ids = ['205889892', '205907132...
import sys import os import platform import subprocess if platform.platform() == 'Linux-4.9.32-v7+-armv7l-with-debian-8.0': subprocess.call(" ln -s /usr/local/lib/python3.4/dist-packages/cv2.cpython-34m.so cv2.so", shell=True) import cv2 subprocess.call(" uvcdynctrl -d /dev/video0 -s \"Focus, Auto\" 0", ...
# -*- coding: utf-8 -*- from pyramid_formalchemy.views import ModelView as Base from pyramid.renderers import render_to_response from pyramid.response import Response from formalchemy.fields import _pk from fa.extjs.fanstatic_resources import fa_extjs from js.extjs import theme import simplejson as json import datetime...
from flask import Flask, request, jsonify, render_template, redirect from flask_pymongo import PyMongo from bson.objectid import ObjectId import datetime app = Flask(__name__) app.config["MONGO_URI"] = "mongodb://localhost:27017/311db" mongo = PyMongo(app) @app.route('/', methods = ['GET']) def hello_world...
from django.shortcuts import render from models import DummyModel def dummies(request): qs = DummyModel.objects.all() return render(request, 'dummies.html', {'qs': qs})
# -*- coding: utf-8 -*- from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from forms.enums import FormRequestReadStatusEnum, CallbackFormPlaceEnum, FeedbackFormPlaceEnum from snippets.models import LastModMixin, BasicModel class BaseFormRequest(Last...
def search(visitados, matrix, i, j, lin, col): if i > 0 and matrix[i-1][j] == 'H' and not (i-1, j) in visitados: visitados.append((i-1, j)) matrix[i][j] = '.' return search(visitados, matrix, i-1, j, lin, col) if i <lin-1 and matrix[i+1][j] == 'H' and not (i+1, j) in visitados: ...
from torch.autograd import Variable from torch.utils.data import DataLoader import random class Wrapper(object): pass class RLWrapper(Wrapper): _pytorch = True _vectorized = True def __init__(self, datasets, batch_size=32, workers=1, use_cuda=False): """ :param datasets: A list of Data...
class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ # # Solution 1 # k = k % len(nums) # if k == 0: # temp = [] # else: # ...
#!/usr/bin/python import sys import nltk from nltk.corpus import stopwords import string import re #This script takes a question removes apostophe, punctuation and stop words if len(sys.argv) != 2: print "Incorrect argument format" else: question = sys.argv[1]; print question; #remove apostrophe question = re.s...
# @Author: aravind # @Date: 2016-08-08T21:59:16+05:30 # @Last modified by: aravind # @Last modified time: 2016-08-08T22:43:07+05:30 from selenium import webdriver import os import getpass import json from selenium.common.exceptions import WebDriverException, NoSuchElementException home_path = os.getenv('HOME') b...
from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def setUp(self): self.payload = { "email": "milan9oaasdsd@gmail.com", "password": "12345qwerty", "first_name": "Milan", "last_name": "Petkovic", "phone": "123234283", ...
from tensorflow.keras import layers from tensorflow.keras.layers import TimeDistributed, LayerNormalization from tensorflow.keras.models import Model, Sequential from tensorflow.keras.regularizers import l2 import kapre from kapre.composed import get_melspectrogram_layer import tensorflow as tf import os def Conv1D(NU...
#!/usr/bin/env python3 """ Test for localif identifier """ import unittest from base_test import PschedTestBase from pscheduler.limitprocessor.identifier.localif import * DATA = { } class TestLimitprocessorIdentifierJQ(PschedTestBase): """ Test the Identifier """ def test_data_is_valid(self): ...
import os import requests import json import datetime as dt from boto.s3.connection import S3Connection, Location from boto.s3.key import Key def unsafe_getenviron(k): v = os.environ.get(k) if(v): return v else: raise Exception('environment variable %s not set' % k) JC_DECAUX_API_KEY = unsafe_getenviron('JC_...
import datetime import calendar weekday_token = { 'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6 } modifier_token = { '1st': 0, '2nd': 1, '3rd': 2, '4th': 3, '5th': 4, 'last': -1, 'teenth': 100 } def m...
import torch import torch.utils.data # from torch.nn.modules.distance import PairwiseDistance from torch.distributions.normal import Normal import matplotlib.pyplot as plt class MapClass: def __init__(self, data, length, width, learning_rate, number_iterations, matrix_graph_weights, data_lables=None, batch_size=...
import pandas as pd from autumn.core.project import ( Project, ParameterSet, load_timeseries, build_rel_path, get_all_available_scenario_paths, use_tuned_proposal_sds, ) from autumn.calibration import Calibration from autumn.calibration.priors import UniformPrior from autumn.calibration.targets...
import pyautogui as pg import time pg.hotkey("winleft","ctrl","d") pg.hotkey("winleft") pg.typewrite("chrome\n",0.3) pg.hotkey("winleft","up") time.sleep(1) pg.hotkey("winleft","up") time.sleep(1) pg.hotkey("winleft","up") time.sleep(1) pg.typewrite("https://www.youtube.com/watch?v=yqEeP1acj4Y\n",0.1) tim...