content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import re # noinspection PyShadowingBuiltins def all(_path): return True def path_contains(*subs): def func(path): return any(map(path.__contains__, subs)) return func def contains_regex(pattern): def func(path): with open(path) as f: code = f.read() return boo...
nilq/baby-python
python
#### import the simple module from the paraview from paraview.simple import * #### disable automatic camera reset on 'Show' paraview.simple._DisableFirstRenderCameraReset() # get color transfer function/color map for 'DICOMImage' dICOMImageLUT = GetColorTransferFunction('DICOMImage') # Rescale transfer function dICOM...
nilq/baby-python
python
from django.db.models.signals import post_save from django.dispatch import receiver from django.core.cache import cache from .models import * @receiver(post_save, sender=Email) def question__delete_caches_on_create(sender, instance, created, **kwargs): cache_name = "get_sent_emails_user_id_" + str(1) if(cache_name i...
nilq/baby-python
python
from flask import Blueprint, session, redirect, render_template, request, flash, url_for, abort from models import PageDetails, Database,Authentication, General from functools import wraps from validator_collection import * admin_remove = Blueprint("admin_remove", __name__) @admin_remove.route("/Admin/Remove", metho...
nilq/baby-python
python
# # Test Netatmo class # import logging import Netatmo def main(): logging.basicConfig(level=logging.DEBUG) netatmo = Netatmo.Netatmo("PyAtmo.conf") home=netatmo.getHomesData() netatmo.getHomeStatus() if __name__ == "__main__": main()
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 json import random from flask import Flask, request from flask_restplus import Resource, Api, Namespace import os from datetime import date, datetime from faker import Faker import security fake = Faker('en_AU') ## load bsb data into memory with open('./resources/bsbs.json') as json_file: bsbs = json.load(...
nilq/baby-python
python
import os import pathlib import re from collections import defaultdict from functools import lru_cache import stanza import torch from loguru import logger from nlgeval import NLGEval from transformers import AutoModelForCausalLM, AutoTokenizer current_dir = pathlib.Path(__file__).parent.absolute() def step_len(fun...
nilq/baby-python
python
# # Copyright (c) nexB Inc. and others. All rights reserved. # VulnerableCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/vulnerablecode for support or download. # See https://aboutcode.org for mor...
nilq/baby-python
python
__all__ = ("MDRenderer", "LOGGER", "RenderTreeNode", "DEFAULT_RENDERER_FUNCS") import logging from types import MappingProxyType from typing import Any, Mapping, MutableMapping, Sequence from markdown_it.common.normalize_url import unescape_string from markdown_it.token import Token from mdformat.renderer._default_...
nilq/baby-python
python
import numpy as np from utils import env_paths as paths from base import Train import time class TrainModel(Train): def __init__(self, model, output_freq=1, pickle_f_custom_freq=None, f_custom_eval=None): super(TrainModel, self).__init__(model, pickle_f_custom_freq, f_custom_eval) ...
nilq/baby-python
python
from typing import Text, Type from aiogram import types from aiogram.dispatcher.filters.builtin import Command, Text from aiogram.dispatcher import FSMContext from aiogram.types import message from middlewares.states.all_states import download_sticker_state import os from loader import dp @dp.message_handler(text="/c...
nilq/baby-python
python
import csv import argparse import enum import sys from normalizer import normalizer from common import common def RepresentsFloat(val): try: float(val) return True except ValueError: return False if __name__ == "__main__": ft_type = enum.Enum("ft_type", ("train", "valid")) p...
nilq/baby-python
python
import os import sys import json import tweepy import requests import pandas as pd from defipulse import DefiPulse from coingecko import CoinGecko from subprocess import call # Data Preprocessing and Feature Engineering consumer_key = os.environ.get('TWITTER_CONSUMER_KEY', 'ap-northeast-1') consumer_secret = os.enviro...
nilq/baby-python
python
# # Copyright (c) 2021 Incisive Technology Ltd # # 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, pu...
nilq/baby-python
python
"""Remote apps ============= """
nilq/baby-python
python
import os import sqlite3 ''' THING I THINK I'M MISSING The completed date shouldn't be a boolean because it can be overdue. It was an integer before so it could be set to the date in which it was marked completed. This should be changed back. ''' class Equipment: def __init__(self, pk=-1, name=''): sel...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy import Item, Field from collections import OrderedDict import six class ScholarshipItem(Item): University = Field() Program = Field() Degree = ...
nilq/baby-python
python
import boto3 import csv profile = "default" def get_instance(instance_name): ec2 = boto3.resource('ec2') return ec2.instances.filter(Filters=[{'Name': 'tag:Name', 'Values': [instance_name]}]) boto3.setup_default_session(profile_name=profile) ec2 = boto3.client('ec2') ec2_list = [] sg_name_dict = {} # dict ...
nilq/baby-python
python
# Copyright 2017-present Open Networking Foundation # # 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 agr...
nilq/baby-python
python
from ..resources.resource import Resource import requests from requests.auth import HTTPBasicAuth class Suppliers(Resource): def __init__(self): super().__init__("suppliers") def delete(self, id): raise NotImplementedError("Not possible to post a warehouse")
nilq/baby-python
python
def tree(x): print("\n".join([f"{'*'*(2* n + 1):^{2*x+1}}" for n in range(x)])) def trunk(n): for i in range(n): for j in range(n-1): print(' ', end=' ') print('***') tree(1) trunk(3)
nilq/baby-python
python
# -*- coding: utf-8 -*- import tkinter as tk from tkinter import messagebox import algoritmo import aicSpider class SampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self._frame = None self.switch_frame(StartPage) def switch_frame(self, frame_class): """Destroi frame ...
nilq/baby-python
python
from django.conf import settings from django.urls import include, path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("...
nilq/baby-python
python
import argparse import os import torch from torch import nn, optim from torch.nn import functional as F from torch.utils.data import DataLoader from torchvision import datasets, transforms # setup parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, defaul...
nilq/baby-python
python
"""Using a class as a decorator demo. Count the number of times a function is called. """ class CallCount: def __init__(self, function): self.f = function self.count = 0 def __call__(self, *args, **kwargs): self.count = 1 return self.f(*args, **kwargs) @property de...
nilq/baby-python
python
# Copyright (c) Open-MMLab. All rights reserved. from mmcv.runner.hooks.hook import HOOKS, Hook @HOOKS.register_module() class AlternateTrainingHook(Hook): # def before_train_iter(self, runner): def before_train_epoch(self, runner): runner.model.module.neck.epoch_num = runner._epoch # if runner...
nilq/baby-python
python
import os import logging from flask import Flask from slack import WebClient from slackeventsapi import SlackEventAdapter # Initialize a Flask app to host the events adapter app = Flask(__name__) # Create an events adapter and register it to an endpoint in the slack app for event injestion. slack_events_adapter = Slac...
nilq/baby-python
python
import os import sys import glob import argparse import numpy as np from PIL import Image from Utility import * from keras.applications.vgg16 import VGG16, preprocess_input from keras.models import Model, load_model from keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization from keras.preprocessing.im...
nilq/baby-python
python
from __future__ import absolute_import from .base import Model from .base import DifferentiableModel class ModelWrapper(Model): """Base class for models that wrap other models. This base class can be used to implement model wrappers that turn models into new models, for example by preprocessing the ...
nilq/baby-python
python
from jinja2 import Template import bot_logger import lang import models def help_user(msg): user = models.User(msg.author.name) if user.is_registered(): msg.reply(Template(lang.message_help + lang.message_footer).render( username=msg.author.name, address=user.address)) else: b...
nilq/baby-python
python
#!/usr/bin/env python import sys import random import itertools import ast def nbackseq(n, length, words): """Generate n-back balanced sequences :param n: int How many characters (including the current one) to look back to assure no duplicates :param length: int The total length o...
nilq/baby-python
python
sir = "mere pere droguri mofturi CamIoane" rime = {} for i in range(len(sir)): if (i == 0 or sir[i - 1] == " "): k = i if (sir[i] == " "): if (rime.get(sir[i - 2:i]) == None): rime[sir[i - 2:i]] = [sir[k:i]] else: rime[sir[i - 2:i]].append(sir[k:i]) ...
nilq/baby-python
python
import os import sys import cherrypy import ConfigParser import urllib import urllib2 import simplejson as json import webtools import time import datetime import random import pprint from pyechonest import song as song_api, config config.TRACE_API_CALLS=True config.ECHO_NEST_API_KEY='EHY4JJEGIOFA1RCJP' import collec...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ppretredit.ui' # # Created: Mon Jan 11 21:22:20 2010 # by: PyQt4 UI code generator 4.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_TrainerEditDlg(object): def setupUi(self, Tra...
nilq/baby-python
python
import datetime as dt import smtplib import random import pandas import os PLACEHOLDER = "[NAME]" MY_EMAIL = "my_email@gmail.com" MY_PASSWORD = "my_password" LETTER_TO_SEND = "" now = dt.datetime.now() is_day = now.day is_month = now.month data = pandas.read_csv("./birthdays.csv") birthdays = data.to_dict(orient="rec...
nilq/baby-python
python
# coding=utf-8 import json from ibm_watson import LanguageTranslatorV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your_api_key') language_translator = LanguageTranslatorV3( version='2018-05-01', authenticator=authenticator) language_translator.set_service_u...
nilq/baby-python
python
# TODO: support axis=k to create multiple factors for each row/col # TODO: knapsack (how to pass costs? must check broadcast/shape) class Logic(object): def __init__(self, variables): self._variables = variables # TODO: deal with negated def _construct(self, fg, variables): return [fg.crea...
nilq/baby-python
python
import sys import os import numpy as np import shutil from common import PostProcess, update_metrics_in_report_json from common import read_limits, check_limits_and_add_to_report_json #from common import VirtualVehicleMakeMetrics as VVM def main(): print "in main....." sampleRate = 0.10 startAna...
nilq/baby-python
python
# Algorithms > Warmup > Simple Array Sum # Calculate the sum of integers in an array. # # https://www.hackerrank.com/challenges/simple-array-sum/problem # # # Complete the simpleArraySum function below. # def simpleArraySum(ar): # # Write your code here. # return sum(ar) if __n...
nilq/baby-python
python
from cached_property import cached_property from onegov.activity import Activity, Attendee, Booking, Occasion from onegov.feriennet import _ from onegov.feriennet import FeriennetApp from onegov.feriennet.collections import BillingCollection, MatchCollection from onegov.feriennet.exports.unlucky import UnluckyExport fr...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Configurations for slimming simple network. - Author: Curt-Park - Email: jwpark@jmarple.ai """ from config.train.cifar100 import simplenet, simplenet_finetune train_config = simplenet.config regularizer_params = { "REGULARIZER": "BnWeight", "REGULARIZER_PARAMS": dict(coeff=1e-5), ...
nilq/baby-python
python
# hack to capture stdout to a string, to test it import re import os import subprocess import io import sys from contextlib import contextmanager import filecmp def test_rr_cases(): # now for various combinations of inputs output_file = 'test_output.csv' # test exact round robin case, but just once ...
nilq/baby-python
python
from gpkit import Model, Variable, VectorVariable, SignomialsEnabled import numpy as np class MST(Model): def setup(self, N): edgeCost = VectorVariable([N, N], 'edgeCost') edgeMaxFlow = VectorVariable([N, N], 'edgeMaxFlow') ...
nilq/baby-python
python
import pytest from auth import create_jwt_payload @pytest.mark.usefixtures("default_qr_code") def test_qr_exists(client, default_qr_code): code = default_qr_code["code"] graph_ql_query_string = f"""query CheckQrExistence {{ qrExists(qrCode: "{code}") }}""" data = {"query": grap...
nilq/baby-python
python
import os import time import requests from flask import render_template, request, flash, redirect, url_for, abort from jinja2 import Markup from app import app, PLOTS_FOLDER, UPLOAD_FOLDER from functions import dir_listing, process_images @app.route('/') def home(): return render_template('home.html') @app.ro...
nilq/baby-python
python
# Packages from sys import argv, exit from os.path import realpath, dirname from flask import Flask from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from flask_sqlalchemy import SQLAlchemy # Local from config import Config path = dirname(realpath(__file__)) secret = "%s/app/app.secre...
nilq/baby-python
python
#! /usr/bin/env python from __future__ import print_function from builtins import str import sys import os from vmrunner import vmrunner import socket # Get an auto-created VM from the vmrunner vm = vmrunner.vms[0] def UDP_test(trigger_line): print("<Test.py> Performing UDP tests") HOST, PORT = "10.0.0.55", 4242...
nilq/baby-python
python
#!/usr/bin/python3 spam = ['apples', 'bannanas', 'tofus', 'cats'] length = len(spam) item = 0 while item < length - 1: print(spam[item], end=' ') item = item + 1 print(' and ' + spam[item])
nilq/baby-python
python
from SOC.models import Manna import numpy as np import pytest def test_boundary_shape(): sim = Manna(L=10) assert sim.values.shape == (12, 12) assert sim.L_with_boundary == 12 def test_run_abel(): sim = Manna(L=20) sim.run(5) def test_run_nonabel(): sim = Manna(L=20, abelian = False) sim....
nilq/baby-python
python
# Copyright 2020 PerfKitBenchmarker Authors. 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 appli...
nilq/baby-python
python
# Code adapted from https://github.com/araffin/learning-to-drive-in-5-minutes/ # Author: Sheelabhadra Dey import argparse import os import time from collections import OrderedDict from pprint import pprint import numpy as np import yaml from stable_baselines.common import set_global_seeds from stable_baselines.common....
nilq/baby-python
python
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTI...
nilq/baby-python
python
from glue.config import DictRegistry __all__ = ['viewer_registry', 'ViewerRegistry'] class ViewerRegistry(DictRegistry): """ Registry containing references to custom viewers. """ def __call__(self, name=None): def decorator(cls): self.add(name, cls) return cls ...
nilq/baby-python
python
# -*- coding: utf-8 -*- ''' Code List Object =============== ''' from __future__ import annotations __all__ = ('CodeList',) from typing import Tuple from builder.commands.scode import SCode from builder.datatypes.builderexception import BuilderError from builder.utils import assertion from builder.utils.logger impo...
nilq/baby-python
python
# import logging from xml.etree import ElementTree as ET import lxml.etree as LET from ckeditor.fields import RichTextField from acdh_tei_pyutils.tei import TeiReader from curator.models import Upload # Create your models here. from django.db import models from django.utils.timezone import now from .namespaces import ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django_fsm.db.fields.fsmfield class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
nilq/baby-python
python
from pycket.interpreter import ( App, Begin, Begin0, BeginForSyntax, CaseLambda, Cell, CellRef, DefineValues, If, Lambda, Let, Letrec, LexicalVar, Module, ModuleVar, LinkletVar, Quote, QuoteSyntax, Require, SetBang, ToplevelVar, Va...
nilq/baby-python
python
# -*- coding: UTF-8 -*- """ @CreateDate: 2021/07/25 @Author: Xingyan Liu @File: builder.py @Project: stagewiseNN """ import os import sys from pathlib import Path from typing import Sequence, Mapping, Optional, Union, Callable import logging import pandas as pd import numpy as np from scipy import sparse import scanpy ...
nilq/baby-python
python
# A import performance test of standard classes, dataclasses, attrs, and cluegen import sys import time standard_template = ''' class C{n}: def __init__(self, a, b, c, d, e): self.a = a self.b = b self.c = c self.d = d self.e = e def __repr__(self): return f'C{...
nilq/baby-python
python
from __future__ import print_function from __future__ import division from collections import defaultdict, OrderedDict from itertools import izip import numbers from time import time import itertools import math import scipy.sparse as sparse import sklearn from sklearn.base import BaseEstimator from sklearn.ensemble i...
nilq/baby-python
python
# -*- encoding: utf-8 -*- text = u""" Mr. Speaker, Mr. President, distinguished Members of the Congress, honored guests, and fellow citizens: I come before you to report on the state of our Union, and I'm pleased to report that after 4 years of united effort, the American people have brought forth a nation renewed, s...
nilq/baby-python
python
# # PySNMP MIB module HUAWEI-SEP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-SEP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:36:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
nilq/baby-python
python
import unittest import unittest.mock import denonavr.__main__ as avr class TestDenonAVR(unittest.TestCase): def test_valid_input_source(self): self.assertTrue(avr._is_valid_input_source("DVD")) self.assertTrue(avr._is_valid_input_source("BD")) self.assertTrue(avr._is_valid_input_source("G...
nilq/baby-python
python
from ...hek.defs.obje import * def get(): return obje_def # replace the model animations dependency with an open sauce one obje_attrs = dict(obje_attrs) obje_attrs[8] = dependency('animation_graph', valid_model_animations_yelo) obje_body = Struct('tagdata', obje_attrs ) obje_def = TagDef("o...
nilq/baby-python
python
class Coordenadas(): def __init__(self, coordenadaX , coordenadaY): self.coordenadaX = coordenadaX self.coordenadaY = coordenadaY def valores(self): print("Los valores ingresados fueron:","(" , self.coordenadaX,",", self.coordenadaY ,")") def cuadrante(self): if...
nilq/baby-python
python
import sys import unittest import os script_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(1, os.path.abspath( os.path.join(script_dir, os.path.join('..', '..')))) import pake class SubpakeTest(unittest.TestCase): def file_helper_test_stub(self, ctx, silent): fp = pake.FileHelp...
nilq/baby-python
python
import sys import re def main(): file = sys.stdin if file.isatty(): filename = input('Input file name: ') file = open(filename) rules = file.readlines() file.close() bags = parseRules(rules) shinyGoldBag = bags['shiny gold'] shinyGoldContainers = shinyGoldBag.findCont...
nilq/baby-python
python
import copy import logging import os import typing import yaml from nbcollection.ci.constants import ENCODING, SCANNER_ARTIFACT_DEST_DIR from nbcollection.ci.generate_ci_environment.constants import NBCOLLECTION_BUILDER, CONFIG_TEMPLATE, JOB_TEMPLATE, \ PULL_REQUEST_TEMPLATE, NBCOLLECTION_WORKFLOW_NAME, PUBLIS...
nilq/baby-python
python
""" protonate.py: Wrapper method for the reduce program: protonate (i.e., add hydrogens) a pdb using reduce and save to an output file. Pablo Gainza - LPDI STI EPFL 2019 Released under an Apache License 2.0 """ from subprocess import Popen, PIPE import os from ipdb import set_trace def protonate(in_...
nilq/baby-python
python
import collections import logging from arekit.common.data.input.providers.opinions import OpinionProvider logger = logging.getLogger(__name__) class BaseRowProvider(object): """ Base provider for rows that suppose to be filled into BaseRowsStorage. """ # region protected methods def _provide_rows(...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') requirements = [ 'pan-python', ] test_requirements = [ 'pan-pyt...
nilq/baby-python
python
class Activation(object): def __init__(self): pass from deepend.activations.Softmax import Softmax from deepend.activations.LeakyReLU import LeakyReLU from deepend.activations.Linear import Linear from deepend.activations.TanH import TanH from deepend.activations.Sigmoid import Sigmoid from deepend.activations.ReLU...
nilq/baby-python
python
"""Exemplo melhorias de Contraste.""" from PIL import Image, ImageEnhance im = Image.open('beijo.jpg') contrast = ImageEnhance.Contrast(im) contrast.enhance(1.2) contrast.show()
nilq/baby-python
python
#!/usr/bin/python ############################ # Librairies import ############################ import os import checkUserInput ############################ # Functions ############################ def confirmation_address(address, what): confirmation = False if checkUserInput.question_and_verification("Confirmez...
nilq/baby-python
python
# -*- python -*- import logging import unittest import electionfraud.testdata as eftd import electionfraud.redist as redist logging.basicConfig(level=logging.DEBUG) class RedistributorTest(unittest.TestCase): pass class TestIdentity(RedistributorTest): def setUp(self): self.rd = redist.Identity(ef...
nilq/baby-python
python
#%% cell """ # Solving a New Keynesian model with Python This file is part of a computational appendix that accompanies the paper. > MATLAB, Python, Julia: What to Choose in Economics? > > Coleman, Lyon, Maliar, and Maliar (2017) In order to run the codes in this file you will need to install and configure a few Pyt...
nilq/baby-python
python
arr = [1, 34, 3, 98, 9, 76, 45, 4] l = len(arr) digits =[] # # Uncomment and use either of the 2 digitconverter # def digitconverter(num): # # digit = [] # while num !=0: # digits.append(num%10) # num = num//10 # def digitconverter(num): # number = str(num) # for i in ra...
nilq/baby-python
python
from rest_framework.serializers import ModelSerializer from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import IdentifiedBaseStation, Operator class IdentifiedBaseStationSerializer(GeoFeatureModelSerializer): class Meta: model = IdentifiedBaseStation geo_field = '...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import pathlib import pickle import yaml import numpy as np from librosa import load from tools import yaml_loader __author__ = 'Konstantinos Drossos -- Tampere University' __docformat__ = 'reStructuredText' __all__ = [ 'dump_pickle_file', 'load_pickle_file', 'read_t...
nilq/baby-python
python
# Generated by Django 3.2.7 on 2021-09-17 12:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Course', '0001_initial'), ] operations = [ migrations.CreateModel( name='LearnGroup', fields=[ ('id'...
nilq/baby-python
python
import gym import copy env = gym.make('LunarLander-v2') env.seed(111) # we cna fix the background for now env.action_space.np_random.seed(123) #fix random actions for now env.reset() for step in range(60): #input() env.render() #save info before action if step == 55: save_state = copy.copy(info)...
nilq/baby-python
python
import asyncio import inspect import warnings import functools from typing import Callable, Generic, TypeVar, Type, Optional def deprecated(reason, stacklevel=2) -> Callable: """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the f...
nilq/baby-python
python
# Copyright 2013-2022 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) import os from spack.package import * class HashTest3(Package): """Used to test package hashing """ homepa...
nilq/baby-python
python
""" Yandex Transport Webdriver API. Continuous Monitoring tests. NOTE: These are designed to run indefinitely and check current YandexTransportAPI status. Tests are working with Live Data, with several random delays between them. They take a lot of time as a result. NOTE: Tests require running YandexTrans...
nilq/baby-python
python
from __future__ import ( absolute_import, unicode_literals, ) import importlib import os import pytest @pytest.fixture(scope='module') def server_settings(server_class): """ Load the server_settings used by this service. """ if server_class.use_django: from django.conf import setting...
nilq/baby-python
python
#! /usr/bin/env python3 from setuptools import find_packages from setuptools import setup def parse_requirements(filename): """Given a filename, strip empty lines and those beginning with #.""" with open(filename) as rfd: output = [] for line in rfd: line = line.strip() ...
nilq/baby-python
python
import torch from allennlp.common.testing import AllenNlpTestCase from allennlp.common.params import Params from allennlp.training.learning_rate_schedulers import ( LearningRateScheduler, CombinedLearningRateScheduler, PolynomialDecay, ) from allennlp.training.optimizers import Optimizer class TestCombin...
nilq/baby-python
python
#!/usr/bin/python3 for i in range(122, 96, -1): if i % 2 == 0: print("{:s}".format(chr(i)), end="") else: print("{:s}".format(chr(i-32)), end="")
nilq/baby-python
python
# -*- coding: utf-8 -*- ## @package palette.main # # Main funcion. # @author tody # @date 2015/08/20 from palette.datasets.google_image import createDatasets from palette.results.single_image import signleImageResults from palette.results.multi_images import multiImagesResults if __name__ == '__main__'...
nilq/baby-python
python
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence class RNN(nn.Module): def __init__(self, config): """ type_rnn: RNN, GRU, LSTM 可选 """ super(RNN, self).__init__() # self.xxx = config.xxx self.input_size = c...
nilq/baby-python
python
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or '28#oN^^VfhcxV7x8H32yGOGIk2wLY%OFi!!V' ### email configs,https://pythonhosted.org/Flask-Mail/ ### MAIL_SERVER = os.environ.get('MAIL_SERVER') MAIL_PORT = int(os.environ.get('MA...
nilq/baby-python
python
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
nilq/baby-python
python
import os import sys sys.path.append( os.path.normpath( os.path.join(os.path.abspath(__file__), "..", "..", "..", "common") ) ) from env_indigo import * indigo = Indigo() indigo.setOption("ignore-stereochemistry-errors", True) indigo.setOption("molfile-saving-skip-date", True) def testSerializeIsoto...
nilq/baby-python
python
import arrow import dateutil import requests COUNTRY_CODE = 'RO' def fetch_RO(): url = 'http://www.transelectrica.ro/sen-filter' data = {} for item in requests.get(url).json(): d = list(item.iteritems())[0] data[d[0]] = d[1] obj = { 'countryCode': COUNTRY_CODE, 'da...
nilq/baby-python
python
from claf.config.factory.data_reader import DataReaderFactory from claf.config.factory.data_loader import DataLoaderFactory from claf.config.factory.model import ModelFactory from claf.config.factory.optimizer import OptimizerFactory from claf.config.factory.tokens import TokenMakersFactory __all__ = [ "DataRead...
nilq/baby-python
python
import os import shutil from datetime import datetime from os.path import dirname, join import torch class Logger(): def __init__(self, para): self.para = para now = datetime.now() if 'time' not in vars(para) else para.time now = now.strftime("%Y_%m_%d_%H_%M_%S") mark = para.model...
nilq/baby-python
python
############################################################################### # Exceptions ############################################################################### class UnexpectedCharacter(Exception): def __init__(self, char, idx, matcher): super().__init__( 'Expected {} at position ...
nilq/baby-python
python
from ex112_1.utilidadescev import moeda, dados preco = dados.leiadinheiro('Digite o preço: ') moeda.resumo(preco, 90, 35)
nilq/baby-python
python
#!/usr/bin/env python3 """ Filters for masking stationary or near stationary data based on vessel speed """ def mask_stationary(Sv, speed, threshold): """ Mask stationary or near stationary data based on vessel speed Args: Sv (float): 2D numpy array with Sv data to be masked (dB) spee...
nilq/baby-python
python