content stringlengths 5 1.05M |
|---|
# Project Quex (http://quex.sourceforge.net); License: MIT;
# (C) 2005-2020 Frank-Rene Schaefer;
#_______________________________________________________________________________
import os
import sys
sys.path.insert(0, os.environ["QUEX_PATH"])
from quex.DEFINITIONS import QUEX_PATH
import quex.engine.m... |
import pytest
import numpy as np
from pytest import raises
from copy import deepcopy
from thyme.parsers.cp2k import parse_md, pack_folder_trj
from thyme.trajectory import Trajectory
from pathlib import Path
class TestParseMD:
def test_direct(self):
folder = "tests/example_files/cp2k_md"
trj = ... |
import re
import json
import six
from itertools import cycle
from scrapy.utils.misc import load_object
from scrapy_rotated_proxy.extensions import default_settings
from scrapy_rotated_proxy import util
import logging
if six.PY2:
from urlparse import urlunparse
from urllib2 import _parse_proxy
else:
from u... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 8 10:46:25 2019
@author: Lombardi
"""
'''
APRIL
'''
from core import User, np
User_list = []
#User classes definition
LI = User("low income",1)
User_list.append(LI)
#Appliances definition
#Low Income
LI_indoor_bulb = LI.Appliance(LI,3,7,2,120,0.2,10)
LI_indoor_bul... |
from datetime import date
from django.contrib.contenttypes.models import ContentType
from django.test import Client, TestCase
from django.urls import reverse
from rest_framework import status
from dcim.forms import SiteCSVForm
from dcim.models import Site
from extras.choices import *
from extras.models import CustomF... |
from django.views.generic import ListView, DetailView
from eventex.core.models import Speaker, Talk
home = ListView.as_view(template_name='index.html', model=Speaker)
speaker_detail = DetailView.as_view(model=Speaker)
talk_list = ListView.as_view(model=Talk)
|
import utils.init_multiprocessing # BEFORE numpy
import numpy as np
import os
import matplotlib.pyplot as plt
from twocell.twocell_simulate import twocell_sim_fast, twocell_sim_as_onelargemodel
from multicell.multicell_spatialcell import SpatialCell
from singlecell.singlecell_constants import MEMS_UNFOLD, BETA
from ... |
from functools import lru_cache
from typing import Optional, List
from fastapi.middleware.cors import CORSMiddleware
from fastapi import Depends, FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from jose import JWTError, jwt
from redminelib import Redmine
from apscheduler.schedul... |
from os import listdir
from os.path import isfile, join
import unittest
import pprint
from parse_apache_configs import parse_config
from pyparsing import *
class TestParsing(unittest.TestCase):
def test_line_by_line(self):
"""
This method tests the parsing of each line of the
apache config ... |
"""
Construct the other ROC plot.
This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE file in the root
directory of this source tree or at
http://www.apache.org/licenses/LICENSE-2.0.
Any modifications or derivative works of this code must retain this
copy... |
"""
Transports provided by aiida_unicore.
Register transports via the "aiida.transports" entry point in setup.json.
"""
from aiida.transports import Transport
class UnicoreTransport(Transport):
"""
AiiDA transport plugin for unicore
"""
|
import torch.nn as nn
import torch.nn.functional as F
import torch
from mmseg.core import add_prefix
from mmseg.ops import resize
from mmcv.runner import load_checkpoint
from ..builder import DISTILLER,build_distill_loss
from mmseg.models import build_segmentor
from mmseg.models.segmentors.base import BaseSegmentor
... |
from ..lib import PASS, MISSING
from ..error import Invalid
from .core import Validator, ValidatorBase, messages
from copy import copy
import logging, sys
_python3 = sys.version_info[0]>=3
log = logging.getLogger(__name__)
@messages\
( fail='This field must be left out'
)
class Missing( Validator ):
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-01 02:35
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bpay', '0001_initial'),
]
operations = [
migrations.AlterModelTable(
nam... |
from django.db import models
class Activity(models.Model):
title = models.CharField(max_length=150)
grade_CHOICES = ((1, 1), (2, 2), (3, 3), (4, 4), (5, 5),(6,6),(7,7),(8,8),(9,9),(10,10),(11,11),(12,12))
grade = models.IntegerField(default=True, choices=grade_CHOICES)
link = models.URLField(max_lengt... |
class Solution:
def isPalindrome(self, x: int) -> bool:
L = 2**31
MAX = L-1
MIN = -L
if not MIN < x < MAX :
return False
if x <0 :
return False
x = str(x)
rev_x = x[::-1]
if int(rev_x) > L:
retu... |
import asyncio
from pyjamas_core.util import Input, Output, Property
from pyjamas_core.supermodel import Supermodel
class Model(Supermodel):
"""
schedules the func gates of the agent
sets the number of elapsed rounds as output
"""
def __init__(self, uuid, name: str):
super(Model, ... |
import logging
from atlassian import Bamboo
"""
That example shows how to clean up Bamboo incomplete or Unknown build results
"""
logging.basicConfig(level=logging.ERROR)
REMOVE = True
STATUS_CLEANED_RESULTS = ["Incomplete", "Unknown"]
EXCLUDED_PROJECTS = ["EXCLUDE_PROJECT"]
BAMBOO_LOGIN = "admin"
BAMBOO_PASS = "pa... |
from timeit import default_timer as timer
import fire
import h5py
import numpy as np
def startTimer():
print("Timer is starting")
start = timer()
hf = h5py.File('time.h5', 'w')
hf.create_dataset('timing', data=start)
hf.close()
def endTimer():
print("Timer ends")
end = timer()
hf = ... |
from minder_utils.models.feature_extractors import SimCLR, Partial_Order, AutoEncoder
from minder_utils.dataloader import process_data
from minder_utils.evaluate.evaluate_models import evaluate_features
from minder_utils.dataloader import Dataloader
from minder_utils.util.initial import first_run
import pandas as pd
im... |
# -*- coding: utf-8 -*-
from enum import Enum
class ChatMode(Enum):
MODE2017 = 'mode_2017'
MODE2018 = 'mode_2018'
MODE2021 = 'mode_2021'
|
import os
import sys
import warnings
from inspect import getmembers, isfunction
from ase.io import read
unsupported_template = '\nProperty "%s" not available. Please verify which features' \
'in Sapphire are supported first by calling\n' \
'\nfrom Utilities.Supported import Supported\n' \
'print(Supported(... |
from django.urls import path, include
from mighty.applications.tenant import views
app_name = 'tenant'
api_urlpatterns = [
path('tenant/', include([
path('', views.TenantList.as_view(), name="api-tenant-list"),
path('<uuid:uid>/', views.TenantDetail.as_view(), name="api-tenant-detail"),
pat... |
import os
import argparse
import numpy as np
try:
from sklearn.cluster import KMeans
except:
raise ImportError('''
Error! Can not import sklearn.
Please install the package sklearn via the following command:
pip install sklearn
''')
try:
import pyoctree
except:
raise ImportError('''\n
Error! C... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
.. module:: __init__
:synopsis: module that contains a class that encompasses the properties of the configuration file and maps it.
"""
import os
import sys
import logging
from collections import OrderedDict
from os import path, environ
from urllib.parse import parse... |
import datetime
import json
import unittest
from app import db
from app.models.bucketlist_models import Users
from app.test_config import GlobalTestCase
from flask import url_for
class BucketlistTest(GlobalTestCase):
def setUp(self):
db.drop_all()
db.create_all()
self.user = Users(
... |
#!/usr/bin/python
# Copyright (c) 2017 David LePage
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: bgp_element_facts
short... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return '{ ' + str(self.val) +': ' + repr(self.left) + ', ' + repr(self.right) + '}'
class Solution:
def getDepth(self, S: str):
end = self.idx
whi... |
#!/usr/bin/env python
#
# License: BSD
# https://raw.githubusercontent.com/splintered-reality/py_trees/devel/LICENSE
#
##############################################################################
# Documentation
##############################################################################
"""
Demonstrates the cha... |
from PyPDF2 import PdfFileReader
def getTextPDF(pdfFileName, password = ''):
pdf_file = open(pdfFileName, 'rb')
read_pdf = PdfFileReader(pdf_file)
if password != '':
read_pdf.decrypt(password)
text = []
for i in range(0,read_pdf.getNumPages()):
text.append(read_pdf.getPage(i).extrac... |
from mani_skill_learn.utils.data import (dict_to_seq, recursive_init_dict_array, map_func_to_dict_array,
store_dict_array_to_h5,
sample_element_in_dict_array, assign_single_element_in_dict_array, is_seq_of)
from mani_skill_learn.utils.fil... |
#!/usr/bin/env python3
from cmd import Cmd
from collections import namedtuple
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
from datetime import timedelta
from enum import Enum
from threading import Lock
import argparse
import configparser
import lxml.html
import os
import json
import... |
import logging
import pandas as pd
from utils.file_handling import write_debug_file
from expworkup.handlers.cleaner import cleaner
from expworkup.handlers.chemical_types import get_unique_chemicals_types_byinstance, runuid_feat_merge
from utils.globals import get_debug_simple
modlog = logging.getLogger(f'mainlog.{__n... |
from random import randint
jog = int(input('Arrisque um numero: '))
comp = randint(1, 10)
tot = 1
while jog != comp:
print('Errou tente novamente!!')
jog = int(input('Arrique um numero: '))
tot += 1
if jog < comp:
print('Um pouco mais')
if jog > comp:
print('Um pouco menos')
print(f... |
import xml.parsers.expat
NC_NS_URI ="urn:ietf:params:xml:ns:netconf:base:1.0"
CAPABILITIES = {
"urn:ietf:params:xml:ns:netconf:base:1.0" : "base",
"urn:ietf:params:netconf:base:1.1" : "base",
"urn:ietf:params:netconf:capability:writable-running:1.0" : "writable-running",
"urn:ietf:params:netconf:capabi... |
import argparse
import numpy as np
import matplotlib.pyplot as plt
import random
from matplotlib.patches import Rectangle
# Usage: python print_solution.py -f <filename>
parser = argparse.ArgumentParser(description='Argument parser')
parser.add_argument("-f", "--file_name", help="Filename", required = True, type=str)
... |
# @l2g 1760 python3
# [1760] Minimum Limit of Balls in a Bag
# Difficulty: Medium
# https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag
#
# You are given an integer array nums where the ith bag contains nums[i] balls.
# You are also given an integer maxOperations.
# You can perform the following operation at ... |
from tenark.identifier import Identifier
def test_identifier_methods():
abstract_methods = Identifier.__abstractmethods__ # type: ignore
assert 'generate_id' in abstract_methods
|
import json
import threading as thread
import scapy.all as sc
def get_net_config():
"""
Get json configuration file and trusted mac addresses
Returns:
dictionary: list of mac_address and corresponding given name
String : IP configuration for your network with CIDR
String : Broadca... |
# -*- coding: utf-8 -*-
"""
checkboxes
~~~~~~~~~
TODO: explain this :)
"""
import re
from UserList import UserList
import vim
from orgmode.liborgmode.base import MultiPurposeList, flatten_list
from orgmode.liborgmode.orgdate import OrgTimeRange
from orgmode.liborgmode.orgdate import get_orgdate
from orgmode.libo... |
def main():
message = 'Hello World'
print(message)
if __name__ == '__main__':
main()
|
print('* ' * 4)
print('* ', ' ' * 2, sep='', end='*\n')
print('* ', ' ' * 2, sep='', end='*\n')
print('* ' * 4)
|
# =============================================================================
# Adds features to the data obtained from the simulation to train a machine
# learning model.
# =============================================================================
import pandas as pd
import json
import networkx as nx
import os
... |
# 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... |
def fun_callback(input):
print('fun_callback sum: ',input)
return
def fun_call(one, two, f_callback):
result = one + two
f_callback(result)
return
first = 10
second = 20
fun_call(first, second, fun_callback) |
#coding=utf-8
import numpy as np
import math
#过滤网站恶意留言
def loadDataSet():
#创造数据集
postingList = [ ['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
['stop... |
import os, sys
root=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(root)
import pytest
from langrank import prepare_train_file, train
def test_train():
langs = ["aze", "ben", "fin"]
datasets = [os.path.join(root, "sample-data", "ted-train.orig.{}".format(l)) for l in langs]
se... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-07-16 07:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0012_auto_20180716_0733'),
]
operations = [
migrations.RemoveFi... |
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot4/blob/main/LICENSE
import os
import numpy as np
import pytest
import skhep_testdata
import uproot
import uproot.writing
ROOT = pytest.importorskip("ROOT")
def test_copy(tmp_path):
original = os.path.join(tmp_path, "original.root")
newfile = ... |
from __future__ import absolute_import
from sentry import tsdb
from sentry.models import ServiceHook
from sentry.testutils import APITestCase
class ProjectServiceHookStatsTest(APITestCase):
def test_simple(self):
project = self.create_project()
hook = ServiceHook.objects.get_or_create(
... |
import json
import time
from data import get_registered_user
from kafka import KafkaProducer
def json_serializer(data):
return json.dumps(data).encode('utf-8')
def get_partition(key, all, available):
return 0
producer = KafkaProducer(bootstrap_servers=['localhost:9092'],
value_s... |
# -*- encoding: utf-8 -*-
# Module iahmin
from numpy import *
from iasecross import iasecross
def iahmin(f, h=1, Bc=iasecross()):
from iaaddm import iaaddm
from iasuprec import iasuprec
g = iaaddm(f,h)
y = iasuprec(g,f,Bc);
return y
|
import unittest
from recipeformats import mmf
class TestParseRecipe(unittest.TestCase):
def assert_equal(self, actual, expected_title, expected_categories,
expected_yield, expected_servings, expected_ingredients,
expected_directions):
actual_ingredients = [repr(... |
import os
import pynoteslib as nl
def test_save_plaintext():
nl.get_config()
n = nl.note_from_plaintext("text for testing PT save")
n.title = "testing PT save"
n.save_plaintext()
assert os.path.exists(nl.get_note_fullpath("testing_PT_save"))
os.remove(nl.get_note_fullpath("testing_PT_save", ... |
# activate theano on gpu
import os;
#os.environ['THEANO_FLAGS'] = "device=gpu";
#import theano;
#theano.config.floatX = 'float32';
import numpy as np;
import sys
import gzip;
from six.moves import cPickle;
from vae_conv import conv_variational_autoencoder;
from keras import backend as K;
from scipy.stats import norm;... |
from django.test import TestCase
from api.aqi_converter import AqiConverter
class ApiConverter(TestCase):
def test_pm1_micrograms_to_aqi(self):
converter = AqiConverter()
self.assertEqual(converter.pm1_micrograms_to_aqi(5), 4)
|
import pyembroidery as emb
def h_straight(pattern, x, y, dx, nx):
pattern.add_stitch_absolute(emb.JUMP,x,y)
for x in range(x,x_nx,dx):
pattern.add_stitch_absolute(emb.STITCH, x,y)
if x != x+nx:
pattern.add_stitch_absolute(emb.STITCH, x+nx,y)
pattern.add_command(emb.STOP)
def v_straight... |
# -*- coding: utf-8 -*-
# @Time : 5/30/2018 2:26 PM
# @Author : sunyonghai
# @File : six2one2.py
# @Software: ZJ_AI
import argparse
import itertools
import json
import logging
import os
import random
from xml.dom.minidom import parseString
import cv2
import numpy as np
from PIL import Image
from lxml.etree impor... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-12 02:52
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
import pytest
from tests.functional.pages.hello import HelloPage
from tests.functional.utils import screenshot_on_failure
from tests.functional.utils import validate_redirect
url = "http://localhost:8000/hello/"
@pytest.mark.functional
@screenshot_on_failure
def test(browser, request):
page = HelloPage(browser,... |
from functools import partial
from pyramid.view import view_defaults
from pyramid.view import view_config
from sqlalchemy.orm import subqueryload
from sqlalchemy.sql.functions import concat
from c2cgeoform.schema import GeoFormSchemaNode
from c2cgeoform.views.abstract_views import ListField
from deform.widget import F... |
#!/usr/bin/python3
from distutils.core import setup
import setuptools # noqa
from ulozto_downloader import __version__
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='ulozto-downloader',
version=__version__,
license='MIT',
description='Uloz.to quick multiple sessions downlo... |
import torch
from tensorboardX import SummaryWriter
import numpy as np
import os
from datetime import datetime
from multiprocessing import cpu_count
import gc
import random
import sys
os.chdir("style_transfer")
sys.path.append("./../models")
sys.path.append("./../general_modules")
from st_argument_parser_helper impo... |
dilation_shapes_test = [
(1, 3, 448, 448, 64, 7, 7, 2, 3, 2, 1),
(1, 64, 112, 112, 192, 3, 3, 1, 1, 2, 1),
(1, 192, 56, 56, 128, 1, 1, 1, 0, 2, 1),
(1, 128, 56, 56, 256, 3, 3, 1, 1, 2, 1),
]
dilation_shapes = [
# yolo
(1, 256, 56, 56, 256, 1, 1, 1, 0, 2, 1), # conv5 4
(1, 256, 56, 56, 5... |
# -*- coding: utf-8 -*-
"""
Created on May 21, 2014
@author: HubbeKing, Tyranic-Moron
"""
from CommandInterface import CommandInterface
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
import GlobalVars
class Alias(CommandInterface):
triggers = ['alias']
help = 'alias <ali... |
import unittest
from BattleShips.tests import BattleShipsTest
from BattleShips.controller import GameController
class TestController(BattleShipsTest):
def setUp(self):
pass
def test_game_controller(self):
game_controller = GameController()
self.assertOutput(game_controller.game_play,... |
#!/usr/bin/python3
import signal
import asyncio
import argparse
import json
import sys
import logging
from logging.handlers import RotatingFileHandler
import hookman.http as http
"""
HookMan main() module.
HookMan module that contains main() along with argument parsing, instantiation of the HTTP Objects,
also creat... |
#!/usr/bin/env python
import unittest, os, sys, subprocess as sp, shlex, numpy as np
import mcvine, mcvine.resources
from mcni.neutron_storage.idf_usenumpy import count
class TestCase(unittest.TestCase):
def test_count(self):
"mcvine neutronstorage count"
cmd = "mcvine neutronstorage count n... |
import os
import platform
import sys
import time
from datetime import datetime
from pytz import timezone
"""
Simple proof of concept python application
"""
def looper():
"""
Simple proof of concept function.
Loops indefinitely, prints to stdout and writes to file.
:return:
"""
while True:
... |
from typing import Any, Dict, List, Optional
from glom import glom
from restapi import decorators
from restapi.rest.definition import EndpointResource, Response
from restapi.services.authentication import User
from restapi.utilities.globals import mem
from restapi.utilities.logs import log
class NewSwaggerSpecifica... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 07 16:31:26 2013
@author: Will Rhodes
"""
import numpy as np
import math
#creates the boolean map from a list of skyObjects (data) with a specified
class BooleanMap:
resolution = 360
dSize = 360./resolution
countMap = np.zeros([resolution,resolution])
... |
from models.order import Order
from models.product import Product
from tests import testing_app
from tests.helpers import *
@with_test_db((Product,))
def test_index_displays_product_names():
create_test_product("Toothbrush", "2.00")
create_test_product("Toothpaste", "1.00")
res = testing_app.get("/")
... |
#!/usr/local/bin/python2.7
from sys import exit
from os import environ, system
environ['KERAS_BACKEND'] = 'tensorflow'
environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
environ["CUDA_VISIBLE_DEVICES"] = ""
import numpy as np
import extra_vars
from subtlenet import config, utils
from subtlenet.backend import obj
from s... |
#!/usr/bin/env python3
import os
from collections import namedtuple
from itertools import chain
import json
# declare normalized data structure
LocalBusiness = namedtuple('LocalBusiness', ['department', 'address', 'geo', 'name', 'url', 'telephone', 'faxNumber', 'email', 'id'])
Department = namedtuple('Departmen... |
import unittest
from EXOSIMS.util.RejectionSampler import RejectionSampler as RS
from EXOSIMS.util.InverseTransformSampler import InverseTransformSampler as ITS
import numpy as np
import scipy.stats
import os
class TestSamplers(unittest.TestCase):
"""Test rejection sampler and inverse transform sampler since both ... |
import cv2
import pickle
from io import BytesIO
import time
import requests
from PIL import Image
import numpy as np
from importlib import import_module
import os
from flask import Flask, render_template, Response
from flask import request
import imutils
import json
import requests
from flask import Blueprint, request,... |
import jsonpickle
from intelhex import IntelHex
from pathlib import Path
from struct import unpack
from calibration_results import CalibrationResults
from cluck2sesame_device import Cluck2SesameDevice
from cluck2sesame_nvm_settings import Cluck2SesameNvmSettings
class CalibrationResultsLoader:
def __init__(self, re... |
from som.vmobjects.abstract_object import AbstractObject
class String(AbstractObject):
_immutable_fields_ = ["_string"]
def __init__(self, value):
AbstractObject.__init__(self)
self._string = value
def get_embedded_string(self):
return self._string
def __str__(self):
... |
#!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# runqslower Trace long process scheduling delays.
# For Linux, uses BCC, eBPF.
#
# This script traces high scheduling delays between tasks being
# ready to run and them running on CPU after that.
#
# USAGE: runqslower [-p PID] [min_us]
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ## ###############################################
#
# music.py
# Proyecto final : Centro Multimedia (centro de entretenimiento para la reproducción de películas, videos, música, y fotografías).
#
# Autores:
# Martínez Bárcenas Edgar Daniel
# García Reyes Saúl Michel
# R... |
"""
.. module:: west_coast_random
:platform: Windows
:synopsis: Example code making a scenario in west_coast_usa and having a
car drive around randomly.
.. moduleauthor:: Marc Müller <mmueller@beamng.gmbh>
"""
import mmap
import random
import sys
from time import sleep
import numpy as np
import... |
# Copyright (C) 2019-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
import inspect
import os, os.path as osp
import zipfile
def current_function_name(depth=1):
return inspect.getouterframes(inspect.currentframe())[depth].function
def make_zip_archive(src_path, dst_path):
with zipfile.ZipFile(dst_... |
import torch
import torch.nn as nn
class GANLoss(nn.Module):
def __init__(self, gan_mode="vanilla", real_label=0.9, fake_label=0.1):
"""
Initialize the GANLoss class.
Parameters:
gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.
... |
import trio
import remi.gui as G
from cloud_ui.apps.application import Application
try:
from cloud_ui.cloudapp import UICloud
except ImportError:
pass
class TelegramNotificationManageApplication(Application):
async def init(self, *args):
await self.cloud.wait_service("telegram_bot")
def ini... |
# Generated by Django 2.0.2 on 2018-02-25 14:51
from django.db import migrations
import lists.models
class Migration(migrations.Migration):
dependencies = [
('lists', '0002_auto_20180225_1540'),
]
operations = [
migrations.AlterField(
model_name='todo',
... |
import fire
import os
from tqdm import tqdm
import pickle
from models.bart import BART
from models.gpt2 import GPT2
def get_model_list(dataset, prog_vocabs, first_model):
model_list = []
for i in range(len(prog_vocabs) - 1):
if i == 0 and 'gpt2' in first_model:
model = GPT2(gpt2_type=firs... |
default_app_config = "netbox_rbac.apps.AppConfig"
|
from rest_framework.generics import (CreateAPIView, RetrieveUpdateAPIView,
RetrieveDestroyAPIView, ListAPIView
)
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from .mo... |
import requests
import json
url = 'http://tentalux.dubno.com/controlsome'
data=[{'number':0, 'brightness':105}]
print(json.dumps(data))
response = requests.post(url, data={'data':json.dumps(data)})
data = response.json()
ARBs = data['ARBs']
arms = len(ARBs)
brightness = sum( [arb[2] for arb in ARBs] ) / arms
print(a... |
import asyncio
import logging
import typing
if typing.TYPE_CHECKING:
from hub.scribe.network import LBCMainNet
from hub.scribe.daemon import LBCDaemon
def chunks(items, size):
"""Break up items, an iterable, into chunks of length size."""
for i in range(0, len(items), size):
yield items[i: i +... |
# Tool for creating 10m buffers around collection points
# Developed by Bhekani Khumalo
import arcpy
import ramm
arcpy.env.overwriteOutput = True
try:
# Get inputs
col_points = arcpy.GetParameterAsText(0)
boundary = arcpy.GetParameterAsText(1)
buff_dist = arcpy.GetParameterAsText(2)
output_locatio... |
# For each wav file in the input directory, convert it to mp3 and then delete it.
import argparse
import inspect
import os
import sys
CONVERT_TYPES = ['.flac', '.octet-stream', '.wav', '.wma']
# command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument('-d', type=str, default='', help='Input dire... |
#!/usr/bin/python
'''
This reads BMP180 sensor data and sends it to Adafruit.io (https://adafruit.io/)
for data analysis and visualization. Requires a valid account.
'''
import sys, time
import Adafruit_BMP.BMP085 as BMP085
from Adafruit_IO import Client
aio = Client('dec373cb22994ee094a33f22f3f7a0e2')
INTERVAL = 30
... |
import pytest
import solution
@pytest.mark.parametrize(
"nums,expected",
[
([1, 2, 3], [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]),
([0, 1], [[0, 1], [1, 0]]),
([1], [[1]]),
],
)
def test_initial_pass(nums, expected):
got = solution.initial_pass(nums)
assert len(got... |
import getopt
import os
import sys
import time
import jsonlines
import pandas as pd
class Aggregator:
"""This class produces a running total of the types of events in a directory"""
def __init__(self, argv):
"""
This method initialises the class variables
:param argv: List[String] -... |
#!/bin/python3
# coding=utf-8
# ------------------------------------------------------------------------------
# Created on October 05 12:49 2021
#
# Vertica Vaas Okta Login command
#
# Usage:
# va login
# va login --profile profile2
#
# (c) Copyright 2021 Micro Focus or one of its affiliates.
# -------------------... |
import tempfile
from pathlib import Path
from libdotfiles.packages import try_install
from libdotfiles.util import current_username, distro_name, download_file, run
if distro_name() == "linux":
try_install("docker")
try_install("docker-compose")
elif distro_name() == "linuxmint":
with tempfile.TemporaryDi... |
print("-----Problema 1-----")
m = "Maximul dintre doua numere"
print(m.upper())
a = int(input("Dati-l pe a: "))
b = int(input("Dati-l pe b: "))
def maxim(a,b):
if a < b :
max = b
print("a < b max = ", max)
elif a > b:
max = a
c = format(max)
print(f'a > b max = {c}')
... |
import SimpleLanguage
class FirstExampleClass:
def __init__(self):
# Init SimpleLanguage with default settings (defaultLanguage: eng, actualLanguage: eng, databasePath: ".\\language\\")
lang = SimpleLanguage.init()
# Take a text from database
print(lang.rString("testKey1"))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import map, range, object, zip, sorted
import sys
import os
def main(argc, argv):
from amplpy import AMPL, DataFrame
import amplpy
from time import time
from threading import Lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.