content
stringlengths
0
894k
type
stringclasses
2 values
# -*- 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...
python
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('...
python
#!/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...
python
class Tuners(object): """Enum class for mapping symbols to string names.""" UNIFORM = "uniform" GP = "gp" GP_EI = "gp_ei" GP_EI_VEL = "gp_eivel"
python
# 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...
python
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...
python
""" 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...
python
# # 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 ...
python
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....
python
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...
python
#! /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...
python
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...
python
from client.nogui import DirManager dm = DirManager() dm.run()
python
#!/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...
python
#!/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...
python
# 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...
python
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: ...
python
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...
python
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....
python
# 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...
python
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....
python
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( ...
python
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...
python
"""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...
python
def register(mf): mf.overwrite_defaults({ "testvar": 42 }, scope="..notexistentmodule")
python
# <caret>
python
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...
python
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" ...
python
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...
python
""" Account base class for holding Account information """ class Account: def __init__(self): self.employee_id: int self.user_name: str self.password: str
python
# -*- 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...
python
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...
python
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 ...
python
""" **************************************************************************************************** :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 ...
python
""" 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_...
python
# 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 ...
python
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...
python
#!/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...
python
# 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...
python
""" 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 ...
python
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...
python
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...
python
# 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...
python
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...
python
"""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": "...
python
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...
python
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("...
python
#!/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...
python
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...
python
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) : ...
python
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...
python
import os import torch import numpy as np from sentence_transformers import SentenceTransformer from experiment.qa.evaluation import BasicQAEvaluation class QAEvaluationSBert(BasicQAEvaluation): def __init__(self, config, config_global, logger): super(QAEvaluationSBert, self).__init__(config, config_glo...
python
"""Test Home Assistant ulid util methods.""" import uuid import homeassistant.util.ulid as ulid_util async def test_ulid_util_uuid_hex(): """Verify we can generate a ulid.""" assert len(ulid_util.ulid_hex()) == 32 assert uuid.UUID(ulid_util.ulid_hex())
python
from flask import Flask, render_template, request, Response from Models import db, SensorData, CustomSensor from flask.json import jsonify from Arduino import serial_port from threading import Thread from Helpers import search_sensor from Constants import DataTypes import os.path db_path = os.path.join('sqlite://', o...
python
#basic program of finding the SECOND LARGEST VALUE among the given list of value #finding the RUNNER UP in other words #used map(),split(),sorted() #the sorted()function here creates a new set returns a sorted list of the specified iterable object. if __name__ == '__main__': #getting the number of scores you are g...
python
from collections import namedtuple ButtonOptions = namedtuple('ButtonOptions', ['activebackground', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'disabledforeground', 'font', 'foreground', 'highlightbackground', 'highlightcolor', ...
python
"""Constants for the Thruk Livestatus sensor integration.""" # This is the internal name of the integration, it should also match the directory # name for the integration. DOMAIN = "thruk_livestatus" HOST_COUNT = "Host count" NUM_SERVICES_CRIT = "Services CRITICAL" NUM_SERVICES_WARN = "Services WARNING" NUM_SERVICES_...
python
import decoder inp_fn = raw_input("Enter the file name to decode:") sp_fn_a = inp_fn.split('.') sp_fn_b = sp_fn_a[0].split('_') inp_fs = open(inp_fn,"r") out_fs = open("decoded_"+sp_fn_b[1]+'.'+sp_fn_b[2],"wb+") enc_ln = int(inp_fs.readline()) st_to_dec = inp_fs.readline() while st_to_dec!='': out_fs.write(decoder....
python
"""Plants tests"""
python
import time, sys, random from pygame import mixer from PyQt5.QtWidgets import QDialog, QApplication from PyQt5 import QtWidgets, QtCore from src.ui.controlPenalUI import Ui_controlPenal from src.songScreen import picWindow class controlPenal(QDialog): def __init__(self): super().__init__() ...
python
# 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 # distributed under t...
python
import sys import argparse import json import logging import os from TrainFace import TrainFace from InferFace import InferFace if __name__ == "__main__": # Read the input information by the user on the command line parser = argparse.ArgumentParser() parser.add_argument("--config_file", help="co...
python
class Solution(object): def defangIPaddr(self, address): """ :type address: str :rtype: str """ return address.replace(".", "[.]") if __name__ == '__main__': address = "0.0.0.0" obj = Solution() obj.defangIPaddr(address)
python
#!/usr/bin/env python # coding:utf-8 import os import sys current_path = os.path.dirname(os.path.abspath(__file__)) helper_path = os.path.join(current_path, os.pardir, os.pardir, os.pardir, 'data', 'launcher', 'helper') if __name__ == "__main__": python_path = os.path.abspath( os.path.join(current_path, os.pardi...
python
#!/usr/bin/python3 import argparse import getpass import glob import os import socket import subprocess import time import sys script_description = ( "Prepare current system for migrate attack, output XSS payload\n" "Requires to be run with sudo/root privs for writing files to system dirs" ) def is_port_op...
python
import typing from core import scriptercore class LinuxDisplayPwnedMsgBox(scriptercore.Scripter): AUTHOR: str = "Danakane" def __init__(self): super(LinuxDisplayPwnedMsgBox, self).__init__() self.__title__: str = "" self.__text__: str = "" self.customize({"title": "The title...
python
# -*- coding: utf-8 -*- """ Пример распаковки/упаковки контейнеров (cf/epf/ert) при помощи onec_dtools Функционал аналогичен C++ версии v8unpack Copyright (c) 2016 infactum """ import argparse import sys from onec_dtools import extract, build def main(): parser = argparse.ArgumentParser() group = parser.ad...
python
__author__ = "MetaCarta" __copyright__ = "Copyright (c) 2006-2008 MetaCarta" __license__ = "Clear BSD" __version__ = "$Id: VersionedPostGIS.py 496 2008-05-18 13:01:13Z crschmidt $" from FeatureServer.DataSource import DataSource from vectorformats.Feature import Feature from FeatureServer.DataSource.PostGIS import P...
python
import requests as reqs import base64 import logging import re import json # 调用淘宝识图请求接口,获取商品源和标签 def taobao_pic_recognize(pic_dir,pic_name,cookie): # with open(pic_dir+'/'+pic_name, "rb") as f: # # b64encode:编码,b64decode: 解码 # base64_data = base64.b64encode(f.read()) imagefile={ "file": (pic_n...
python
from flask import Flask, request, redirect from twilio.twiml.messaging_response import MessagingResponse import pandas as pd import datetime import pytz # the below import is only needed for forwarding the sms, in case the client sends KONTAKT from twilio.rest import Client account_sid = '###################...
python
from src.bert_classifier.model import Model from src.bert_classifier.fit import fit
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from telegram.ext import Updater, MessageHandler, Filters import traceback as tb import json import random import threading START_MESSAGE = (''' Loop message in chat / group / channel. add - /add message: add message to loop. list - /list: list message inside the loop....
python
# Copyright 2019 Google LLC. 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 law or a...
python
from setuptools import setup setup( name="backbones", version="0.1", description="Common neural network architectures implemented in PyTorch.", url="https://github.com/bentaculum/backbones", author="Benjamin Gallusser", author_email="benjamin.gallusser@epfl.ch", license="MIT", install_r...
python
from typing import List, Tuple, Callable, Optional import numpy as np import tweedie from gluonts.model.forecast import SampleForecast, QuantileForecast from scipy.optimize import fmin_l_bfgs_b from scipy.special import gammaln, factorial, psi from scipy.stats import norm, beta, gamma, nbinom, poisson from sklearn.pre...
python
import argparse import os import time from keystoneauth1 import loading from keystoneauth1 import session from heatclient import client _TERMINAL = [ 'CREATE_FAILED', 'CREATE_COMPLETE', 'UPDATE_FAILED', 'UPDATE_COMPLETE' ] _INTERVAL = 20 def get_session(): """Get a keystone session :returns...
python
from pydantic import BaseModel #fastapi接口的数据模型 class User(BaseModel): first_name: str last_name: str age: int class Config: orm_mode = True
python
import sys import getpass from mlflow.tracking.context.abstract_context import RunContextProvider from mlflow.entities import SourceType from mlflow.utils.mlflow_tags import ( MLFLOW_USER, MLFLOW_SOURCE_TYPE, MLFLOW_SOURCE_NAME, ) _DEFAULT_USER = "unknown" def _get_user(): """Get the current comput...
python
import numpy as np import torch from torch.utils.data import Dataset from torch.utils.data.dataloader import default_collate from fairseq.data.fairseq_dataset import FairseqDataset def sine(phase, amplitude, x): return np.sin(x + phase) * amplitude class SineDataset(Dataset): def __init__(self, split, phas...
python
import socket server = "localhost" #settings channel = "#domino" botnick = "firestorck_bot" print("Server : ", server) print("Channel : ", channel) print("Name : ", botnick) irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket print ("connecting to: "+server) irc.connect((server, 6667)) ...
python
import numpy as np import copy as cp DIRECTIONS = [np.array((0, 1)), np.array((1, 0)), np.array((1, 1)), np.array((0, -1)), np.array((-1, 0)), np.array((-1, -1)), np.array((1, -1)), np.array((-1, 1))] class State: def __init__(self, grid=None, previous_skip=False, side=2, master_side=2): if...
python
import os import glob import shutil import tempfile import numpy as np import common import features import folds from audio_toolbox import ffmpeg, sox from constants import * def normalize(input_file): temp_dir = tempfile.mkdtemp() transcoded_file = os.path.join(temp_dir, 'transcoded.flac') ffmpeg.tra...
python
import django_describer.actions import django_describer.datatypes import django_describer.permissions import django_describer.describers import django_describer.utils import django_describer.adapters name = "django_describer"
python
from ctypes import * from .jenv import * from . import Object from . import ClassUtils from . import Executable from . import String from . import Modifier class Method(Executable.Executable, Modifier.Modifier): _isInit = None _Class = None _getName = None _getReturnType = None _count = 0 def ...
python
"""Tests for the ResourceTracker class""" import errno import gc import os import pytest import re import signal import subprocess import sys import time import warnings import weakref from loky import ProcessPoolExecutor import loky.backend.resource_tracker as resource_tracker from loky.backend.context import get_con...
python
from abc import ABC, abstractmethod from datetime import datetime from typing import List, Optional, Tuple, Any, Dict, Iterable, Generator import yaml from smart_open import smart_open from blurr.core import logging from blurr.core.aggregate_block import BlockAggregate, TimeAggregate from blurr.core.errors import Pr...
python
from .base_requests import AnymailRequestsBackend, RequestsPayload from ..exceptions import AnymailRequestsAPIError from ..message import AnymailRecipientStatus from ..utils import get_anymail_setting class EmailBackend(AnymailRequestsBackend): """ Postal v1 API Email Backend """ esp_name = "Postal" ...
python
# encoding: utf-8 # module NationalInstruments.RFmx calls itself RFmx # from NationalInstruments.RFmx.InstrMX.Fx40, Version=19.1.0.49152, Culture=neutral, PublicKeyToken=dc6ad606294fc298 # by generator 1.145 # no doc # no imports # no functions # no classes # variables with complex values
python
from ..mime import GlueMimeListWidget, LAYERS_MIME_TYPE class TestGlueMimeListWidget(object): def setup_method(self, method): self.w = GlueMimeListWidget() def test_mime_type(self): assert self.w.mimeTypes() == [LAYERS_MIME_TYPE] def test_mime_data(self): self.w.set_data(3, 'tes...
python
# Generated by Django 2.0.5 on 2018-05-07 13:56 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Ticket', fields=[ ...
python
import torch import torch.nn.functional as F import random class NGDSAC: ''' Neural-Guided DSAC to robustly fit lines. ''' def __init__(self, hyps, inlier_thresh, inlier_beta, inlier_alpha, loss_function, invalid_loss): ''' Constructor. hyps -- number of line hypotheses sampled for each image inlier_thr...
python
import Signatures class Tx: inputs = None #input addreses outputs = None #output addreses sigs = None # signatures reqd = None #required signatures that are not inputs def __init__(self): self.inputs = [] self.outputs = [] self.sigs = [] self.reqd = [] def add_inp...
python
from rest_framework import serializers from rest_framework.fields import SerializerMethodField from .models import content_choice, visibility_choice from .models import Post as Post from backend.settings import SITE_ADDRESS from author.serializers import AuthorSerializer from comment.serializers import ChoiceField, Co...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import time import requests from bs4 import BeautifulSoup session = requests.session() session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0' words = [] for page in range(1, 94+1): if pa...
python
import torch import torch.nn as nn from einops.layers.torch import Rearrange # This model is modified from https://github.com/lucidrains/vit-pytorch class ViT(nn.Module): def __init__(self, image_size, patch_size, dim, transformer, num_classes, channels=3, joint=True): super().__init__() num_patch...
python
import os import signal import asyncio import datetime import json import logging import edgefarm_application as ef from schema_loader import schema_read # # Using the ads_producer/encoder, you can publish a message towards ADS # ads_producer = None ads_encoder = None async def temperature_handler(msg): """This ...
python
import datetime import unittest import isce from isceobj.Orbit.Orbit import StateVector class StateVectorTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testEqualCompare(self): """ Test that __cmp__ returns true when the times are the s...
python
"""Batching Lambda function - puts all S3 objects into SQS to be re-analyzed.""" # Expects the following environment variables: # BATCH_LAMBDA_NAME: The name of this Lambda function. # BATCH_LAMBDA_QUALIFIER: The qualifier (alias) which is used to invoke this function. # OBJECTS_PER_MESSAGE: The number of S3 obje...
python
from cmanager import CreditManager
python
# -*- coding: utf-8 -*- import ldap #import ldap.modlist as modlist from brie.config import ldap_config from brie.lib.log_helper import BrieLogging from brie.model.ldap import Groupes class Groups(object): __groups = list() def __init__(self, groups): self.__groups = groups #end def def __g...
python