content
stringlengths
5
1.05M
''' Copyright 2013 Cosnita Radu Viorel 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, publish, distribute...
#!/usr/bin/python from idaapi import * import idc import idautils def lookup_str_in_func(func): found = [] func_name = idc.get_func_name(func) addrs = list(idautils.FuncItems(func)) # get list of all the address for line in addrs: dism = idc.generate_disasm_line(line, 0) if input_str in dism: find...
import json import yaml import copy from collections import abc import hcl # dd = {"name": "joe", "info": {"age": [5, 12, 42], "gender": {"type": "male"}, "accidents": [{"name": "Thursday"}, {"height": "six 2"}, {"color": "blue", "eyes": "brown"}]}, 'status': 'ACTIVE', 'streamspec': {'StreamEnabled': True, 'StreamVi...
#! /usr/bin/python3 # -*- coding: utf-8 -*- # # delete/riak_delete.py # # Sep/22/2015 # ---------------------------------------------------------------- import sys # sys.path.append ('/var/www/data_base/common/python_common') from curl_get import curl_delete_proc # --------------------------------------------------...
from components.fov import is_in_fov class BasicMonster(): def take_turn(self, target, fov, game_map, entities): results = [] monster = self.owner if is_in_fov(fov, monster.x, monster.y): if monster.distance_to(target) >= 2: monster.move_towards(target.x, target...
#! /bin/env python from collections import OrderedDict import six _TASK_STATUS_STRINGS = OrderedDict( [ ("create", ("creating", "created")), ("initialize", ("initializing", "initialized")), ("update", ("updating", "updated")), ("finalize", ("finalizing", "finalized")), ] ) _TA...
import matplotlib.pyplot as plt import numpy as np import torch from train_old import train_old from train import train params = { 'seed': 1234, 'lr': 2e-2, 'batch_size': 20, 'training_batches': 200, } history_loss_euclidean = train_old(params, gradient_type='euclidean') history_loss_quasi_diagonal_...
import numpy as np import os import pandas as pd import torch import torch.nn as nn import utils from torch.utils.data import Dataset, DataLoader from models import rnn import math from tqdm import tqdm from utils.utils import TestSetloader PATH_submission_example = r'D:\dataset\2021智慧農業數位分身創新應用競賽\org\submission.csv' ...
""" .. Copyright (c) 2014-2017, Magni developers. All rights reserved. See LICENSE.rst for further information. Module providing functionality for building a hierarchical object-structure. The reading of an .mi file is logically separated into four steps of which the functionality provided by this module ...
aktivirao = _State(0) weight = 8 def run(): if not State.goldenium_activated.val: return False x,y=coord('goldenium') #r.goto(*coord('goldenium')) if not pathfind(x-16,y+8,-1): return False r.absrot(-90) napgold(2) sleep(0.3) pump(2,1) # Implementirati stak umesto ovoga r.speed(60) r.forward(96) ...
from relationship import Relationship __version__ = '0.0.1'
from numpy import loadtxt from nltk.corpus import stopwords from nltk.tokenize import sent_tokenize, word_tokenize import nltk nltk.download('stopwords') nltk.download('punkt') # configure nltk with stop words stopWords = set(stopwords.words('english')) # load additional stopwords additionalWords = loadtxt("words.dat...
from ..messages import MsgHeader from dataclasses import dataclass @dataclass class MsgBase: header: MsgHeader def __init__(self, msg_bytes: bytes): self.header = MsgHeader(msg_bytes)
from .test_default_generator import * from .test_generated_report_api import * from .test_generated_reports import * from .test_report import * from .test_report_api import * from .test_trip_summary_generator import *
from itertools import product class NonexistentClue(BaseException): pass class NoSolution(BaseException): pass class WrongLengthAnswer(BaseException): pass RED = "\033[31m" DEFAULT = "\033[0m" class Solver: def __init__(self, grid): self.grid = grid self.clue_desc = {} self....
from typing import List from typing import Dict from typing import Callable from typing import Union import math import random from networkx import Graph from networkx import pagerank_scipy as pagerank from .sentence import Sentence from .utils import parse_text_into_sentences, parse_candidates_to_sentences from .u...
# -*- coding: utf-8 -*- # Copyright 2017 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Baselines for user/group tests.""" from __future__ import print_function from chromite.lib import cros_collections # firewal...
# Artificial Neural Network # Part 1 - Data preprocessing # Import Libraries import numpy as np import pandas as pd # Import Dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values # :-1 doesn't include the last index which in this case is the DV y = dataset.iloc[:, 13].value...
# -*- coding: utf-8 -*- import os, re, shutil CLEAN_REGEX = re.compile("(.+)\s*\(.+\)", re.IGNORECASE) IGNORE = ["libobjc.A.dylib", "libSystem.B.dylib", "/System/Library/Frameworks", "/usr/lib/system/"] def checkIgnore(path): for elm in IGNORE: if path.find(elm) != -1: return True ...
from selenium import webdriver import time # http://httpbin.org/get with open('ip.txt') as f: lines = (line.strip() for line in f) ip = list(lines) with open('user_agent.txt') as f: lines = (line.strip() for line in f) user_agent = list(lines) # 添加配置 options = webdriver.ChromeOptions() options.add_ar...
### EXAMPLE PYTHON MODULE # Define some variables: numberone = 1 ageofqueen = 78 # define some functions def printhello(): print "hello" def timesfour(input): print input * 4 # define a class class Piano: def __init__(self): self.type = "Pianola" self.height = 3 self.price...
from typing import Iterable, List, Optional from django.db.models import manager from django.db.models.manager import Manager from .signals import post_bulk_save class CustomManager(Manager): def bulk_create(self, objs: Iterable[any], batch_size: Optional[int], ignore_conflicts: bool) -> List[any]: temp ...
from enum import Enum from urllib.request import urlretrieve import tqdm import numpy as np import os pbar = None def show_progress(block_num, block_size, total_size): global pbar if pbar is None: pbar = tqdm.tqdm(total=total_size / 1024, unit='kB') downloaded = block_num * block_size if down...
import os import sys from testing import Testing import numpy as np import ell_helper import ell script_path = os.path.dirname(os.path.abspath(__file__)) def load_vad_data(): vad_data = os.path.join(script_path, "..", "..", "..", "libraries", "dsp", "VadData.txt") if not os.path.isfile(vad_data): vad_...
import copy import logging import time import urllib import urlparse from mopidy import httpclient import requests import mopidy_funkwhale logger = logging.getLogger(__name__) # Modified from https://code.eliotberriot.com/funkwhale/mopidy/ # blob/master/mopidy_funkwhale/client.py class Sessi...
# Django modules. from django.contrib.auth.models import BaseUserManager # !Triplinker modules: # Current app modules. from .helpers.manager.create_users_func import create_acc class TLAccountManager(BaseUserManager): """Creates common user and super user""" def create_user(self, first_name, second_name, e...
#!/usr/bin/env python # encoding: utf-8 __copyright__ = "Copyright 2021, AAIR Lab, ASU" __authors__ = ["Abhyudaya Srinet", "Pulkit Verma"] __credits__ = ["Siddharth Srivastava"] __license__ = "MIT" __version__ = "1.0" __maintainers__ = ["Pulkit Verma", "Abhyudaya Srinet"] __contact__ = "aair.lab@asu.edu" __docformat__...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-07 10:23 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0002_mainshop'), ] operations = [ migrations.AddField( mod...
# Copyright 2020, 37.78 Tecnologia Ltda. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
# -*- coding: utf-8 -*- # # Copyright (c) 2017, the cclib development team # # This file is part of cclib (http://cclib.github.io) and is distributed under # the terms of the BSD 3-Clause License. """Run method unit tests for cclib.""" import sys import unittest sys.path.insert(1, "method") from .method.testbader i...
#!/usr/bin/env python # coding: utf-8 # This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # # Solution Notebook # ## Problem: Implement a queue with enqueue and dequeue methods using a linked lis...
class character(): def _init_(self,name,job,age): self.name=name self.job=job self.age=age self.health=100 delf.weapon=[] class Fighter(character): def _init_(self,name,age): super()._init_(name,'Fighter',age) class monster(): def _init_(self,name): ...
# coding=utf-8 """ Initialize the megamodel with - all metamodels - all scripts components (parsers/printers/plantuml/...) - the configuration This module is called by the environment """ import modelscript.metamodels import modelscript.scripts import modelscript.config MEGAMODEL=None # This variable is filled later...
from django.urls import path from . import views app_name = 'decks' urlpatterns = [ path('', views.index, name='index'), path('<int:deck_id>/', views.details, name='detail'), path('new/', views.new, name='new'), path('store/', views.store, name='store'), path('<int:deck_id>/edit', views.edit, name...
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException from selenium.webdriver.chrome.options import Options #WINDOW_SIZE ...
# Generated by Django 2.2.3 on 2019-07-09 01:34 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
try: from setuptools import setup setup except ImportError: from distutils.core import setup setup setup( name='vlbi_errors', version='0.1', author='Ilya Pashchenko', author_email='in4pashchenko@gmail.com', packages=['vlbi_errors', 'tests'], scripts=[], url='https://github....
from .filehex import *
from django.contrib import admin from django.urls import path, include from django.conf.urls import url # from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('Articles.urls')), path('calendar/', include('Calendar.urls')), path('enter/', include('Users.urls')), ]
# Copyright 2017 Max W. Y. Lam # # 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, so...
""" Graphs — Sprint Challenge :: World generation """ from room import Room import random import math class World: def __init__(self): self.starting_room = None self.rooms = {} self.room_grid = [] self.grid_size = 0 def load_graph(self, room_graph): num_rooms = len(ro...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import numpy as np import random def MarkovChainModel(src, n): with open(src, 'r', encoding='utf-8') as file: OGdata = file.read() OGList = OGdata.split(' ') indexList = list(dict.fromkeys(OGList)) sentences = OGdata.split("\n\n") fWords = [i.split(' ')[0] for i in sentences] N = len(i...
import albumentations as a import cv2,os,random path='E:\\pos_neg\\Positive' write='E:\\augmented\\positive' j=0 for file in os.listdir(path): img=cv2.imread(os.path.join(path,file)) angle=random.randint(15,30) img=a.rotate(img,angle) cv2.imwrite(os.path.join(write,str(j)+file),img) j+=1 ...
import random import datetime import collections import numpy as np from scipy import sparse from sklearn.preprocessing import normalize from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from news_tls import data, utils, summarizers, plugin random.seed(...
import torch import numpy as np from scipy.stats import mode class Meter: def __init__(self): self.v_list = [] def update(self, v:float, coefficient:float=1): v = v / coefficient self.v_list.append(v) def compute(self): res = np.sum(self.v_list) / len(self.v_list) ...
kilometros = int(input("Digite su kilometraje: ")) kilogramos = int(input("Digite su peso de equipaje: ")) medio = input("Digite su medio de transporte: " ) medio = medio.lower() if medio == "tren": valor_total = 2000 + kilometros * 1000.3 + kilogramos * 75 print("Su valor para tren es: "+str(valor_total)) el...
from pyrevit import EXEC_PARAMS import clr clr.AddReference('RevitAPI') clr.AddReference('RevitAPIUI') clr.AddReference("RevitServices") import Autodesk.Revit.DB as DB doc = EXEC_PARAMS.event_args.GetDocument() # type: DB.Document rebar_filer = DB.ElementClassFilter(DB.Structure.Rebar) added_rebar_id = EXEC_PARA...
from flask import Flask, render_template from printer import PX105 app = Flask(__name__) app.config.from_object('config') class HighCharts(object): def __init__(self, chart_id, chart, series, xAxis, plot_options): self.chart_id = chart_id self.chart = chart self.series = series ...
import numpy import time import warnings try: from scipy import io except ImportError: warnings.warn("couldn't import scipy") import theano from theano import config import theano.tensor as T from pylearn2 import rbm_tools from pylearn2.models import rbm def load_rbm_params(fname): mnistvh = io.loadmat(...
# 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 # dist...
""" A remote controller has 2 button: turn light on and turn light off It does a action to a Light object. """ import abc class Command(metaclass=abc.ABCMeta): @abc.abstractmethod def execute(self): raise NotImplementedError class NoCommand(Command): """ Null object pattern for initialize ...
# This file is a part of ninfs. # # Copyright (c) 2017-2019 Ian Burgwin # This file is licensed under The MIT License (MIT). # You can find the full license text in LICENSE.md in the root of this project. from functools import wraps from io import BufferedIOBase from typing import TYPE_CHECKING if TYPE_CHECKING: ...
n = float(input("Enter a decimal number between 0-1: ")) p = 0 while ((2**p)*n)%1 != 0: p += 1 print("The value of p is " + str(p)) num = int((2**p)*n) print("The int number is " + str(num)) result = "" while (num > 0): result = str(num%2) + result num = num//2 print("The Result value is: " + str(result)) fo...
from joblib import Parallel, delayed import queue import os import time # Define number of GPUs available GPU_available = [0,1,2,3,4,5,6,7,8,9] N_GPU = len(GPU_available) ## model, training_file, bsz, gradientc_acc, training_file template = "python run_glue.py --model_name_or_path {} --train_file data/{}.json --vali...
# -*- coding: utf-8 -*- # # scanless pingeu module # https://github.com/vesche/scanless # import requests BASE_URL = 'http://ping.eu' SCAN_LOC = '/action.php?atype=5' OUTPUT = ''' ------- pingeu ------- PORT STATE SERVICE 21/tcp {:<6} ftp 22/tcp {:<6} ssh 23/tcp {:<6} telnet 25/tcp {:<6} smtp 53/tcp {...
# Doris Zdravkovic, March, 2019 # Solution to problem 10 # Import numpy import numpy as np # Import matplotlib.pyplot import matplotlib.pyplot as plt # x = range from 0 to 4 included # 0 = beginning value of the range # 5 = end of the range x = np.arange(0, 5) # plot - red, blue, green lines # red = x, blue = x2, gre...
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from django.utils.text import slugify from django.db.models import Q from datetime import date, timedelta from random import choice as rand_choice from ingredients.models import Ingredient from meals.models import Meal, Me...
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'VERSION'), encoding='utf8') as f: version = f.read().strip() setup( name='claripy', version=version, python_requires='>=3.6', packages=find_packages(), install_requires=[ 'z3-solve...
from __future__ import unicode_literals from django.core.management.base import BaseCommand, CommandError from django.contrib.auth import get_user_model class Command(BaseCommand): args = '<username password>' help = """Create a user with a specified username and password. User will be created as staff. Arg...
""" Implementation of a lightweight exchange-triggering mechanism via small HTTP requests asking if we should do a full exchange. Ping Sequence ============= Diagram:: 1. BrokerService --> Pinger : Start 2. [Loop forever] | | 2.1 Pinger --> PingClient : Schedule Ping | | 2.2...
#!/usr/bin/env python import sys import time from tools.zookeeper import Zookeeper # Usage: check_consumption.py <averaging_time_sec> <max_average_power_W> # Exit code: 0 -> passed # 1 -> failed if __name__ == "__main__": z = Zookeeper() duration = None if len(sys.argv) > 1: duration = int(sys....
#Una palabras es palindromo def palindrome(word): reversedWord = word[::-1] if word.lower() == reversedWord.lower(): print('"{}" SI es palindromo'.format(word)) else: print('"{}" NO es palindromo'.format(word)) if __name__ == '__main__': word = str(input('Escribe una palabra:...
from utils import timex, tsv from covid19.lk_vax import epid WINDOW = 28 TARGET_POPULATION = 14_600_000 def analysis(): timeseries = epid.load_timeseries() print(len(timeseries)) latest = timeseries[-1] window_ago = timeseries[-1 - WINDOW] dose2_per_day = ( latest['cum_total_dose2'] - w...
#!/usr/bin/env python # # gtf2bed: convert GTF contents to BED format # Copyright (C) University of Manchester 2012,2020 Peter Briggs # import sys import logging from argparse import ArgumentParser from ..GTFFile import GTFIterator from ..GFFFile import ANNOTATION from .. import get_version def main(): """...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- import numpy as np from asdf import yamlutil from asdf.tags.core.ndarray import NDArrayType from astropy import table from ...types import AstropyAsdfType class TableType(AstropyAsdfType): name = 'core/table' types = ['a...
from couchdb.mapping import IntegerField from couchdb.mapping import ListField from couchdb.mapping import TextField from couchdb.mapping import ViewField from .utils import GodhandDocument class Series(GodhandDocument): """ Represents a collection of Volume objects. # Owner if ``owner_id`` is set, that...
"""Hades AMQP API agent""" import celery from . import tasks def create_app() -> celery.Celery: app = celery.Celery(__package__) for obj in tasks.__dict__.values(): if isinstance(obj, tasks.Task): app.register_task(obj) return app
# -*- coding: utf-8 -*- """ Microsoft-Windows-TZSync GUID : 3527cb55-1298-49d4-ab94-1243db0fcaff """ from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct from etl.utils import WString, CString, SystemTime, Guid from etl.dtyp import Sid from etl.pars...
# imports import sys # main function def main(argv): num_list = [] total = 0 f = open("nums2.txt", 'r') for lines in f: num_list.append(lines) for i in range(0, len(num_list)): num_list[i] = num_list[i].replace('\n', '') #print num_list num_length = 50 total = 100 biggy = [] remainder = 0 for i in rang...
import pytest from app.device.gps import GPS def test_no_satalites(): raw_data = { 'GPGGA': ['015138.800', '', '', '', '', '0', '00', '', '', 'M', '', 'M', '', '*7E\r\n'], 'GPRMC': ['015138.800', 'V', '', '', '', '', '0.00', '0.00', '060180', '', '', 'N*44\r\n'] } expected_data = { ...
''' This is a simple python driver for the B&K Turntable System Type 9640 using the PyVISA [1] module, itself a wrapper around the NI-VISA library (available for windows [2], linux [3], and mac [4]). As of now, only absolute positioning has been implemented. Revision History ----------------- 2017/05 Robin Scheibler...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from .roi_heads import Res5ROIHeads, ROIHeads, StandardROIHeads, select_foreground_proposals from .rotated_fast_rcnn import RROIHeads from . import cascade_rcnn # isort:skip
from .. import MaxRanker import numpy as np class TestMaxRankerClass: def create_data(self): query_chunk2match_chunk = { 100: [ {'parent_id': 1, 'id': 10, 'score': 0.4, 'length': 200}, ], 110: [ {'parent_id': 1, 'id': 10, 'score': 0.3, 'l...
# coding: utf-8 # In[1]: import pandas as pd import os import sys # In[2]: import matplotlib.pyplot as plt # In[3]: # plt.rcParams["figure.figsize"]=[15,5] if len(sys.argv) < 2: print("No filename passed. Place the CSV file in the same folder.") exit(2) ldfile=sys.argv[1] out_csv_path=s...
from .scraper import scrape from .visual import plot
from discord.ext import commands def is_guild_owner(): async def predicate(ctx) -> bool: try: return ctx.author == ctx.guild.owner except AttributeError: return False return commands.check(predicate) def is_administrator_or_permission(**perms): async def predicat...
from unittest import mock import pytest from ruamel.yaml import YAML import great_expectations.exceptions as ge_exceptions from great_expectations import DataContext from great_expectations.core import IDDict from great_expectations.core.batch import ( BatchDefinition, BatchRequest, BatchRequestBase, ) fr...
from typing import Dict, Union, List second_units: Dict[str, int] = {'s': 60, 'm': 60, 'h': 24, 'd': 365} sub_second_unit: Dict[str, float] = {'ms': 1e-03, 'µs': 1e-06, "ns": 1e-09} def pretty_time(time: Union[int, float]) -> str: """Format time to a human readable string.""" if not time: return '0s'...
from django.apps import AppConfig class WeatherDisplayConfig(AppConfig): name = 'weather_display'
# # PySNMP MIB module ASCEND-MIBREDHM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBREDHM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:12:05 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
from flask import Flask, render_template import datetime import random app = Flask(__name__) @app.route('/') def index(): days = ['월요일', '화요일', '수요일', '목요일', '금요일'] menu = ['오코토 제육', '나이스샤워 텐동', '뤠벤 돈가스', '타코벨', '맘스터치', '이어곰탕', '반계탕', '한산주 순대국', 'Johnson 샌드위치'] # print(f"오늘은 {days[datetime.dat...
""" Modul for den innebyde webserveren """ # Bot Utilities from cogs.utils.db import DB import requests from flask import Flask, redirect, render_template, request app = Flask(__name__, static_folder="../../static", template_folder="../../templates") class Server: """ Klasse for initalisering av Flask ...
from django.conf.urls import patterns, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = patterns('pari.map.views', url(r'^$', 'index'), ) urlpatterns += staticfiles_urlpatterns()
from player import Player class Batter(Player): ''' A batter and all of his stats as collected from various means and manipulated in the base Player class most likely ''' def __init__(self, name, name_display, id): """ Return a batter object :param name: :param name_...
# Generated by Django 2.2.13 on 2020-10-25 18:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_eveonline_connector', '0037_auto_20201018_1628'), ] operations = [ migrations.AlterField( model_name='evestructure', ...
import threading import time class Signal: ''' A signal is a tool that can be used to control program execution. A program can wait() for other code to send() the signal before continuing. You can later clear() the signal to reset it to the initial state. For instance, this can be used to pause th...
""" File routing to the admin region """ from django.contrib import admin from .models import Configuration from .models import Event from .models import EventTranslation from .models import Offer from .models import OfferTemplate from .models import Language from .models import LanguageTreeNode from .models import ...
import pytest from Acquire.Accounting import Accounts from Acquire.Identity import ACLRules, ACLRule, Authorisation from Acquire.Crypto import PrivateKey, get_private_key from Acquire.Service import get_service_account_bucket, push_is_running_service @pytest.fixture(scope="session") def bucket(tmpdir_factory): ...
from SPARQLWrapper import SPARQLWrapper, JSON from argparse import ArgumentParser import re import json import os import typing DEFAULT_SAVE_LOCATION = os.path.join(os.getcwd(), "prop_idents_v3.json") def get_properties(pnode_id): """ Function used to get the corresponding properties of given p node id :...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import gamma class ReproductionNumber: def __init__(self, incidence, prior_shape=1, prior_scale=5, si_pmf=None, si_pars=None, t_start=None, window_width=None): """ Initialize ReproductionNumbe...
import info class subinfo(info.infoclass): def setTargets(self): for ver in ['2.4.28', '2.4.33', '2.4.36', '2.4.45']: self.targets[ver] = ('ftp://ftp.openldap.org/pub/OpenLDAP/' 'openldap-release/openldap-' + ver + '.tgz') self.targetInstSrc[ver] = ...
# std import uuid # 3rd party import pytest # local from xsorted import xsorter from . util import random_strings class CustomSerializer: """ Custom serializer using a simple in-memory dict. """ def __init__(self): self.store = {} def dump(self, thing): object_id = uuid.uuid4() ...
""" Implementation of ProGAN generator and discriminator with the key attributions from the paper. We have tried to make the implementation compact but a goal is also to keep it readable and understandable. Specifically the key points implemented are: 1) Progressive growing (of model and layers) 2) Minibatch std on Di...
#!/usr/bin/env python3 from __future__ import division from builtins import str from builtins import range from past.utils import old_div import os, sys, re, requests, json, shutil, traceback, logging, hashlib, math from itertools import chain from zipfile import ZipFile from subprocess import check_call, CalledProces...
__author__ = 'Juergen Simon' __email__ = 'juergen.simon@uni-bonn.de' __version__ = '1.6.0' __url__ = 'http://git.meteo.uni-bonn.de/projects/meanie3d' __all__ = ['app', 'visualisation', 'resources'] import os.path import sys def getVersion(): ''' :return:meanie3D package version ''' from . import __ver...
# coding utf-8 ''' Basic utilities. ''' import re import lxml.etree as et from .exceptions import XMLSyntaxError, ConversionError from . import plugin_config element_t = type(et.Element('x')) def element(tag, *children, **attribs): el = et.Element(tag, attribs) for child in children: if isinstance(child, elemen...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from django.contrib.auth import get_user_model from fabric_bolt.projects import models from fabric_bolt...
from gym.spaces import box import numpy as np class Box(box.Box): def flatten(self, x): return np.asarray(x).flatten() def unflatten(self, x): return np.asarray(x).reshape(self.shape)
import numpy as np import pandas as pd from lib.error import MinorityGameError from collections import OrderedDict from lib.agents.factory_vectorized import VectorizedStrategyUpdatingAgentFactory class VectorizedMinorityGame: """ Vectorized version of Minority Game. Speeds up the simulation exponentially for ...