text
stringlengths
38
1.54M
# --------------------------- Word embeddings --------------------------- from utils.flags import FLAGS PRETRAINED_MODE = 'pretrained' FINETUNED_MODE = 'finetuned' TRAINED_MODE = 'trained' GLOVE = 'glove' GLOVE_URL = 'http://nlp.stanford.edu/data/' WORD2VEC = 'word2vec' FASTTEXT = 'fasttext' FASTTEXT_CRAWL_URL = '...
class BaseModel: """ Интерфейс модели """ def process(self, batch: list): """ Обработать группу запросов :param batch: группа запросов для обработки :return: результат применения модели """ raise NotImplementedError()
import scipy.io.wavfile as wav import os from os.path import basename class Files: @staticmethod def read_all_files(files_dir): files = os.listdir(files_dir) audio_files_data = [] file_names = [] for file in files: fs, audio_data = wav.read(files_dir + '/' + fil...
""" Matrix Spiral Copy Given a 2D array (matrix) inputMatrix of integers, create a function spiralCopy that copies inputMatrix’s values into a 1D array in a spiral order, clockwise. Your function then should return that array. Analyze the time and space complexities of your solution. Example: input: inputMatrix = [ ...
# # Copyright 2019 Ramble Lab # from flask import current_app from google.cloud import firestore, exceptions from datetime import datetime, timezone, timedelta from tzlocal import get_localzone db = firestore.Client() class Mutex(object): def __init__(self, resource=None, team_id=None, locked=False, owner=None,...
from __future__ import print_function, division, absolute_import import tensorflow as tf import numpy as np import zhusuan as zs from zhusuan import reuse import utils.data as data_ import utils.model as model from utils.ptb import reader from utils import parameters from utils.beam_search import beam_search from te...
import csv import re if __name__ == '__exchange_fixer__': exchange_in = [] with open('data/exchange_in.csv', mode='rt', newline='\r\n', encoding='utf-8') as exchange_in_file: for line in exchange_in_file: line = line.rstrip('\'\r\n') parts = line.split('؛') for i in ...
""" Copyright (c) 2014 High-Performance Computing and GIS (HPCGIS) Laboratory. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. Authors and contributors: Eric Shook (eshook@kent.edu); Zhengliang Feng (odayfans@gmail.com, zfeng2@kent.edu) """ from .Bo...
#!/usr/bin/env python3 def detect_ranges(L): # sorting the list sorted_list = sorted(L) seq_start = 0 seq_end = 0 result_list = [] # iterating from 2nd to last element for i in range(1, len(sorted_list)): if sorted_list[i] - 1 == sorted_list[i-1]: seq_end = i ...
#for loop for i in range(1,10): for j in range(1,10): s= i*j print ('%d * %d = %d ' %(i, j , s), end="") print('\n') # while loop i=1; while i < 10: j=1 while j < 10: s= i*j print ('%d * %d = %d ' %(i, j , s)) j += 1 i += 1 print...
"""Reusable validators.""" from typing import Callable from confusable_homoglyphs import confusables from teached import settings CONFUSABLE = "This name cannot be registered.Please choose a different name." CONFUSABLE_EMAIL = ( "This email address cannot be registered. " "Please supply a different email ad...
from pico2d import * import game_framework from Scene import rank_scene from Object import CPlane from Object import CPlayer from Object import CAsteroid from Object import CBullet from Object import CParticle import random particle_list = [] player_list = [] bullet_list = [] asteroid_list = [] plane_list = [] score =...
group_1 =int(input('Введите количество учеников в первой группе: ')) group_2 =int(input('Введите количество учеников во второй группе: ')) group_3 =int(input('Введите количество учеников в третьей группе: ')) result = group_1//2 + group_2//2 + group_3//2 if group_1/2 == 0 and group_2/2 == 0 and group_3/2 == 0: prin...
#!/usr/bin/env python # coding: utf-8 # In[105]: import pandas as pd from sklearn.model_selection import train_test_split import numpy as np from sklearn.feature_selection import SelectFromModel from sklearn.ensemble import RandomForestClassifier import eli5 from eli5.sklearn import PermutationImportance import matp...
import numpy as np import scipy import matplotlib.pyplot as plt ################################################ from scipy.signal import argrelextrema ################################################# # input: # ts, time series of a tidal wave # outpout: # MTL,MHHW,MHW,MLW,MLLW, tidal water levels (see their defin...
import numpy as np from cvxopt import solvers, matrix, spmatrix from scipy import sparse from scipy.linalg import norm from numpy.linalg import LinAlgError import warnings from least_squares import lstsq_solve def is_pos_def(A): if np.array_equal(A, A.T): # Test the symmetry of the matrix. try: ...
''' Created on May 25, 2018 @author: nishant.sethi ''' import math def bi_dist(x, n, p): b = (math.factorial(n)/(math.factorial(x)*math.factorial(n-x)))*(p**x)*((1-p)**(n-x)) return(b) b, p, n = 0, 0.12, 10 for i in range(0,3): b += bi_dist(i, n, p) print("%.3f" %b) b=0 for i in range(2,...
import logging from django.conf import settings from django.db import models from ...utilities.base_model import BaseModel from .encounter import Encounter # Get an instance of a logger logger = logging.getLogger(__name__) class Note(BaseModel): class Meta: # https://docs.djangoproject.com/en/1.10/ref/models...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Send simulated sensor data via UDP, bypassing udp-serial bridge. """ import math import sys import time import send_udp SERIAL_START_CHAR = b's' SERIAL_END_CHAR = b'e' TRANSMISSION_FREQ = 50 # Hz UDP_PORT = 9900 WHEEL_RADIUS = 0.3 # m if __name__ == "__main__": ...
from replit import clear # HINT: You can call clear to from art import logo print(logo) next = True bid_dict={} def find_highest_bidder(bidding_record): highest_bid = 0 winner = "" for bidder in bidding_record: bid_amount = bidding_record[bidder] if bid_amount > highest_bid: h...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
import tensorflow as tf from tensorflow.contrib import rnn import numpy as np class SeriesPredictor: def __init__(self, input_dim, seq_size, hidden_dim=10): ## Inspired from Machine Learning with TensorFlow by Nishant Shukla self.input_dim = input_dim self.seq_size = seq_size self.h...
import argparse import json import os from datetime import datetime import shutil import time from itertools import chain from pathlib import Path import melloddy_tuner as tuner import numpy as np import pandas as pd from scipy.io import mmwrite from scipy.sparse import csr_matrix def init_arg_parser(): parser...
from threading import Thread import configparser import datetime import re import subprocess import time import pyperclip as clp # install using "pip install pyperclip" import logging LIVESTREAMER = "livestreamer" YOUTUBE = "youtube" MPV = "mpv" TWITCH = "twitch" MAIN = "main" MESSAGES = "messages" LOGT...
import numpy as np import random import torch import nltk from gensim.scripts.glove2word2vec import glove2word2vec from gensim.models import KeyedVectors class RealDataLoader(): def __init__(self, batch_size, seq_length): self.batch_size = batch_size self.seq_length = seq_length # self.word...
import importlib #LOGGING from loguru import logger from aiogram import Dispatcher, types class MetaHandler(object): @staticmethod def register_all(dp = None): if dp is None: dp = Dispatcher.get_current() handlers_module = importlib.import_module('.handlers_bot', package='bot.handl...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^new', views.new), url(r'^create', views.create), url(r'^show', views.show), url(r'^(?P<number>[0-9]{4})', views.show), url(r'^edit/(?P<year>[0-9]{4})', views.edit), url(r'^delete...
""" This module is responsible for creating the DB. """ from flask_sqlalchemy import SQLAlchemy #: The database engine is set here db = SQLAlchemy()
def get_summ(num_one, num_two): try: one, two = int(num_one), int(num_two) return one + two except ValueError: return "Не могу сложить!" if __name__ == "__main__": print(get_summ(2, 2)) print(get_summ(3, "3")) print(get_summ("4", "4")) print(get_summ("five", 5)) pr...
# -*- coding: utf-8 -*- from .CatsOfUlthar import CatsOfUlthar from .ElderSign import ElderSign from .GreatRaceOfYith import GreatRaceOfYith from .Investigators import Investigators from .ProfessorHenryArmitage import ProfessorHenryArmitage from .RandolphCarter import RandolphCarter from .TheNecronomicon import TheNec...
n=int(input()) l=int(input()) a=[] flag=0 for x in range(n): k=int(input()) a.append(k) for x in range(n-1): ans=0 #print (x,"x ="); for y in range(x+1,n): ans=a[x]+a[y] #print (y,"y =",ans); if ans==l: flag=1 break if flag==1: print("Yes") else: print("NO")
#download images from web import urllib.request def dl_jpg(url, file_path, file_name = "Untitled"): #create full path full_path = file_path + file_name + '.jpg' #retrives and saves image using provided url urllib.request.urlretrieve(url, full_path) #ask user for image to save url = input("Enter image...
""" all rules/logic specific to the single cell ATAC workflow should be here. """ rule create_SNAP_object: """ Create a snapobject for each BAM file. These snapobjects can be merged later using snaptools in R. """ input: bam=expand("{final_bam_dir}/{{assembly}}-{{sample}}.sambamba-queryn...
import string newString = input("Enter input: ").lower() #newString takes the input and converts everything to lower new = list(set(newString.split())) #Split the new strings into a collection of words to put in a set. #This needs to be converted back into a list since sort() method is for lists only new.sort() pr...
import random def randomizeArray(arr): max=len(arr)-1 for i in range(max-1): j=random.randint(i,max) a=arr[i] arr[i]=arr[j] arr[j]=a a=["Talgat", "Hamza", "Behic", "adsasd", "masa", "ps"] randomizeArray(a) print (a)
import random pc = random.randint(1,100) for i in range(10): player = int(input('请输入数字:')) if player > pc: print('太大了') elif player < pc: print('太小了') else: print('答对了') break
#!/usr/bin/python3.7 # @Time : 2020/5/27 0027 15:44 # -*- coding: utf-8 -*- # @Time : 2020-05-27 15:38:50 from base.decorators import api_retry from base.exceptions import DefinedBusinessException, UndefinedBusinessException from base.helper import JsonHelper from bns.b2b.po.po_bns import BnsApi from testdata import g...
#import the required modules import RPi.GPIO as GPIO import time # set the pins numbering mode GPIO.setmode(GPIO.BOARD) # Select the GPIO pins used for the encoder K0-K3 data inputs GPIO.setup(11, GPIO.OUT) GPIO.setup(15, GPIO.OUT) GPIO.setup(16, GPIO.OUT) GPIO.setup(13, GPIO.OUT) # Select the signal used to select ...
1. Assert: Either Type(_V_) is Object or Type(_V_) is Null. 1. Let _current_ be ? _O_.[[GetPrototypeOf]](). 1. If SameValue(_V_, _current_) is *true*, return *true*. 1. Return *false*.
from urllib3.exceptions import ProtocolError, ReadTimeoutError import tweepy import dataset import json from tweepy import StreamListener from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer from textblob import TextBlob from models import * import pandas as pd import numpy as np from config import * im...
# 숫자의 개수 from sys import stdin A= int(stdin.readline()) B= int(stdin.readline()) C= int(stdin.readline()) num=A*B*C a = list(map(int, str(num))) for i in range(10): print(a.count(i))
#!/usr/bin/env python # --------------------------- # Name : Ryan J. Prater # EID : rp22566 # CSID : rprater # CS373 - Downing - Project #1 # --------------------------- """ To test the program: % python TestCollatz.py >& TestCollatz.py.out % chmod ugo+x TestCollatz.py % TestCollatz.py >& TestCollatz....
import ast from cosmic_ray.util import build_mutations OPERATORS = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod, ast.Pow, ast.LShift, ast.RShift, ast.BitOr, ast.BitXor, ast.BitAnd) def to_ops(f): return OPERATORS + (None,) def test_build_mutations_avoids_self_mutation...
#!/usr/bin/env python3 # from object_detection.py` import argparse from PIL import Image, ImageDraw from aiy.vision.inference import ImageInference from aiy.vision.models import object_detection from picamera import PiCamera import time import boto3 # connect to AWS S3 s3 = boto3.resource('s3', aws_access_key_i...
from datetime import timedelta from progress.bar import IncrementalBar # Progress has issues on Windows # https://github.com/verigak/progress/issues/58#issuecomment-471718558 def get_patched_progress(): # Import a clean version of the entire package. import progress # Import the wraps decorator for copyin...
# -*- coding: utf-8 -*- """ 假设未来的净资产收益率以及杠杆率不变,计算股票以当前价格买入后多久可收回成本 @author: robert """ import math import data def p2f(x): return float(x.strip('%'))/100 ticker_arr = ["AAPL", "FB", "DIS", "GOOG", "NVDA", "AMZN", "MSFT", "IBM", "BABA", "TCEHY", "V", "NKE", "LULU","GOLD"] title_arr = ["Trailing P/...
import sys def get_vas_for_fos(elf, fos): vas = [] for fo, _ in fos: foundVA = False for section in elf.sections: if section.file_offset < fo < \ section.file_offset + section.size: offset = fo - section.file_offset vas += [section.vi...
import numpy as np from one_step_kmeans_method import * def get_val(x,y,z,t,r): ''' A function to get the objective value. :param x: The centroids. [n,m] array :param y: The grids. [t,m] array :param z: The samples. ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Answers', fields=[ ('id', model...
from mongoengine import Q from mainapp.models_mongodb import messages def get(fromUser, toUser): return messages.objects().filter(fromUser__in=[fromUser, toUser], toUser__in=[fromUser, toUser]).order_by( 'created_at') def create(fromUser, toUser, content, file, type): mess = messages(fromUser=fromUser, toU...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-09-18 16:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('conference', '0010_auto_20170712_1241'), ] operations = [ migrations.AddFie...
from tkinter import* from tkinter import messagebox import requests import time from time import ctime from bs4 import BeautifulSoup import pandas as pd from PIL import ImageTk, Image root = Tk() root.geometry("400x100") root.title("Flipkart Price Tracker") root.resizable(height=False, width=False) r...
# -*- coding: utf-8 -*- """ .. class:: Worm This module contains the class that defines the worm as a whole """ import PyOpenWorm import sqlite3 from rdflib import ConjunctiveGraph, Graph, URIRef, Namespace, Literal from rdflib.namespace import RDFS class Worm: def __init__(self): self.semant...
# -*- coding: utf-8 -*- # language:zh-CN from time import sleep from appium import webdriver from common.common_method.appium.get_udid import get_android_udid from common.common_method.appium.start_appium import start_android_appium from common.page.Mobile.Android.Login.LoginPage import LoginPage class OPPOMobile: ...
from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth.models import User from .utils import sendOTPto from django.core.cache import cache from random import random from io import BytesIO from qrcode import make from base64 import b64encode from vehicle.models imp...
from django.conf.urls import patterns, include, url from django.contrib import admin from django.core.urlresolvers import reverse_lazy from django.views.generic import RedirectView from Verfahrensverzeichnis.admin import user_admin_site admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$',...
from django.test import TestCase from django.core.exceptions import ValidationError from django.db.utils import IntegrityError from django.core.files import File as DjangoFile from . import models from core import utils class ModelTest(TestCase): def test_can_add_and_retrieve_product(self): p1 =...
__title__ = 'svg file' class Machine: def __init__(self, parent, *args, **kwargs): self.parent = parent config_optional = [] config_required = ['filename'] def configure(self, *args, **kwargs): if 'filename' in kwargs: self.filename = kwargs['filename'] print "%s machine has filename %s" % (__titl...
import requests from geopy.geocoders import Nominatim import json import os import sys def reverse_geocode(coordinates): api_key = os.environ.get('POSITIONSTACK_API') lat, lng = [x.strip() for x in coordinates.split(',')[:2]] query = f'http://api.positionstack.com/v1/reverse?access_key={api_key}&query={lat...
from django.shortcuts import render from django.contrib.auth.decorators import (login_required, user_passes_test) from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.db import IntegrityError from django.urls import reverse from django.contrib.auth imp...
""" 1. 实现有向图、无向图、有权图、无权图的邻接矩阵和邻接表表示方法 2. 实现图的深度优先搜索、广度优先搜索实现 3. Dijkstra 算法实现 4. 拓扑排序 """ #实现图的深度优先搜索、广度优先搜索实现 from cllections import deque class Graph : """无向图""" def __init__(self,num_vertices): self._num_vertices = num_vertices self._adjacency = [[] for _ in range(num_vertices)] def add_edge(se...
import rospy from geometry_msgs.msg import PoseArray import tf from tf.transformations import euler_from_quaternion import numpy as np class RowEndpointDetection(object): def __init__(self): # Parse params. lines_topic = rospy.get_param('~lines_topic', '/state_lines') path_topic = rospy.get_param('...
# Copyright 2022 Northern.tech AS # # 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 ag...
# django import os from django.contrib.auth.models import User from django.db.models import Q, Max, Min from django.core.files.storage import FileSystemStorage from django.contrib.auth.decorators import login_required from django.contrib.auth import views as auth_views from django.http import JsonResponse from django...
import socket from threading import Thread from .TCPpackage import TCPpackage SERVER_PORT = 9998 class ServerCore(): def __init__(self): self.port = SERVER_PORT self.socket = self.create_socket() def create_socket(self, backlog=5): serversocket = socket.socket() serversocket.b...
import numpy as np import utils from flexprojects.parser import parse_flexible_project def decorate_quality_attributes(p, q, chosen_customer): qlevels = range(q['nqlevels']) def revenue_for_period(l, t): rperiods = q['customers']['revenue_periods'] revs = q['customers']['revenues'][chosen_cus...
import collections import sys T = int(raw_input()) for i in range(T): n = int(raw_input()) sideLengths = collections.deque(map(int, raw_input().split())) lastLength = sys.maxint answer = 'Yes' while len(sideLengths) > 0: if len(sideLengths) == 1: item = sideLengths.pop() ...
""" Helper functions for the pretrained model to be used within our API. Author: Explore Data Science Academy. Note: --------------------------------------------------------------------- Plase follow the instructions provided within the README.md file located within this directory for guidanc...
buildCount = 3 ninjaCount = 25 tunelCount = 2 banditCount = 40 print("calculating ....") ninjaTotal = ninjaCount * buildCount print(f"Total ninjas: {ninjaTotal}") banditTotal = banditCount * tunelCount print(f"Total bandits: {banditTotal}") total = ninjaTotal + banditTotal print(f"total: {total}")
import numpy as np import pandas as pd import random as rd import scipy.sparse as sp from time import time from collections import defaultdict class Data(object): def __init__(self, path, max_len=10): ''' ''' self.path = path self.max_len = max_len train_file = path ...
"""A module that contains helper functions""" import argparse from pathlib import Path, PurePath from typing import List def remove_vars(df, r_val: int, num_samples: int, cols: List[str]): """Removes variants that are homozygous variant or references in more that ...
"""Externalized strings for better structure and easier localization""" setup_greeting = """Dwarf - First run configuration Insert your bot's token, or enter 'cancel' to cancel the setup:""" not_a_token = "Invalid input. Restart Dwarf and repeat the configuration process." choose_prefix = """Choose a prefix. A pref...
import requests apikey = <<NEED TO FIX WITH CONFIGPARSER>> url = 'https://www.abuseipdb.com/check/' ip = '154.121.5.240' category = { 3: 'Fraud_Orders', 4: 'DDoS_Attack', 9: 'Open_Proxy', 10: 'Web_Spam', 11: 'Email_Spam', 14: 'Port_Scan', 18: 'Brute_Force', ...
x = 0 # zero is the starting point while x < 10: # while x remains less than 10 print(x) #print the numbers of X x += 1 # adds 1 to the count, 0,1,2,3, etc.
# Generated by Django 2.0.6 on 2018-06-22 07:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('post_office', '0006_attachment_mimetype'), ] operations = [ migrations.CreateModel( ...
import sys, json, time from pymongo import MongoClient mongo = MongoClient('198.199.113.194',27017) reddit = mongo['bigdata']['reddit'] # Load query from file try: commenters = json.load(open('top50comments.json')) subreddits = commenters.keys() # Read from mongo except IOError: print 'Aggregating top 50...' top...
game = [ [0, 0 ,0], [0, 0, 0], [0, 0, 0] ] def game_board(player=0, row=1, column=1): print(" a, b, c") if not just_display: game[row][column] = player for count,games in enumerate(game): print(count, games) game_board() game_board(player=1, row=2, column=1) # game[0][1] =...
''' try: 可能出现异常的代码 except: 如果有异常执行的代码 finally: 无论是否有异常都会执行的代码 ''' def add(a, b): try: return a / b except: print('除数不能为0') finally: print('你好啊') c = add(1, 0) print(c)
# This file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements. from pprint import pprint from data_manager import DataManager from flight_search import FlightSearch sheety = DataManager() # sheet_data = sheety.sheety_get_data() sheet_data = [ ...
from flask_mail import Message from flask import current_app from app import mail from threading import Thread def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(subject , sender, recipients, text_body, html_body): msg = Message(subject, sender = sender, recipients ...
# Generated by Django 2.2.6 on 2019-10-12 13:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('frontend', '0003_viewablegiftcard_featured'), ] operations = [ migrations.AddField( model_name='viewablegiftcard', n...
import sublime import sublime_plugin import os.path from ...core import ( JavaClass, JavaClassPath, JavaUtils, RE, SnippetsManager, StateProperty ) from ...utils import ( ActionHistory, StatusManager ) EXTENDS_IMPLEMENTS_RE = "([:<])" MAIN_TEMPLATE = "public static void main(String[] a...
# DO NOT AUTOVERSION # version=1.0.0 # -- dscudiero -- Thu 10/05/2017 @ 11:47:41.64 #================================================================================================== #================================================================================================== import inspect, sys, traceback impor...
from picamera import PiCamera import socket import telegram import time import os from encrypt import * PUBLIC_KEY_FILENAME = os.environ['PUBLIC_KEY_FILENAME'] BOT_TOKEN = os.environ['BOT_TOKEN'] CHAT_ID = int(os.environ['CHAT_ID']) CAPTURE_INTERVAL = int(os.environ['CAPTURE_INTERVAL']) def internet(host="8.8.8.8", ...
# Copyright 2022 Quantapix Authors. All Rights Reserved. # # 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 l...
import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as pypl import numpy import h5py import scipy.constants import popdrop from python_tools import multiprocesstools as mpt from scipy.misc import factorial # Molar protein concentration cs_molar = [5E-6, 75E-6, 100E-6, 200E-6] # [mol/l] for c_molar in ...
# Leetcode: 229. Majority Element II class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ # required O(n) and O(1) space candidate0, candidate1 = 0, 1 count0, count1 = 0, 0 for num in nums: ...
import abc import functools __all__ = ['Invertible', 'InvertibleNetwork'] _FORWARD = "forward" _BACKWARD = "backward" class Invertible(abc.ABC): @abc.abstractmethod def forward(self, x): return NotImplemented @abc.abstractmethod def backward(self, x): return NotImplemented clas...
import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F class ResidualNet_14(nn.Module): def __init__(self): super(ResidualNet, self).__init__() # Conolutions Layers self.conv1 = nn.Conv2d(in_channels = 3, out_channels = , kernel_size = 3) self.conv2 = nn.Conv2d(...
#!/usr/bin/env python # -*- coding: utf-8 -*- # indexhandlers.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Apr 2018 ''' These are Tornado handlers for the AJAX actions. ''' #################### ## SYSTEM IMPORTS ## #################### import logging import json from datetime import datetime import numpy as n...
from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import backref db = SQLAlchemy() class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String) name = db.Column(db.String) password = db.Column(db.String) fixtures = db.relatio...
import logging import os import requests GEOSERVER_BASE_URL = os.getenv('GEOSERVER_BASE_URL', 'http://localhost:8080/geoserver') GEOSERVER_USERNAME = os.getenv('GEOSERVER_USERNAME', 'admin') GEOSERVER_PASSWORD = os.getenv('GEOSERVER_PASSWORD', 'geoserver') _log = logging.getLogger(__name__) def create_workspace(...
import os import unittest from src.utility import lineyielder THIS_DIR = os.path.dirname(os.path.abspath(__file__)) def parse_boarding_pass(boarding_pass): row_spec = boarding_pass[:7] column_spec = boarding_pass[7:] rows = search(row_spec, range(0, 128), "F", "B") columns = search(column_spec, ran...
# Generated by Django 2.1.5 on 2019-02-11 13:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('foodrition_api', '0002_auto_20190206_1142'), ] operations = [ migrations.CreateModel( name='FoodImage', fields=[ ...
rule all: input: ".deps-installed", "sclr-lowbase.pdf" rule install_deps: input: "renv.lock" output: ".deps-installed" shell: """Rscript -e 'renv::restore();file.create(".deps-installed")'""" rule sim: input: ".deps-installed", "sim/sim.R" ...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Article(models.Model): title=models.CharField(max_length=30) content=models.TextField() create_time=models.DateTimeField() last_updated_time=models.DateTimeField(auto_now=True) author=models.F...
# references: # algorithm: https://perso.uclouvain.be/vincent.blondel/research/louvain.html # module: http://perso.crans.org/aynaud/communities/ # code: https://app.dominodatalab.com/LeJit/FacebookNetwork/browse? # snap data: https://snap.stanford.edu/data/ import networkx import mat...
from itertools import islice def fib(): prev, curr = 0, 1 while True: yield curr prev, curr = curr, curr+prev f = fib() result = list(islice(f, 0, 10)) print(result)
__author__ = 'lewis' from utils import new_dict_if_none _advertised_configs = {} class PlatformConfig(object): def __init__(self, caps=None): self._caps = new_dict_if_none(caps) @property def caps(self): return self._caps class LocalChromeConfig(PlatformConfig): def set_capabil...
#!/usr/bin/python # -*- coding: utf-8 -*- out_filename = "index.html" page_title = "Comparisons" comparisons = [ { "item1" : "Φίλιππος Πλιάτσικας", "img1" : "pliatsikas.jpg", "item2" : "Μία Πέτρα", "img2" : "stone.jpg", "questions" : [ [ "Μπορεί να συνθέσει αξιόλογη μουσική", "n"...