content
stringlengths
5
1.05M
from ._BoxBoundsCoercion import BoxBoundsCoercion from ._Coercion import Coercion from ._MaskBoundsCoercion import MaskBoundsCoercion
class TrainingState: def __init__(self): """ A Structure containing states to be passed to callbacks """ # Will increment after each epochs self.current_epoch = 0 # Will increment after each batch self.current_batch = 0 # last execution was train or ev...
# -*- coding: iso-8859-1 -*- """ MoinMoin - makecache script @copyright: 2008 MoinMoin:ReimarBauer @license: GNU GPL, see COPYING for details. """ from MoinMoin import caching from MoinMoin.Page import Page from MoinMoin.script import MoinScript from MoinMoin.stats import hitcounts class PluginScript(MoinScript): ...
from typing import Dict, Optional from asyncpg.exceptions import UniqueViolationError from app.database.schema import User, UserToken async def get_user(query: Dict) -> Optional[User]: """Gets user from database.""" user = await User.objects.get_or_none(**query) return user async def create_user(user)...
#importing the libraries import numpy as np import cv2 from collections import deque from color_selector import color_detector import time import os #from record import last_frame # calling the colour function color_detector() # color_arr() bpoints = [deque(maxlen = 512)] gpoints = [deque...
""" .. UIExample:: 100 from flexx import app, ui # A red widget class Example(ui.Widget): CSS = ".flx-example {background:#f00; min-width: 20px; min-height:20px}" """ import json import threading from .. import react from ..app import Pair, get_instance_by_id from ..app.serialize import...
from django.contrib import admin from .models import Note @admin.register(Note) class NoteAdmin(admin.ModelAdmin): pass
from hyperlpr_py3 import pipline as pp import hyperlpr_py3.config as hyperConfig import cv2 import sys import os debugInfo = hyperConfig.configuration["global"]["debug"] testPath = hyperConfig.configuration["detectTest"]["detectPath"] outPath = hyperConfig.configuration["detectTest"]["outputPath"] def detectPlateTe...
''' from pysnmp.hlapi import * errorIndication, errorStatus, errorIndex, varBinds = next( setCmd(SnmpEngine(), CommunityData('public'), UdpTransportTarget(('192.168.61.6', 161)), ContextData(), ObjectType(ObjectIdentity('LUXL-POE-MIB', 'luxlPoeConfigInterfaceParamMode', ...
""" Provide CouchDB utility functions. """ import os import yaml import couchdb from cloudly.decorators import Memoized import cloudly.logger as logger from cloudly.aws import ec2 log = logger.init(__name__) @Memoized def get_server(hostname=None, port=None, username=None, password=None, protocol=N...
# # This file is part of CasADi. # # CasADi -- A symbolic framework for dynamic optimization. # Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, # K.U. Leuven. All rights reserved. # Copyright (C) 2011-2014 Greg Horn # # CasADi is free software; you can...
# Generated by Django 2.0.4 on 2018-04-12 12:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('text', '0004_details_slug'), ] operations = [ migrations.AddField( model_name='details', name='text_color', ...
from unittest import mock import pytest from django.contrib.auth.models import User from django.db import DEFAULT_DB_ALIAS from django.test.utils import override_settings from dj_anonymizer.utils import import_if_exist, truncate_table @pytest.mark.parametrize('path, expected', [ ('hello', False), ('base', T...
import autolens as al def tracer_generator_from_aggregator(aggregator): return aggregator.map(func=tracer_from_agg_obj) def tracer_from_agg_obj(agg_obj): output = agg_obj.output phase_attributes = agg_obj.phase_attributes most_likely_instance = output.most_likely_instance galaxies = most_likely...
# Author: 14281055 Liheng Chen CIT BJTU # File Name: NVDVulnInfoCrawler.py import re import os import bs4 import xlrd import xlwt from xlutils.copy import copy import Repository def write_workbook(vuln_detail_dict, save_path, row): r_workbook = xlrd.open_workbook(save_path, formatting_info=True) w_workbook =...
"""Class to describe MySQL backup copy""" import json from .periodic_copy import PeriodicCopy from .exceptions import WrongInputData class MySQLCopy(PeriodicCopy): # pylint: disable=too-many-instance-attributes """ Instantiate a MySQL copy. :param host: Hostname where the backup was taken from. :typ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Speciallan import os anno_path = '../../data/VOCdevkit/SAR-Ship-Dataset/dataset_voc' main_path = '../../data/VOCdevkit/SAR-Ship-Dataset/ImageSets/Main' train_list = os.listdir(anno_path + '/train/Annotations') test_list = os.listdir(anno_path + '/test/Annotations...
#!/usr/bin/env python # encoding: utf-8 def most_common(lst): s = set(lst) return max(s, key=lambda x: lst.count(x)) def POSEnsemble(lst): ret = [] for i in range(len(lst[0])): ret.append(most_common([l[i] for l in lst])) return ret
"""distutils.errors Provides exceptions used by the Distutils modules. Note that Distutils modules may raise standard exceptions; in particular, SystemExit is usually raised for errors that are obviously the end-user's fault (eg. bad command-line arguments). This module safe to use in "from ... import *" mode; it on...
# -*- coding:ascii -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 9 _modified_time = 1389308004.184105 _enable_loop = True _template_filename = 'C:\\myStuff\\calculator\\styles/calc.cssm' _template_uri = 'calc.cssm' _source_...
from setuptools import setup, find_packages with open("README.md") as f: readme = f.read() with open("LICENSE") as f: license = f.read() setup( name="gadi", version="0.1.0", description="Zugänglichere Versionen der Daten von gesetze-im-internet.de", long_description=readme, author="Niko ...
from pysc2.env import sc2_env from pysc2.lib import features from pysc2.agents import base_agent from pysc2.lib import actions from absl import app import numpy as np import torch MAPNAME = 'MoveToBeacon' APM = 0 APM = int(APM / 18.75) UNLIMIT = 0 VISUALIZE = False REALTIME = True if REALTIME : REALTIME_GAME_L...
import sqlite3 import pytest from ddht.v5_1.alexandria.advertisement_db import create_tables @pytest.fixture async def alice_alexandria_client(alice, alice_network): async with alice.alexandria.client(alice_network) as alice_alexandria_client: yield alice_alexandria_client @pytest.fixture async def bo...
import json import uuid from time import sleep import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry class Api: def __init__(self, hostname): self.timeout = 4 self.hostname = hostname self.cookies = {} # user def register...
"""Module used for creating the "urls.json" file""" import json import pathlib import discord from more_itertools import chunked __all__ = ['upload_images', 'save_image_urls', 'get_card_image_file', 'get_card_image_url'] _CARD_IMG_PATH = pathlib.Path('data/images/cards') _CARD_IMG_URLS_PATH = _CARD_IMG_PATH / 'urls...
import tslearn import numpy as np import pandas as pd from tslearn.preprocessing import TimeSeriesScalerMinMax from tslearn.piecewise import PiecewiseAggregateApproximation as PAA import matplotlib.pyplot as plt import os, argparse import json ap = argparse.ArgumentParser() ap.add_argument("--dimrec", type = int, choi...
# in sentence = 'hello' print('hello' in sentence)
import objects import ledmatrixdrawer import object_playground import points # import random_blocks import rgbleddrawer import controller import pygame import numbertoblock import datetime import Pong_collisions import gamespeed import time import random import Ball_Steuerung def titlescreen(rgb:rgbleddrawer.RgbLedDr...
from google_images_download import google_images_download import json from PIL import Image import os import time import tensorflow as tf def verify_image(img_file, sess): # test image try: v_image = open(img_file, 'rb') return sess.run(tf.image.is_jpeg(v_image.read())) # is valid ...
import datetime from propagators.base import Propagator from astropy.coordinates import EarthLocation, GCRS from astropy.time import Time from astropy import units as u from simpy.core import Environment from typing import ( List, Dict, Tuple, Any, Iterator, Optional, Type, Callable, ...
from tkinter import Tk , Label , Button , PhotoImage; from tkinter.ttk import Progressbar; from tkinter.filedialog import asksaveasfile from threading import Thread; from os import remove , fdopen; from sys import getsizeof; from tempfile import mkstemp; from time import time , sleep , strftime , gmtime; import wave; i...
"""Utilities for genshin.py.""" from . import geetest from .concurrency import * from .ds import * from .fs import * from .logfile import * from .uid import *
# Copyright 2016 Canonical Ltd # # 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, s...
import random import speech_recognition as sr import time from .transcribe import recognize_speech_from_mic def test_speech_recognition(): # set the list of words, maxnumber of guesses, and prompt limit WORDS = ["apple", "banana", "grape", "orange", "mango", "lemon"] NUM_GUESSES = 3 PROMPT_LIMIT = 5 ...
from enum import IntEnum class DataSetType(IntEnum): RAW = 0 FILE = 1 ABBYY = 2 PAGEXML = 3 HDF5 = 4 EXTENDED_PREDICTION = 5 GENERATED_LINE = 6 def __str__(self): return self.name @staticmethod def from_string(s): try: return DataSetType[s] ...
#!/usr/bin/python import pypresenter.slide class slide3(pypresenter.slide): def __init__(self): super(self.__class__, self).__init__('center') def content(self, window=None): return 'pyconfig DSL (Domain Specific Language)' def draw(self, window): self.displayText(window, self.cont...
#!/usr/bin/env python # -*- coding: utf-8 -*-import unittest import unittest import json from signature import MTSigner class TestSignature(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testSign(self): fo = open("../sample.txt", "r") str = fo...
# Copyright 2021 aaaaaaaalesha <sks2311211@mail.ru> import unittest from src.stack import Stack class StackTestCase(unittest.TestCase): def test_stack_empty(self): stack = Stack() self.assertTrue(stack.empty()) stack.push(1) self.assertFalse(stack.empty()) stack.push(2)...
_base_ = ['../ld/ld_r18_gflv1_r101_fpn_coco_1x.py'] model = dict( pretrained='torchvision://resnet50', output_feature=True, backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=...
from mpi4py import MPI from time import perf_counter as gettime import numpy import sys from contextlib import contextmanager class Profiler: def resettime(self): self.t0 = gettime() def setbarrier(self, inoption): self.timerbarrier = inoption def setmpicommunicator(self, inmpicommunicat...
import torch import torchvision import torchvision.transforms as transforms import math import time # How many models (==slaves) K=10 # train K models by Federated learning # each iteration over a subset of parameters: 1) average 2) pass back average to slaves 3) SGD step # initialize with pre-trained models (better ...
import os import sys import yaml repos = {} config = { "token": os.environ["GITHUB_TOKEN"], "repos": repos, } repos["nightly.link"] = { "queries": [("https://nightly.link", "-path:.github/workflows")], "min_stars": 8, } repos["nightly.link in workflows"] = { "queries": [("https://nightly.link", "...
# -*- coding: utf-8 -*- # Store a person’s name in a variable, and print a message # to that person. Your message should be simple, such as, “Hello Eric, would you like to learn some Python today?” name = 'Ross' print('Hello ' + name + ', would you like to learn some Python today?')
""" Enunciado Faça um programa que peça para o usuário digitar um número n e imprima uma lista com todos os números de 0 a n-1. Exemplo: se o usuário digitar 5, o programa deve imprimir [0, 1, 2, 3, 4] """ lista = [] numero = int(input("Digite um número inteiro: ")) c = 0 while c < numero: lista.append(c) c =...
import sys sys.path.append('../') sys.path.append('../../') from dquant.util import Util import os import asyncio, collections import json, time import logging import hashlib import queue from asyncio import AbstractEventLoop from dquant.config import cfg from dquant.constants import Constants from dquant.markets.mark...
from collections import OrderedDict, defaultdict import os import numpy as np from env.tasks import HomeServiceTaskSampler, HomeServiceTaskType from experiments.home_service_base import HomeServiceBaseExperimentConfig from PIL import Image import argparse import torch import torch.backends.cudnn as cudnn import pickle...
""" The SunEquation class is used approximately calculate the sunset and sunrise times using the Sunrise Equation found on Wikipedia. """ import math import logging # from datetime import datetime, timezone import datetime import pytz from tzlocal import get_localzone class SunEquation: """ Used ...
import time import unittest from cdn_origin.origin import Origin from cdn_origin.origin_set import OriginSet class TestOriginSet(unittest.TestCase): def upload_dummy_1(self, dest_name: str, data: bytes, job_types: str, info: None): print('upload_dummy_1', dest_name, data, job_types, info) time.sle...
# -*- coding: UTF-8 -*- # @File: multiliteral.py # @Author: SCERush # @Contact: 1037920609@qq.com # @Datetime: 20/7/5 17:30 # @Software: PyCharm """ 文件说明:multiliteral密码 """ import re # 字母表 keywordList = "ABCDEFGHIKLMNOPQRSTUVWXYZ" def removePunctuation(text): filter = '[^A-Z]' return re.su...
import os import re import datetime import dateutil.parser import configparser import numpy as np import astropy.io.fits as fits from astropy.table import Table from ...utils.misc import extract_date from ..common import load_obslog, load_config from .common import print_wrapper, get_ccd_geometry from .reduce import ...
#!/usr/bin/env python ''' test_brozzling.py - XXX explain Copyright (C) 2016-2018 Internet Archive 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 U...
import pytest from keras.datasets import mnist import numpy as np @pytest.fixture def mnist_dataset(): (X_train, _), (X_test, _) = mnist.load_data() X_train = X_train.astype('float32') / 256. X_test = X_test.astype('float32') / 256. X_train = X_train.reshape((len(X_train), np.prod(X_train.shape[1:])))...
# Generated by Django 2.2.7 on 2019-12-19 14:25 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('employees', '0024_auto_20171229_1156'), ] operations = [ migrations.AddField( model_name='userdata...
from flask.globals import current_app from infosystem.celery import celery, decide_on_run from infosystem.common import exception from infosystem.subsystem.user.email import TypeEmail @decide_on_run @celery.task(autoretry_for=(exception.NotFound,), default_retry_delay=5, retry_kwargs={'max_...
import os import pytesseract import logging from PIL import Image LOGGER = logging.getLogger(__name__) __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) # Get CAPTCHA image & extract text class CaptchaHandler: def __init__(self): self.filename = 'solved_captcha.png' ...
#!/usr/bin/env python2 # Copyright (c) 2016 Jonathan Broche (@g0jhonny) from lib.logger import * from lib.soupify import * from lib.workbench import * from lib.crawler import * import os, argparse, sys, time parser = argparse.ArgumentParser(description='InSpy - A LinkedIn enumeration tool by Jonathan Broche (@g0jhonn...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # SPDX-License-Identifier: MIT # Copyright (C) 2020-2021 Mobica Limited """Create team file basing on specified project members""" # Standard library imports import sys import json # Third party imports import jsonschema # Project imports import cjm import cjm.cfg imp...
#!/usr/bin/env python import unittest from pymodbus.compat import IS_PYTHON3 if IS_PYTHON3: from unittest.mock import patch, Mock else: # Python 2 from mock import patch, Mock from pymodbus.client.async.twisted import ( ModbusClientProtocol, ModbusUdpClientProtocol, ModbusSerClientProtocol, ModbusTcpClientP...
import pandas as pd from sklearn.model_selection import train_test_split FEATURES = ["lepton_pT", "lepton_eta", "lepton phi", "missing_energy_magnitude", "missing_energy_phi", "jet_1_pt", "jet_1_eta", "jet_1_phi", "jet_1_btag", "jet_2_pt", "jet_2_eta", "jet_2_phi", "jet_...
import io import json import pytest from rubrik_polaris.rubrik_polaris import PolarisClient BASE_URL = "https://rubrik-se-beta.my.rubrik.com/api" def util_load_json(path: str) -> dict: """Load a json to python dict.""" with io.open(path, mode='r', encoding='utf-8') as f: return json.loads(f.read()) ...
import torch __author__ = 'Andres' def calc_gradient_penalty_bayes(discriminator, real_data, fake_data, gamma): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") batch_size = real_data.size()[0] alpha = torch.rand(batch_size, 1, 1, 1) alpha = alpha.expand(real_data.size()).to(devi...
# Imports from 3rd party libraries import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output # Imports from this application from app import app # 1 column layout # https://dash-bootstrap-components.opensource.f...
import hashlib with open('data/day4.txt') as f: data = f.read() number = 1 md5_hash = hashlib.md5(data + str(number)) while md5_hash.hexdigest()[0:6] != '000000': number += 1 print number md5_hash = hashlib.md5(data + str(number)) print 'Solution: {0}'.format(number)
def prime(num): flag = 0 counter = 2 while counter <=(num**0.5): if num % counter== 0: break counter +=1 else: return True def sum_of_primes(num): sum1 = 0 for i in range(2,num): if prime(i): sum1+=i return sum1 a = sum_of_primes(2000000) print(a)
import warnings import unittest from itertools import product import random import torch from torch.testing._internal.common_utils import \ (TestCase, run_tests, do_test_empty_full, TEST_NUMPY, suppress_warnings, IS_WINDOWS, torch_to_numpy_dtype_dict, slowTest) from torch.testing._internal.common_device_type...
from typing import Dict class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeZeroSumSublists(self, head: ListNode) -> ListNode: curr = dummy = ListNode(0) dummy.next = head prefix_sum = 0 seen = {} # type: Dict[int,...
#!/usr/bin/python import tlsvld import scipy import numpy import math U = tlsvld.array([[0.37471362,-0.07411912,-0.0379023],[-0.07411912,0.39010298,-0.03240841],[-0.0379023,-0.03240841,0.33057791]]) V = tlsvld.array([[0.38484156,-0.06933809,-0.04994903],[-0.06933809,0.41376374,-0.03275701],[-0.04994903,-0.03275701,0.3...
import os import re from tqdm import tqdm import tensorflow as tf from erinn.python.generator import PredictGenerator from erinn.python.utils.io_utils import read_config_file, get_pkl_list, read_pkl, write_pkl # setting config_file = os.path.join('..', 'config', 'config.yml') config = read_config_file(config_file) ...
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Author : phant0ms # @Time : 2020/8/4 15:12 # @File : session.py from app.core.config import settings from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session engine = create_engine(settings.SQLALCHEMY_...
import numpy as np import pandas as pd from preprocessing.InputHelper import transformLabels_aux from collections import Counter def plotHistogram(valueList, caption): freqs = pd.Series(valueList).value_counts() print (caption) print (freqs) #freqs.plot(kind='bar') #plt.suptitle(caption) #plt....
# # PySNMP MIB module IANA-FINISHER-MIB (http://pysnmp.sf.net) # ASN.1 source http://mibs.snmplabs.com:80/asn1/IANA-FINISHER-MIB # Produced by pysmi-0.0.7 at Sun Feb 14 00:15:44 2016 # On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose # Using Python version 3.5.0 (default, Jan 5 2016, 17:11:5...
import random from random import randint from datetime import datetime, timedelta f=open('myDataStock.csv','w',encoding='UTF-8') food = ["chicken", "bread", "lettuce", "potato", "carotte", "rice", "pork", "mushroom", "tomato", "egg", "beef"] x = datetime.now() id = 0 for i in range(365): orderDay = str(x...
# vim: sw=4:ts=4:et:cc=120 # # data models used to communicate over HTTP # import datetime import json import uuid from typing import Optional, Any, Union from ace.time import utc_now from pydantic import BaseModel, Field from pydantic.json import pydantic_encoder class DetectionPointModel(BaseModel): """Repr...
from PyGARV import * """ This class implements a Genetic Algorithm to maximize the following function. max f = 20x + 60y subject to: 30x + 20y >= 2700 5x + 10y <= 850 x + y >= 95 x, y >= 0 """ class Example(PyGARV): def __init__(self): #You can find out what each parameter does #looking at the ...
#!/usr/bin/env python # created by Bruce Yuan on 17-11-27 from inspect import signature from pylimit.limit_error import LimitError from pylimit.list_limit import check_type from pylimit.type_limit import type_limit import functools def tuple_limit(**info): """ 这个其实和 list_limit基本是一样的,可是需要考虑到 tuple 基本是不会变化的 ...
# app.py # also importing the request module from flask import Flask, render_template, request import sys,os import configparser import dbus app = Flask(__name__) app.config["CACHE_TYPE"] = "null" dir = os.path.dirname(__file__) filename = os.path.join(dir, '../../config/rgb_options.ini') # Configuration for the ma...
"""A thread-based worker pool.""" from __future__ import absolute_import, division, print_function __metaclass__ = type import collections import threading import time import socket import warnings from six.moves import queue from jaraco.functools import pass_none __all__ = ('WorkerThread', 'ThreadPool') class...
from __future__ import unicode_literals import logging import requests import string import urllib2 import urlparse from mopidy_podcast.directory import PodcastDirectory from mopidy_podcast.models import Ref from . import Extension _TAG_PATH = '/api/2/tag/{tag}/{count}.json' _TAGS_PATH = '/api/2/tags/{count}.json' ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### # WARNING: Generated code! # # ************************** # # Manual changes may get lost if file is generated again. # # Only code inside the [MANUAL] ta...
import luz import torch luz.set_seed(123) def get_dataset(size): x = torch.rand(10) y = torch.tensor([0.0, 0.0, 0.0, 1.0, 0.0]) d = luz.Data(x=x, y=y) return luz.Dataset([d] * size) class Net(luz.Model): def __init__(self): super().__init__() self.lin = torch.nn.Linear(10, 5) ...
#!/usr/bin/env python from __future__ import print_function import os,sys,argparse,logging,time import getpass parser = argparse.ArgumentParser() parser.add_argument("brokeraddr",type=str,help="Broker Address") parser.add_argument("-l","--logfile",type=str, default=None, help="where the log file is...
# -*- coding=utf-8 -*- """{{cookiecutter.project_name}} core module.""" def get_emojis(): """Return a dict of emojis.""" return dict(snek="🐍", rabit="🐰", monky="🐒")
"""empty message Revision ID: 444d4749dfa1 Revises: 16f0ba32110a Create Date: 2021-10-14 06:23:17.102819 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '444d4749dfa1' down_revision = '16f0ba32110a' branch_labels = None depends_on = None def upgrade(): # ...
import pytest from pytest_djangoapp.configuration import Configuration def test_configration(pytestconfig): settings = Configuration.get() settings[Configuration._KEY_APP] = 'some' assert Configuration.get_combined(pytestconfig) settings[Configuration._KEY_APP] = '' assert Configuration.get_co...
from pydriller.domain.developer import Developer def test_eq_dev(): d1 = Developer("Davide", "s.d@gmail.com") d2 = Developer("Davide", "s.d@gmail.com") d3 = Developer("Davide", "s.d@gmail.eu") d4 = None assert d1 == d1 assert d1 == d2 assert d1 != d3 assert d1 != d4
from django.contrib import admin from requestHandler.models import User, Song, SystemSetting admin.site.register(User) admin.site.register(Song) admin.site.register(SystemSetting)
import redis from settings import REDIS_URL from rq import Worker, Queue, Connection listen = ['default'] conn = redis.from_url(REDIS_URL) if __name__ == '__main__': with Connection(conn): worker = Worker(list(map(Queue, listen))) worker.work()
from uio import *
""" This problem was asked by Amazon. Given a pivot x, and a list lst, partition the list into three parts. The first part contains all elements in lst that are less than x The second part contains all elements in lst that are equal to x The third part contains all elements in lst that are larger than x Ordering with...
def get_hour(epoch_seconds): return epoch_seconds // 3600 def get_minutes(epoch_seconds): return (epoch_seconds // 60) % 60 def get_seconds(epoch_seconds): return epoch_seconds % 60 def time_from_utc(utc_offset, utc_zero): return utc_offset + utc_zero def get_time(hour, minutes, seconds, time_type, ...
import os from typing import List import numpy as np import pandas as pd from pandas.core.groupby import DataFrameGroupBy from ..indicators import AbstractIndicator from ..domain import StockPrice, Portfolio from ..converters import utils class StockFrame(): def __init__(self, **kwargs) -> None: self.df: ...
from django.conf import settings from django.contrib.postgres.fields import JSONField from django.db import models from mptt.fields import TreeForeignKey from mptt.models import MPTTModel from publications.models import Platform class Organization(MPTTModel): ext_id = models.PositiveIntegerField( unique...
# Dylan Connors import re def get_planet_names(content:str) -> str: pattern = re.compile("\"BodyName\":\"(.+?)\"") result = pattern.findall(content) names = [] if result: for r in result: names.append(r) return names
#!/usr/bin/env python3 # This script is used to run the cluster pool reservation system import sys import traceback from clusterpool.main import main if __name__ == '__main__': sys.exit(main())
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from __future__ import with_statement from txtorcon.interface import IAddrListener from txtorcon.util import maybe_ip_addr from twisted.internet.interfaces import IReactorTime ...
import os import requests from astropy.io import fits import h5py from catkit.hardware.FourDTechnology.Accufiz import Accufiz from catkit.interfaces.Instrument import SimInstrument class PoppyAccufizEmulator: def __init__(self, optics, *args, status_code=200, **kwargs): super().__init__(*args, **kwargs...
# -*- coding: utf-8 -*- ############# # # Copyright - Nirlendu Saha # # author - nirlendu@gmail.com # ############# def array_compaction(arr): """ Returns a list with unique elements in it """ compact_array = [] # Index always points to the last element of the compact_array. Since compact_array is [] initially, ...
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021 # by the softwar...
import subprocess from unittest import mock import pytest from lektorium.repo.local.storage import AWS, GitLab, GitlabStorage, GitStorage @pytest.mark.asyncio async def test_gitlabstorage(tmpdir): remote_dir = tmpdir / 'remote' local_dir = tmpdir / 'local' remote_dir.mkdir() local_dir.mkdir() su...