content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- class Config(object): def __init__(self, config_path): config_path = Config.validate_path(config_path) self.config_path = config_path self._config = Config.validate_format_and_parse(config_path) def __getitem__(self, key): return self._config.get(key) ...
from django.conf.urls import include, url from django.contrib import admin #handler400 = 'world.views.error400page' #AEN: THIS doesn't work! import voxel_globe.main.views urlpatterns = [ #Admin site apps url(r'^admin/', include(admin.site.urls)), #Test app for development reasons url(r'^world/', inc...
"""added column to DT and created NewTable Revision ID: 1100598db8eb Revises: 66362e7784fd Create Date: 2021-02-21 13:56:05.307362 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '1100598db8eb' down_revision = '66362e7784fd' branch_labels = None depends_on = No...
import time import multiprocessing import subprocess import sys import os def run(name): dir_path = os.path.dirname(os.path.realpath(__file__)) subprocess.Popen(('%s' % sys.executable, os.path.join(dir_path, "test_remote.py"), name, "etc etc")) if __name__ == '__main__': multiprocessing.Process(target=ru...
# -*- coding: utf-8 -*- from __future__ import print_function import os from concurrent.futures import TimeoutError from kikimr.public.sdk.python import client as ydb import random EXPIRATION_QUEUE_COUNT = 4 DOC_TABLE_PARTITION_COUNT = 4 ADD_DOCUMENT_TRANSACTION = """PRAGMA TablePathPrefix("%s"); DECLARE $url AS Ut...
#Elsa by Frostmeister import discord import math import time import googlesearch as gs import urbandictionary as ud import random import asyncio from discord.ext import commands ####### General class General: def __init__(self , bot): self.bot = bot @commands.command() async def in...
# -*- coding:utf-8 -*- """ jsondict <-> dict <-> model object \______________________/ """ def _datetime(*args): import pytz from datetime import datetime args = list(args) args.append(pytz.utc) return datetime(*args) def _getTarget(): from alchemyjsonschema.mapping import Draft4MappingF...
import numpy as np ''' Reorient the mesh represented by @vertices so that the z-axis is aligned with @axis ''' def orient_mesh(vertices, axis): vector_norm = np.sqrt(axis[0]**2 + axis[1]**2 + axis[2]**2) yz_length = np.sqrt(axis[1]**2 + axis[2]**2) # Rotate around the y-axis if vector_norm != 0: ...
# -*- coding: utf-8 -*- import logging import math import random from PIL import Image, ImageDraw from .wallpaper_filter import WallpaperFilter from ..geom.point import Point from ..geom.size import Size logger = logging.getLogger(__name__) class Tunnel(WallpaperFilter): def _centroid(self, size) -> Point: ...
#!/usr/bin/env python #-*- coding=UTF-8 -*- import httplib2 import json import random import string import time import urllib from securUtil import SecurUtil class smsUtil(): @staticmethod def baseHTTPSRequest(url, data): # 配置 HTTP Request Header AppKey = '1958cd7bc542a299b0c3bc428f14006e'...
""" drift ===== Drift calculation methods. """ from .continuous import drift_continuous from .roman import drift_roman
# Copyright (c) 2019, Digi International, Inc. # # 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 limitation the rights # to use, copy, modify, merge, pu...
import math, glm class Camera: def __init__(self, position): self.position = position self.up = glm.vec3(0, 1, 0) self.worldUp = glm.vec3(0, 1, 0) self.pitch = 0 self.yaw = 0 self.speed = 20 self.sensitivity = 0.25 self.updateVectors() def moveRi...
from bfieldtools import contour import pytest import numpy as np from numpy.testing import ( assert_array_almost_equal, assert_array_equal, assert_allclose, assert_equal, ) def setup_contour_input(): """ Load example mesh and create scalars data """ from bfieldtools.utils import load_exa...
# Leia um valor de comprimento em jardas e apresente-o convertido em metros # A foruma de conversão é: M = 0.91 * J J = float(input("Digite um valor em jardas: ")) M = 0.91 * J print("O valor em de jardas para metros é: %0.2f" % M)
from .arch import Arch from .debian import Debian from .ubuntu import Ubuntu from .redhat import RedHat from .centos import CentOS
import argparse import torch from torch.autograd import Variable import model import util import data import time import torchvision.transforms as transforms import shutil model_names = sorted(name for name in model.__dict__ if name.startswith("Planet") and callable(model.__dict__[name])) print model_names ...
import abc class RecurrentSupervisedLearningEnv(metaclass=abc.ABCMeta): """ An environment that's really just a supervised learning task. """ @abc.abstractmethod def get_batch(self, batch_size): """ :param batch_size: Size of the batch size :return: tuple (X, Y) where ...
''' Created on Aug 9, 2013 @author: salchoman@gmail.com - salcho ''' class wsResponse: def __init__(self, id=-1, params=None, size=-1, response=None, payload=None, plugin=None): self.id = id self.params = params self.size = size self.http_code = -1 self.response = None...
import tensorflow as tf def iou(source, target): """Calculates intersection over union (IoU) and intersection areas for two sets of objects with box representations. This uses simple arithmetic and outer products to calculate the IoU and intersections between all pairs without looping. Parameter...
# Generated by Django 3.0.3 on 2020-08-10 13:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ecommerce_platform', '0015_auto_20200810_1252'), ] operations = [ migrations.RenameField( model_name='coupon', ...
import pytest from pytest import approx import os import shutil import numpy as np import pandas as pd from tarpan.testutils.a03_cars.cars import get_fit from tarpan.cmdstanpy.waic import ( waic, compare_waic, save_compare_waic_csv, save_compare_waic_txt, waic_compared_to_df, WaicData, WaicModelCompared, ...
# -*- coding: utf-8 -*- # @Date : 2019-07-26 # @Author : Xinyu Gong (xy_gong@tamu.edu) # @Link : None # @Version : 0.0 import os import glob import argparse import numpy as np from scipy.misc import imread import tensorflow as tf import utils.fid_score as fid def parse_args(): parser = argparse.Argument...
# -*- coding: utf-8 -*- from __future__ import absolute_import ''' @author: Jinpeng LI @contact: mr.li.jinpeng@gmail.com @organization: I2BM, Neurospin, Gif-sur-Yvette, France @organization: CATI, France @organization: U{IFR 49<http://www.ifr49.org>} @license: U{CeCILL version 2<http://www.cecill.info/licences/Lice...
from dataclasses import dataclass, field from typing import Dict from lf3py.serialization.deserializer import DictDeserializer @dataclass class SNSMessage(DictDeserializer): message: str = '' attributes: Dict[str, Dict[str, str]] = field(default_factory=dict)
from utils import * def cross_val_split(dataset, folds): """ Splits the dataset into folds number of subsets of almost equal size after randomly shuffling it, for cross validation. :param dataset: The dataset to be splitted. :param folds: The number of folds to be created. :return: The datase...
import random from abc import ABCMeta, abstractmethod from collections import defaultdict, Counter, OrderedDict import math import numpy as np from gtd.log import indent from wge.rl import Trace def normalize_counts(counts): """Return a normalized Counter object.""" normed = Counter() total = float(sum(...
# # PySNMP MIB module FNCNMS (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FNCNMS # Produced by pysmi-0.3.4 at Wed May 1 13:14:13 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) ...
import random letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x' 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X', 'Y', 'Z'] numbers = ['0', '1', '2', '3', '4', '5', '6', ...
""" Determine an optimal list of hotel to visit. ``` $ python src/domain/solver.py \ -s "/Users/fpaupier/projects/samu_social/data/hotels_subset.csv ``` Note that the first record should be the adress of the starting point (let's say the HQ of the Samu Social) """ import argparse import numpy as...
import torch.nn as nn import math import torch.nn.functional as F __all__ = ['SENet', 'Sphere20a', 'senet50'] def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) # ...
# Create your views here. from django.conf import settings from django.core.cache import cache from django.db.models import Prefetch from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from rest_framework.generics import RetrieveAPIView, ListAPIView from question.m...
import os.path import random import multiprocessing import pandas as pd from utils import load_library, correct_full_sequence, get_precursor_indice, tear_library, flatten_list from mz_calculator import calc_fragment_mz def shuffle_seq(seq = None, seed = None): """Fisher-Yates algorithm. Modified from PECAN's deco...
#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2020-2021 Micron Technology, Inc. All rights reserved. import argparse import datetime import os import time import subprocess import sys import requests_unixsocket import yaml TZ_LOCAL = datetime.datetime.now(datetime.timezone.utc).ast...
import csv import six import io import json import logging from collections import Mapping from ..util import resolve_file_path logger = logging.getLogger(__name__) EPILOG = __doc__ class MappingTableIntakeException(Exception): """ Specific type of exception we'd like to throw if we fail in this stage du...
import numpy as np import torch import itertools from torch.autograd import Variable def getGridMask(frame, dimensions, num_person, neighborhood_size, grid_size, is_occupancy = False): ''' This function computes the binary mask that represents the occupancy of each ped in the other's grid params: ...
# Copyright 2021 The KaiJIN 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 ...
import anyio from anyio_mqtt import AnyIOMQTTClient import logging _LOG = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) logging.getLogger("anyio_mqtt").setLevel(logging.DEBUG) PAHO_LOGGER = logging.getLogger("paho") PAHO_LOGGER.setLevel(logging.DEBUG) async def main() -> None: _LOG.debu...
import time import random import numpy as np import torch from torchtuples import tuplefy, TupleTree def make_name_hash(name='', file_ending='.pt'): year, month, day, hour, minute, second = time.localtime()[:6] ascii_letters_digits = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' random_h...
# Copyright (c) Andrey Sobolev, 2019. Distributed under MIT license, see LICENSE file. GEOMETRY_LABEL = 'Geometry optimization' PHONON_LABEL = 'Phonon frequency' ELASTIC_LABEL = 'Elastic constants' PROPERTIES_LABEL = 'One-electron properties'
import django # this verifies local libraries can be packed into the egg def addition(first, second): return first + second
import sys import os import argparse import pandas as pd from fr.tagc.rainet.core.util.exception.RainetException import RainetException from fr.tagc.rainet.core.util.log.Logger import Logger from fr.tagc.rainet.core.util.time.Timer import Timer from fr.tagc.rainet.core.util.subprocess.SubprocessUtil import SubprocessU...
""" 参数及配置 """ # main.py small_dataset = False # 选择数据集规模 small_train_path = "../data/small_dataset/train.conll" # 小数据集-训练集 small_dev_path = "../data/small_dataset/dev.conll" # 小数据集-验证集 big_train_path = "../data/big_dataset/train" # 大数据集-训练集 big_dev_path = "../data/big_dataset/dev" # 大数据集-验证集 big_test_pat...
from cakechat.utils.data_structures import create_namedtuple_instance SPECIAL_TOKENS = create_namedtuple_instance( 'SPECIAL_TOKENS', PAD_TOKEN=u'_pad_', UNKNOWN_TOKEN=u'_unk_', START_TOKEN=u'_start_', EOS_TOKEN=u'_end_') DIALOG_TEXT_FIELD = 'text' DIALOG_CONDITION_FIELD = 'condition'
from models.models import Departamento
# -*- coding: utf-8 -*- """ Python implementation of Tanner Helland's color color conversion code. http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/ """ import math # Aproximate colour temperatures for common lighting conditions. COLOR_TEMPERATURES = { 'candle': 1900, 'sunrise': 2000, ...
# The MIT license: # # Copyright 2017 Andre Netzeband # # 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 limitation # the rights to use, copy, modify, merg...
# Generated by Django 2.2.5 on 2019-10-07 17:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0016_datetimes_to_dates'), ] operations = [ migrations.AlterField( model_name='preliminarycase', name='comp...
from pyvisdk.esxcli.executer import execute_soap from pyvisdk.esxcli.base import Base class IscsiNetworkportalIpconfig(Base): ''' Operations that can be performed on iSCSI Network Portal (iSCSI vmknic)'s IP configuration ''' moid = 'ha-cli-handler-iscsi-networkportal-ipconfig' def set(self, adapte...
# -*- coding: utf-8 -*- """Tests dict input objects for `tackle.providers.system.hooks.lists` module.""" from tackle.main import tackle def test_provider_system_hook_lists(change_dir): """Verify the hook call works properly.""" output = tackle('.', no_input=True) assert 'donkey' in output['appended_list...
from flask_wtf import FlaskForm from wtforms import StringField,TextAreaField,SubmitField,SelectField from wtforms.validators import Required class PitchForm(FlaskForm): title = StringField('Pitch title',validators=[Required()]) text = TextAreaField('Text',validators=[Required()]) category = SelectField('...
#!/usr/bin/env python """ ROS node implementing Rhinohawk global mission state. See rh_msgs.msg.State for a full description of the state data. The state node aggregates state from many different sources and makes it available to other nodes in the Rhinohawk System, particularly the controller node which is responsibl...
class Tuners(object): """Enum class for mapping symbols to string names.""" UNIFORM = "uniform" GP = "gp" GP_EI = "gp_ei" GP_EI_VEL = "gp_eivel"
# coding=utf-8 import re from jinja2 import Environment, PackageLoader class ViewModel(object): class Property(object): def __init__(self, name, type_name): super(ViewModel.Property, self).__init__() self.name = name self.type_name = type_name def __str__(sel...
import matplotlib.pyplot as plt import numpy as np from plotting import * def PID(x,I,dx,KP,KI,KD): u = -np.dot(KP,x)-np.dot(KI,I)-np.dot(KD,dx) return u def PID_trajectory(A,B,c,D,x0,dx0,KP,KI,KD,dt=1e-3,T=10,xdes=None,dxdes=None): """ For 2nd order system Ax + Bdx + c + Du and PID controller Ret...
""" Copyright (c) 2018 Intel Corporation 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 writin...
# # Copyright (c) 2021, NVIDIA CORPORATION. # # 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 ...
from sentence_transformers import SentenceTransformer, InputExample, losses from torch.utils.data import DataLoader #Define the model. Either from scratch of by loading a pre-trained model model = SentenceTransformer('distilbert-base-nli-mean-tokens') #Define your train examples. You need more than just two examples....
from ..core import Dimensioned, AttrTree try: import pandas from .pandas import DFrame # noqa (API import) except: pandas = None try: import seaborn from .seaborn import * # noqa (API import) except: seaborn = None from .collector import * # noqa (API import) def public(obj): i...
#! /bin/python3 import socket listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) listener.bind(('127.0.0.1', 8080)) listener.listen(0) print("[+] Esperando por conexiones") connection, addr = listener.accept() print("[+] Conexion de " + str(ad...
from collections import defaultdict, deque import math from .models import Node, Edge class Graph(object): def __init__(self): self.nodes = set() # Nodes models self.edges = defaultdict(list) # Edges models self.distances = {} # mimic Nodes model def add_node(self, valu...
from client.nogui import DirManager dm = DirManager() dm.run()
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright CNRS 2012 # Roman Yurchak (LULI) # This software is governed by the CeCILL-B license under French law and # abiding by the rules of distribution of free software. import numpy as np from scipy.constants import e, c, m_e, epsilon_0, k, N_A from scipy.constants impo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import humps import re def main(): comp = re.compile(r"^(0x[\da-f]+) ([\w \,]*) (\d)", re.M | re.I) match = None op_input = "utils/opcodes.txt" op_output = "src/op.rs" dis_output = "src/dis/mod.rs" asm_output = "src/asm/mod.rs" with open(o...
# Copyright 2019 Google Inc. 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 CustomVLCClass import serial import time import threading time.sleep(20) while True: def inputListener(): inputdata = input('0 to quit the first song, 1 to quit the second song') if(inputdata == '0'): if a.mediaplayer.is_playing() : a.pause() else: ...
import torch from kobart import get_kobart_tokenizer from transformers.models.bart import BartForConditionalGeneration class KoBART_title(): def __init__(self, ckpt_path="./n_title_epoch_3"): self.model = BartForConditionalGeneration.from_pretrained(ckpt_path).cuda() self.tokenizer = get_kobart_to...
from scripts.game_objects.game_object import GameObject from scripts.consts import IRON_SWORD, WOODEN_BOW class Weapon(GameObject): def __init__(self, game, type, damage, x, y): weapon_dict = {'iron_sword': IRON_SWORD, 'wooden_bow': WOODEN_BOW} super().__init__(game, weapon_dict[type], x, y, game....
# Copyright (c) 2014 ITOCHU Techno-Solutions Corporation. # # 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...
from __future__ import unicode_literals __all__ = ( 'Key', 'Keys', ) class Key(object): def __init__(self, name): #: Descriptive way of writing keys in configuration files. e.g. <C-A> #: for ``Control-A``. self.name = name def __repr__(self): return 'Key(%s)' % self....
import autograd import autograd.numpy as np import scipy as sp from copy import deepcopy import paragami from paragami.autograd_supplement_lib import grouped_sum import vittles import time def _validate(y, x): n_obs = x.shape[0] x_dim = x.shape[1] if len(y) != n_obs: raise ValueError( ...
import json import numpy as np import os.path as osp import warnings from collections import defaultdict from plyfile import PlyData from six import b from ..utils.point_clouds import uniform_sample from ..utils import invert_dictionary, read_dict from ..utils.plotting import plot_pointcloud from .three_d_object impo...
"""Voorstudie voor een DTD editor (wxPython versie) - not actively maintained """ import os,sys,shutil,copy from xml.etree.ElementTree import Element, ElementTree, SubElement import parsedtd as pd ELTYPES = ('pcdata','one','opt','mul','mulopt') ATTTYPES = ('cdata','enum','id') VALTYPES = ('opt','req','fix','dflt...
def register(mf): mf.overwrite_defaults({ "testvar": 42 }, scope="..notexistentmodule")
# <caret>
import os, sys, inspect # realpath() will make your script run, even if you symlink it :) cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) # use this if you want to include modules from a subfol...
from Core.Anlyst import anlyse from Core.URLs import WayUrl from Core.URLs import WebUrl from Test.NetWorkTest import WebUrlPostTest from Core.NetWork import VisitorWays from Core.NetWork import visit xpaths = ['//*[@id="form3"]/a/@href'] selector = '#form3 > a' def TestOfAnlyseByRegex(): url = "regex://a/b0" ...
import click from cortex.server import server from cortex.utils import logging # ----=========== CLI ===========---- @click.group() def cli(): pass @cli.command("run-server") @click.option("--host", "-h") @click.option("--port", "-p", type=int) @click.argument('publish_url') def run_server_cli(host, port, publis...
""" Account base class for holding Account information """ class Account: def __init__(self): self.employee_id: int self.user_name: str self.password: str
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(verbose...
import typing as T from dataclasses import dataclass from moonleap import Resource from titan.project_pkg.service import Tool @dataclass class SetupFile(Tool): pass @dataclass class SetupFileConfig(Resource): body: T.Union[dict, T.Callable] def get_body(self): return self.body() if callable(se...
import numpy as np from utils.tt_dataset import AgentType, TrajectoryTypeDataset from test_problems.u_grid_encoding import xy2mrx_v1 as xy2mrx from test_problems.risk_distances import dist2rt_v1 as dist2rt from test_problems.grid_encoding import rt2enc_v1 as rt2enc from utils import general as ge import scipy.optimize ...
""" **************************************************************************************************** :copyright (c) 2019-2021 URBANopt, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted ...
""" Generate training source and target domain records """ import os import csv import random import argparse def write_csv(path, lines): with open(path, 'w') as f: csv_writer = csv.writer(f, delimiter='\t') for i, (p, l) in enumerate(lines): csv_writer.writerow([i, l, p]) def read_...
# Copyright (c) 2021 Valerii Sukhorukov. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and ...
import cdat_info import cdms2 import numpy import unittest import sys PLOT = False if PLOT: from matplotlib import pylab as pl from mpl_toolkits.basemap import Basemap as bm class TestTasRegrid(unittest.TestCase): """ All test interpolate to the same grid """ def setUp(self): self.cl...
#!/usr/bin/env python # EVAPOR Workflow written in Python 3.6 in April 2020 by mswartz2@gmu.edu # This code will import text string, extract the emojis as list # report out the unique emojis and unique emoji attributes for the text # then for text analyze the structure of the content # and then delve into the emojis a...
# Generated by Django 2.2.13 on 2021-08-09 08:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0118_auto_20210809_1032'), ] operations = [ migrations.AlterField( model_name='reportcolumnpostfix', na...
""" Serialiser tests """ from datetime import datetime import unittest from zorp.serialiser import Serialiser class TestSerialiser(unittest.TestCase): """ Test the serialiser """ def __test_encode_decode(self, expected): """ Test that encoding and decoding a value results in ...
import torch import torch.utils.data as data_utils from torch.utils.data import DataLoader import torch.autograd as autograd import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable from torch.nn.parameter import Parameter from allennlp.modules.attention im...
from oscar.apps.offer import models class AlphabetRange(object): name = "Products that start with D" def contains_product(self, product): return product.title.startswith('D') def num_products(self): return None class BasketOwnerCalledBarry(models.Condition): name = "User must be ca...
# Generated by Django 2.1.7 on 2019-04-09 14:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0044_auto_20190409_1448'), ] operations = [ migrations.RemoveField( model_name='badgesp...
import requests from bs4 import BeautifulSoup blacklist = { "farms", "csa", "farmers-markets", "restaurants", "food-coops", "u-pick", "farm-stands", "others", "list"} city = '/locations/' wiki = f"https://www.localharvest.org/{city}" page = requests.get(wiki) soup = BeautifulSoup(page.text, "html.parser") for link in...
"""Common functions.""" import re from socket import getaddrinfo, AF_INET, AF_INET6, IPPROTO_TCP from datetime import timedelta def explode_datetime(datetime_str): """Extract days minutes and seconds from datetime (days, minutes, seconds). Example: "1d 3h 2m" returns {"days": "1", "hours": "3", "minutes": "...
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for, current_app, json from flask.ext.login import login_user, login_required, logout_user from app.users.models import Users from app.users.forms import LoginForm, RegisterForm, UserForm, PasswordForm, ResetPassForm, NewPassForm fr...
import argparse import os import zipfile def make_rel_archive(a_args): archive = zipfile.ZipFile("(Part 1) Engine Fixes.zip".format(a_args.name), "w", zipfile.ZIP_DEFLATED) def do_write(a_path): archive.write(a_path, "SKSE/Plugins/{}".format(os.path.basename(a_path))) def write_rootfile(a_extension): do_write("...
#!/usr/bin/env python ## Create Microsoft Test Server DRM keys, parse LAURL array ## python.exe RegisterDRM_MicrosoftTest.py > keys_microsofttest.json ## Aki Nieminen/Sofia Digital ## 2017-11-30/Aki: changed hexdecode to python3 ## 2017-08-21/Aki: initial release import sys, os, time, datetime, json, base64 f...
from .face_utils import align_crop_face_landmarks, compute_increased_bbox, get_valid_bboxes, paste_face_back from .misc import img2tensor, load_file_from_url, scandir __all__ = [ 'align_crop_face_landmarks', 'compute_increased_bbox', 'get_valid_bboxes', 'load_file_from_url', 'paste_face_back', 'img2tensor', 's...
import numpy as np def AdjHE_estimator(A,data, npc=0, std=False): # remove identifiers form y for linear algebra y = data.Residual # select PC columns PC_cols = [ col.startswith("PC") for col in data ] PCs = data.iloc[:, PC_cols] # If standardized AdjHE is chosen if (std == True) : ...
import os, sys, hashlib, argparse BLOCK_SIZE = 65536 def calculateFileHash(path): hasher = hashlib.md5() with open(path, 'rb') as targetFile: buffer = targetFile.read(BLOCK_SIZE) while len(buffer) > 0: hasher.update(buffer) buffer = targetFile.read(BLOCK_SIZE) retur...