content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from train import d_conv_dim, g_conv_dim, z_size, model_name, img_size
import torch
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from train_class.load_model import Discriminator, Generator
from train_class.load_model import build_network
import torch.nn.functional as F
# load pretrained mod... | nilq/baby-python | python |
import numpy as np
from core import Cache
from core import scipy_diffev
from core import notification
from core import preset
from core import track_and_update_metric
from visualization import display_iterations
def diffev_function_test(w, *args):
cache = args[0]
cache.w = w
residual = 0
for x, y in ... | nilq/baby-python | python |
from stockpyle._base import BaseDictionaryStore
class ShoveStore(BaseDictionaryStore):
"""Represents a store that places all objects in a Shove (see http://pypi.python.org/pypi/shove)"""
def __init__(self, shove=None, shoveuri=None, polymorphic=False, lifetime_cb=None):
# TODO: deprecate 'sho... | nilq/baby-python | python |
# 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... | nilq/baby-python | python |
##########################################################
### Import Necessary Modules
import argparse #provides options at the command line
import sys #take command line arguments and uses it in the script
import gzip #allows gzipped files to be read
... | nilq/baby-python | python |
# from .__S3File import s3_set_profile as set_profile
from .__S3File import s3_xlist as xlist
from .__S3File import s3_download as download
from .__S3File import s3_upload as upload
from .__S3File import s3_load as load
from .__S3File import s3_save as save
from .__S3File import s3_open as open
from .__S3File import s3... | nilq/baby-python | python |
# Copyright 2017, 2018 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... | nilq/baby-python | python |
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
class SEIRModelAge:
"""
This class implements a SEIR-like compartmental epidemic model
consisting of SEIR states plus death, and hospitalizations and age
structure.
In the diff eq modeling, these parameters a... | nilq/baby-python | python |
#!/usr/bin/env python
from dissect.cstruct import cstruct, dumpstruct
import socket
import struct
protocol = cstruct()
protocol.load("""
enum AttackType : uint8 {
ATK_OPT_DPORT = 7,
ATK_OPT_DOMAIN = 8,
ATK_OPT_NUM_SOCKETS = 24,
};
struct AttackTarget {
DWORD ipv4;
BYTE netmask;
};
stru... | nilq/baby-python | python |
from celery import task
import re
from django.utils import timezone
from backups.models import Backup, BackupRun, BackupSetOfRun, BackupNotification
import os
from django.conf import settings
from app.utils import DjangoLock
@task(ignore_result=True, queue="backups")
def run_backup(id, mode='hourly', backupsetpk=... | nilq/baby-python | python |
import logging
from dicewars.client.ai_driver import BattleCommand, EndTurnCommand
class AI:
def __init__(self, player_name, board, players_order):
self.player_name = player_name
self.logger = logging.getLogger('AI')
def ai_turn(self, board, nb_moves_this_turn, nb_turns_this_game, time_left)... | nilq/baby-python | python |
import random
from typing import List
from project.conf import get_configuration
from project.utils import ITEMS_SECTION
from project.effect import SideEffect, instantiate_side_effects
from project.interface import IItem, IHealingItem, IRecoveryItem, IEquipmentItem, ISideEffect
class Item(IItem):
def __init__(se... | nilq/baby-python | python |
import RPi.GPIO as GPIO
import time
from libdw import pyrebase
#Database Set-Up
projectid = "cleanbean-9e2f5"
dburl = "https://" + projectid + ".firebaseio.com"
authdomain = projectid + ".firebaseapp.com"
apikey = "AIzaSyA6H-rDpfGJZcTqFhf69t3VYbbOzfUW0EM"
email = "kenzho_lim@mymail.sutd.edu.sg"
password = "123456"
c... | nilq/baby-python | python |
"""Metaclass that overrides creating a new pipeline by wrapping methods with validators and setters."""
from functools import wraps
from rayml.exceptions import PipelineNotYetFittedError
from rayml.utils.base_meta import BaseMeta
class PipelineBaseMeta(BaseMeta):
"""Metaclass that overrides creating a new pipeli... | nilq/baby-python | python |
from setuptools import setup
import glob
import os
import sys
import json
def package_files(package_dir, subdirectory):
# walk the input package_dir/subdirectory
# return a package_data list
paths = []
directory = os.path.join(package_dir, subdirectory)
for (path, directories, filenames) in os.walk... | nilq/baby-python | python |
""" Advent of Code Day 2 - Bathroom Security"""
def get_code(start_pos, keypad, valid_pos):
"""Returns the code generated from instructions on specified keypad."""
pos = start_pos
code = ''
for line in lines:
for move in line:
if move == 'R':
next_pos = [pos[0], pos... | nilq/baby-python | python |
import chanutils.reddit
from chanutils import get_json
from playitem import PlayItem, PlayItemList
_SEARCH_URL = "https://www.googleapis.com/youtube/v3/search"
_FEEDLIST = [
{'title':'Trending', 'url':'http://www.reddit.com/domain/youtube.com/top/.json'},
{'title':'Popular', 'url':'https://www.googleapis.com/yout... | nilq/baby-python | python |
"""
Demo for chunk extraction in pyClarion.
Prerequisite: Understanding of the basics of pyClarion as discussed in the demo
`free_association.py`.
"""
from pyClarion import (
Structure, Construct,
agent, subsystem, buffer, flow_bt, flow_tb, features, chunks, terminus,
feature, updater,
Chunks, Asset... | nilq/baby-python | python |
import numpy
from pylab import *
from scipy.interpolate import interp1d
d1,e1,ee1,f1,ef1=numpy.loadtxt("full.txt",unpack=True)
f1=-f1*31.6e-15
inds=argsort(d1)
d1=d1[inds]
f1=f1[inds]
d2,e2,ee2,f2,ef2=numpy.loadtxt("PEC.txt",unpack=True)
f2=-f2*31.6e-15
inds=argsort(d2)
d2=d2[inds]
f2=f2[inds]
d3,e3,ee3,f3,ef3=numpy... | nilq/baby-python | python |
# _*_ coding:utf-8 _*_
# 练习函数调用。
def hello(name):
print "hello",name
pass
def manyHello():
for i in ["a","bobo","green"]:
hello(i)
pass
manyHello() | nilq/baby-python | python |
from comex_stat.assets.models import (CGCE, CUCI, NCM, SH, AssetExportFacts,
AssetImportFacts, Country,
FederativeUnit, TradeBlocs,
Transportation, Urf)
from graphene_django.filter.fields import DjangoFilte... | nilq/baby-python | python |
import numpy as np
import pandas as pd
np.random.seed(101)
df = pd.DataFrame(np.random.randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'. split())
print(df)
print(df[['W', 'Z']])
df['new'] = df['W'] + df['X']
print(df)
print(df.loc['A', 'X'])
print(df.loc['A'])
| nilq/baby-python | python |
# coding: utf-8
"""
Prisma Cloud Compute API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.04.439
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_impor... | nilq/baby-python | python |
import boto3
def post_handler(event, context):
sns= boto3.client('sns')
response = sns.publish(
TopicArn='arn:aws:sns:eu-west-1:538353771716:mytopic',
Message='testinglambda'
)
return{
"message" : "successful"
}
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""Test... | nilq/baby-python | python |
from __future__ import absolute_import
from django.core import mail
from sentry.utils.compat.mock import patch
from social_auth.models import UserSocialAuth
from sentry.exceptions import InvalidIdentity, PluginError
from sentry.models import (
Commit,
Deploy,
Integration,
LatestRepoReleaseEnvironment,... | nilq/baby-python | python |
from src.models import Movie
from src.api import Api
from flask import request
from os import remove , listdir
from os.path import exists
class Movies(Api):
def __init__(self):
super().__init__()
def create_model(self):
self.model = Movie()
def sanitize_data(self):
data = [
... | nilq/baby-python | python |
import unittest
from python_tuya_oittm.api_client import ApiClient
TEST_DEVICE_ID = '<enter a device id>'
TEST_ENCRYPTION_KEY = '<enter an encryption key>'
class TestTuyaApiClientIntegratedMethods(unittest.TestCase):
def test_get_metadata(self):
api_client = ApiClient()
data = api_client.get_met... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Sentinel Tools API Class
Sentinel Tools - API Class
============================
Simple wrapper class for the Sentinel API that takes a Config object.
This file is a part of Sentinel Tools
Copyright 2020 - MET Norway (Machine Ocean Project)
Licensed under the Apache License, Version ... | nilq/baby-python | python |
"""
plenum package metadata
"""
import os
import json
from typing import Tuple, List, Union
import collections.abc
from common.version import PlenumVersion, InvalidVersionError
VERSION_FILENAME = '__version__.json'
VERSION_FILE = os.path.join(
os.path.abspath(os.path.dirname(__file__)), VERSION_FILENAME)
def lo... | nilq/baby-python | python |
from utils.orm.db import BaseModel
import httpx
import json
from sanic.log import logger as _logger
class DemoModel(BaseModel):
__tablename__ = 'demo_model'
async def demo_method(self):
print('demo method')
| nilq/baby-python | python |
import json
from operator import itemgetter
from orchard_watch import query_db
from orchard_watch import respond
annoucement_schema = [
['annoucementid', 'longValue'],
['title', 'stringValue'],
['description', 'stringValue'],
['dateTime', 'stringValue'],
['email', 'stringValue']
]
def annoucement... | nilq/baby-python | python |
# Copyright 2021 Adam Byerly. 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 agre... | nilq/baby-python | python |
import copy
import logging
from random import uniform
import matplotlib.pyplot as plt
import numpy as np
from morpho import BrillouinZonePath as BZPath
from morpho import SymmetryPoint as SPoint
from scipy.signal import find_peaks
from fdtd import EFieldDetector, Grid, HFieldDetector, Material
from fdtd.boundaries im... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T
#
# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyx... | nilq/baby-python | python |
import sys
sys.path.append('objection_engine/')
import objection_engine
# You can also import the components like this
from objection_engine.renderer import render_comment_list
from objection_engine.beans.comment import Comment
foo = [objection_engine.comment.Comment(), objection_engine.comment.Comment(text_content='Se... | nilq/baby-python | python |
from bs4 import BeautifulSoup
from bs4 import NavigableString
import requests
import logging
import pandas as pd
import json
def get_cleaned_movie(movie_bs4):
"""Get a dictionary of a movie from its bs4 object"""
# parse directors and stars arrays
movie_directors_array = []
movie_stars_array = []
... | nilq/baby-python | python |
from ...kernel import core
from ...kernel.core import VSkillModifier as V
from ...kernel.core import CharacterModifier as MDF
from ...character import characterKernel as ck
from functools import partial
class AuraWeaponBuilder():
def __init__(self, enhancer, skill_importance, enhance_importance):
self.Aura... | nilq/baby-python | python |
import datetime
import decimal
import functools
from sqlalchemy.ext.associationproxy import _AssociationList
from geojson import dumps as _dumps
from geojson.codec import PyGFPEncoder
class GeoJSONEncoder(PyGFPEncoder):
# SQLAlchemy's Reflecting Tables mechanism uses decimal.Decimal
# for numeric columns an... | nilq/baby-python | python |
# Generated by Django 3.1.7 on 2021-03-25 19:48
from django.db import migrations, models
import django.utils.timezone
import phonenumber_field.modelfields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... | nilq/baby-python | python |
import logging
import allure
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from models.auth import AuthData
from pages.app import Application
logger = logging.getLogger("moodle")
@pytest.fixture(scope="s... | nilq/baby-python | python |
class RouteException(Exception):
"""Raise when there is a general problem in a route"""
def __init__(self, message, status_code=500, data=None, *args):
self.message = message
self.status_code = status_code
self.data = data
super().__init__(message, status_code, data, *args)
cl... | nilq/baby-python | python |
"""
class to extract domain-specific terms
for examples, 'JavaScript' in CS and 'limit' in math
"""
import logging
logger = logging.getLogger(__name__)
from DST.utils.TermUtil import filterTerm
class DomainTerm(object):
"""
class to extract domain-specific terms
"""
def __init__(self, maxTermsCount=3... | nilq/baby-python | python |
"""Bare wrapper around IPOPT using numpy arrays and exception handling.
This module has an intermediate level of abstraction in the wrapping. Exception
handling is done in the callbacks and the error is signalled back to IPOPT. The
parameters in the callbacks are converted to ndarrays and the function inputs
are valid... | nilq/baby-python | python |
import omemo
from omemo_backend_signal import BACKEND as SignalBackend
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tests")))
from deletingotpkpolicy import DeletingOTPKPolicy
from dr_chat import mainLoop
import example_data
try:
input = raw_input
except Na... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... | nilq/baby-python | python |
import os
import numpy as np
from tqdm import tqdm
from stable_baselines import PPO2
from navrep.envs.navreptrainencodedenv import NavRepTrainEncodedEnv
from crowd_sim.envs.utils.info import Timeout, ReachGoal, Danger, Collision, CollisionOtherAgent
from navrep.tools.commonargs import parse_common_args
class NavRepCP... | nilq/baby-python | python |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class DbusGlib(AutotoolsPackage):
"""dbus-glib package provides GLib interface for D-Bus API.""... | nilq/baby-python | python |
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
class Meeting(models.Model):
title = models.CharField(
max_length=256,
verbose_name=_('Title'),
help_text=_('Title of the meeting')
)
... | nilq/baby-python | python |
"""Test the sum_odd_numbers function."""
import pytest
def test_nth_even():
"""test the nth_even function."""
from get_nth_number import nth_even
test_value = nth_even(100)
assert test_value == 198 | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2008, Yung-Yu Chen <yyc@solvcon.net>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyrigh... | nilq/baby-python | python |
'''
HecTime and writing Irregular time-series safely
'''
import sys
from pydsstools.heclib.dss.HecDss import Open
from pydsstools.core import TimeSeriesContainer
from pydsstools.heclib.utils import HecTime, DssLastError
dss_file = "example.dss"
fid = Open(dss_file)
def decor(func):
def f(*arg,**kwargs):
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @File : baseview.py
# @Date : 2021/2/25
# @Desc :
from rest_framework.generics import UpdateAPIView, DestroyAPIView
from rest_framework.serializers import Serializer
from rest_framework.viewsets import ModelViewSet
class FakeSerializer(Serializer):
pass
class BaseView(ModelViewSet, ... | nilq/baby-python | python |
import math
import time
import pytest
from . import assert_javascript_entry
@pytest.mark.asyncio
async def test_types_and_values(bidi_session, current_session, inline, wait_for_event):
await bidi_session.session.subscribe(events=["log.entryAdded"])
on_entry_added = wait_for_event("log.entryAdded")
exp... | nilq/baby-python | python |
"""
LibriParty Dataset creation by using official metadata.
Author
------
Samuele Cornell, 2020
Mirco Ravanelli, 2020
"""
import os
import sys
import speechbrain as sb
from hyperpyyaml import load_hyperpyyaml
from speechbrain.utils.data_utils import download_file
from local.create_mixtures_from_metadata import create... | nilq/baby-python | python |
import simplejson as json
class PConf():
def __init__(self, filename="", schema={}):
"""initialize with a schema dictionary"""
if not filename or not isinstance(schema, dict):
return None
with open(filename, "r") as f:
self.conf = json.loads(f.read())
self.schema = schema
self.validate(self.conf, ... | nilq/baby-python | python |
from flask import request
def get_locale():
rv = request.accept_languages.best_match(['zh', 'en'])
return rv or 'en'
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2022 askusay
#
# 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 b... | nilq/baby-python | python |
from pyit.cop import ITokenCop, Cop
from pyit.offence import Offence
from token import *
class SpaceIndentationCop(Cop):
COP_CONFIG = {}
OPEN_BRACKETS = {
'(': LPAR,
'[': LSQB,
'{': LBRACE,
}
CLOSE_BRACKETS = {
'}': RBRACE,
']': RSQB,
')': RPAR,
}
... | nilq/baby-python | python |
import sys
import pandas as pd
import matplotlib.pyplot as plt
sys.path.append('../minvime')
import estimator_classification as esti # The file ../minvime/estimator_classification.py
fprates = [0.0, 0.00001, 0.0001, 0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.015,
0.02,0.025, 0.03, 0.035, 0.04, 0.045, 0... | nilq/baby-python | python |
# -*- coding: utf-8 -*- #
# Copyright 2021 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 requir... | nilq/baby-python | python |
from flask import Flask, jsonify, request
from pymongo import MongoClient
from flask_script import Manager, Command, Shell
from flask_mail import Mail, Message
import nltk
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer
from nltk import word_tokenize, pos_tag
from tenseflow ... | nilq/baby-python | python |
from mayan.apps.appearance.classes import Icon
icon_statistics = Icon(driver_name='fontawesome', symbol='chart-line')
icon_execute = Icon(driver_name='fontawesome', symbol='cog')
icon_namespace_details = Icon(driver_name='fontawesome', symbol='chart-line')
icon_namespace_list = Icon(driver_name='fontawesome', symbol='... | nilq/baby-python | python |
from distutils.core import setup
# py2exe stuff
import py2exe, os
# find pythoncard resources to add as 'data_files'
pycard_resources=[]
for filename in os.listdir('.'):
if filename.find('.rsrc.')>-1:
pycard_resources+=[filename]
# includes for py2exe
includes=[]
for comp in ['button','multicolumnlist','s... | nilq/baby-python | python |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import shutil
from pathlib import Path
from typing import Tuple
import subprocess
import tempfile
import pytest
from flexmock import flexmock
from packit.utils.commands import cwd
from packit.utils.repo import create_new_repo
from tests.s... | nilq/baby-python | python |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import unittest
import numpy as np
import six
import tensorflow as tf
from tfsnippet.bayes import Bernoulli
from tests.helper import TestCase
from tests.bayes.distributions._helper import (DistributionTestMixin,
BigNumberVerifyTestMixin,
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
" The code for the sc2 environment, maybe add some functions for the original pysc2 version "
# modified from AlphaStar pseudo-code
import numpy as np
from s2clientprotocol import sc2api_pb2 as sc_pb
from pysc2 import run_configs
from pysc2.lib import features
from pys... | nilq/baby-python | python |
"""definition of problem instance
Author: Keisuke Okumura
Affiliation: TokyoTech & OSX
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Optional, Union
import numpy as np
from .obstacle import Obstacle, ObstacleSphere
from .static_objects import StaticObjects
@dat... | nilq/baby-python | python |
# ptif_uploader script / webhook
# The developement has been resumed from uploader_jyhton
# Designed to use models from slide-atlas
__author__ = 'dhan'
#TODO: Extend the uploader for
# - Wrapping c++ image_uploader for ndpi and jp2 images
#noqua E501
import os
import sys
import argparse
# from celery import Celery... | nilq/baby-python | python |
import warnings
import math
from typing import Optional, TypeVar
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from torch.nn import init
from torch.nn.parameter import Parameter
import torchshard as ts
class ParallelLoss(Module):
"""
... | nilq/baby-python | python |
# Generated by nuclio.export.NuclioExporter
import os
import pandas as pd
import numpy as np
import scipy as sp
import pickle
import datetime
import v3io_frames as v3f
import matplotlib.pyplot as plt
from sklearn.preprocessing import KBinsDiscretizer
def to_observations(context, t, u, key):
t = (
t.app... | nilq/baby-python | python |
from django.db import models
class Author(models.Model):
"""
An `Article` author
Attributes:
name (CharField):
Author name.
email (EmailField):
Author email.
"""
name = models.CharField(max_length=255)
email = models.EmailField()
class Article(models... | nilq/baby-python | python |
allData = {'AK': {'Aleutians East': {'pop': 3141, 'tracts': 1},
'Aleutians West': {'pop': 5561, 'tracts': 2},
'Anchorage': {'pop': 291826, 'tracts': 55},
'Bethel': {'pop': 17013, 'tracts': 3},
'Bristol Bay': {'pop': 997, 'tracts': 1},
'Denali': {'pop': 1826, 'tracts': 1},
... | nilq/baby-python | python |
import torch
import getopt
import math
import numpy
import os
import PIL
import PIL.Image
import sys
import torch.nn.functional as F
import torchvision.transforms as transforms
import skimage.io as io
import numpy as np
from skimage import morphology
from scipy import ndimage
import math
transform = transforms.Compos... | nilq/baby-python | python |
import ssl
import sys
import json
import os
import requests
import toml
import atexit
import re
import traceback
from pyVim import connect
from pyVmomi import vim
from pyVmomi import vmodl
# GLOBAL_VARS
DEBUG = False
# CONFIG
VC_CONFIG = '/var/openfaas/secrets/vcconfig'
service_instance = None
class bgc:
HEADER... | nilq/baby-python | python |
from datetime import datetime
from product import Product
class Slides(Product):
def __init__(self, raw_product):
Product.__init__(self, raw_product)
bib_info = raw_product.get('slides', {})
self._parse_bib_info(bib_info)
def _parse_bib_info(self, bib_info):
self._repository =... | nilq/baby-python | python |
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from data_crystal.settings import URL_PREFIX
from data_manager.models import Data
###############################################################################
def app_home(request):
template = loader.get_temp... | nilq/baby-python | python |
import argparse
import torch
import torch.nn.functional as F
from gat_conv import GATConv
from torch.nn import Linear
from datasets import get_planetoid_dataset
from snap_dataset import SNAPDataset
from suite_sparse import SuiteSparseMatrixCollection
from train_eval_cs import run
import pdb
from torch_geometric.nn impo... | nilq/baby-python | python |
import os
from config.defaults import *
if os.environ.get("ENV") == 'dev':
print("==== Loading DEV environment ====")
from config.local import *
elif os.environ.get("ENV") == 'docker':
print("==== Loading Docker environment ====")
from config.docker import *
else:
print("==== Loading HERKOU enviro... | nilq/baby-python | python |
from typing import Any, Dict, List, Optional, Tuple, Type, Union
import gym
import numpy as np
from stable_baselines3.common.distributions import SquashedDiagGaussianDistribution
import torch as th
from torch.distributions.multivariate_normal import MultivariateNormal
import torch.nn as nn
from torch.nn.utils ... | nilq/baby-python | python |
import os
import urllib2
import uuid
import falcon
import mimetypes
import requests
import logging
from datetime import datetime
__author__ = 'Maged'
logging.basicConfig(filename='dropbox_upload_manager.log', level=logging.DEBUG)
WGET_CMD = '/usr/bin/wget'
ALLOWED_TYPES = (
'text/plain',
'image/gif',
'i... | nilq/baby-python | python |
from unittest import TestCase, main
from os import remove
from os.path import exists, join
from datetime import datetime
from shutil import move
from biom import load_table
import pandas as pd
from qiita_core.util import qiita_test_checker
from qiita_db.analysis import Analysis, Collection
from qiita_db.job import Jo... | nilq/baby-python | python |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='pdt-r']/div[@class='t']/div[@class='l']/h1",
'price' : "//div[@class='l']/div/p/span",
'category' : "//body/form[@id... | nilq/baby-python | python |
"""pydantic models for GeoJSON Feature objects."""
from typing import Dict, Generic, List, Optional, TypeVar
from pydantic import Field, validator
from pydantic.generics import GenericModel
from geojson_pydantic.geometries import Geometry
from geojson_pydantic.types import BBox
Props = TypeVar("Props", bound=Dict)
... | nilq/baby-python | python |
"""Async version of stream-unzip (https://github.com/uktrade/stream-unzip). MIT License."""
import zlib
from struct import Struct
async def stream_unzip(zipfile_chunks, chunk_size=65536):
local_file_header_signature = b'\x50\x4b\x03\x04'
local_file_header_struct = Struct('<H2sHHHIIIHH')
zip64_compressed_... | nilq/baby-python | python |
"""
Given two sequences ‘s1’ and ‘s2’, write a method to find the length
of the shortest sequence which has ‘s1’ and ‘s2’ as subsequences.
Example 2:
Input: s1: "abcf" s2:"bdcf"
Output: 5
Explanation: The shortest common super-sequence (SCS) is "abdcf".
Example 2:
Input: s1: "dynamic" s2:"programming"
Output: 1... | nilq/baby-python | python |
"""The yale_smart_alarm component."""
| nilq/baby-python | python |
import numpy as np #import numpy library
#intergers
i=10
print(type(i)) #print out the data type 1
a_i = np.zeros(i,dtype=int) #declare an array of ints
print(type(a_i)) #will return ndarray
print(type(a_i[0])) #will return int64
#floats
x = 119.0 #floating point number
print(type(x)) #print out the... | nilq/baby-python | python |
"""Utilties for distributed processing"""
import horovod.tensorflow.keras as hvd
def rank():
try:
return hvd.rank()
except ValueError:
return 0
def barrier():
try:
hvd.allreduce([], name='Barrier')
except ValueError:
pass
| nilq/baby-python | python |
import os
import time
import pytest
from rhcephcompose.compose import Compose
from kobo.conf import PyConfigParser
import py.path
@pytest.fixture
def conf(fixtures_dir):
conf_file = os.path.join(fixtures_dir, 'basic.conf')
conf = PyConfigParser()
conf.load_from_file(conf_file)
return conf
class Test... | nilq/baby-python | python |
# Copyright 2020 The TensorFlow Probability Authors.
#
# 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 o... | nilq/baby-python | python |
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... | nilq/baby-python | python |
'''
Created on Jul 13, 2018
@author: friedl
'''
import subprocess
import sys
def run_bwa_aln(genome_index, fastq_in_file, sai_out_file, bwa_path='bwa', threads=1, R_param=None):
''' calls bwa aln '''
# build bwa command
command = [bwa_path, 'aln', '-t', str(threads), '-f', sai_out_file]
if(R_par... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Given the taxonomy output from AlchemyAPI, for each level of taxonomies, extract the graph
so that the taxons in this level are connected based on
***Jaccardi score*** for the users sharing these taxons in their tweets
"""
import codecs
from collections import defau... | nilq/baby-python | python |
# Copyright 2017 Neosapience, Inc.
#
# 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 wri... | nilq/baby-python | python |
# problems init file
from tigerforecast.problems.core import Problem
from tigerforecast.problems.sp500 import SP500
from tigerforecast.problems.uci_indoor import UCI_Indoor
from tigerforecast.problems.enso import ENSO
from tigerforecast.problems.crypto import Crypto
from tigerforecast.problems.random import Random
fro... | nilq/baby-python | python |
import sys
sys.path.append('..')
import torch.nn as nn
import torch
class ConvBlock(nn.Module):
"""Layer to perform a convolution followed by LeakyReLU
"""
def __init__(self, in_channels, out_channels):
super(ConvBlock, self).__init__()
self.conv = Conv3x3(in_channels, out_channels)
... | nilq/baby-python | python |
import os
import pickle
import socket
import threading
import time
from cryptography.fernet import Fernet
from scripts import encryption
from scripts.consts import MessageTypes
# IP = socket.gethostbyname(socket.gethostname())
IP = 'localhost'
PORT = 8004
class Server:
def __init__(self):
self.active_co... | nilq/baby-python | python |
#!/usr/bin/env python
import pytest
import os
import sys
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
from pathlib import Path
from dselib.thread import initTLS
initTLS()
from dselib.context import DSEContext
from dselib.defaults import Defaults
from dselib... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.