content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import torch
import shutil
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
def rotation(inputs):
batch = inputs.shape[0]
target = torch.Tensor(np.random.permutat... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""These test the utils.py functions."""
from __future__ import unicode_literals
import pytest
from hypothesis import given
from hypothesis.strategies import binary, floats, integers, lists, text
from natsort.compat.py23 import PY_VERSION, py23_str
from natsort.utils import natsort_key
if PY_V... | nilq/baby-python | python |
from ..abstract import ErdReadOnlyConverter
from ..primitives import *
from gehomesdk.erd.values.fridge import FridgeIceBucketStatus, ErdFullNotFull
class FridgeIceBucketStatusConverter(ErdReadOnlyConverter[FridgeIceBucketStatus]):
def erd_decode(self, value: str) -> FridgeIceBucketStatus:
"""Decode Ice bu... | nilq/baby-python | python |
import datetime
import unittest
import unittest.mock
from conflowgen.api.container_flow_generation_manager import ContainerFlowGenerationManager
from conflowgen.application.models.container_flow_generation_properties import ContainerFlowGenerationProperties
from conflowgen.domain_models.distribution_models.mode_of_tra... | nilq/baby-python | python |
from polecat.rest.schema_builder import RestSchemaBuilder
def test_schema_builder():
schema = RestSchemaBuilder().build()
assert len(schema.routes) > 0
| nilq/baby-python | python |
from PIL import Image
import matplotlib.pyplot as plt
# Log images
def log_input_image(x, opts):
return tensor2im(x)
def tensor2im(var):
# var shape: (3, H, W)
var = var.cpu().detach().transpose(0, 2).transpose(0, 1).numpy()
var = ((var + 1) / 2)
var[var < 0] = 0
var[var > 1] = 1
var = var * 255
return Imag... | nilq/baby-python | python |
import csv
from argparse import ArgumentParser
import re
parser = ArgumentParser()
parser.add_argument('--input_file', type=str)
parser.add_argument('--output_csv_file', type=str)
parser.add_argument('--option', default='eval', choices=['eval', 'debug'])
args = parser.parse_args()
lang_regex = re.compile('lang=(\w+... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(False)
... | nilq/baby-python | python |
import unittest
from unittest.mock import patch
import pytest
import Parser.languageInterface as languageInterface
# class Test_LanguageInterface(unittest.TestCase):
# @patch('Parser.languageInterface.LanguageInterface.getSymbols')
# @patch('Parser.languageInterface.LanguageInterface.printParsedData')
# ... | nilq/baby-python | python |
import os
import os.path as op
from sklearn.externals import joblib as jl
from glob import glob
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import f_classif, SelectPercentile
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import StratifiedKFold
from sklearn.svm im... | nilq/baby-python | python |
import os
import copy
from util.queryParser import SimpleQueryParser
def gene_imagenet_synset(output_file):
sid2synset = {}
for line in open('visualness_data/words.txt'):
sid, synset = line.strip().split('\t')
sid2synset[sid] = synset
fout = open(output_file, 'w')
for line in open('vi... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
Count the number of called variants per sample in a VCF file.
"""
import argparse
import collections
import vcf
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"vcf", help="the vcf file to analyze", type=lambda f: vcf.Reader(fil... | nilq/baby-python | python |
from django.contrib import admin
from django.db import models
from tinymce.widgets import TinyMCE
from .models import Aviso
from .models import AvisoViewer
from .forms import AvisoFormAdmin
@admin.register(Aviso)
class AvisoAdmin(admin.ModelAdmin):
fields = ['titulo', 'subtitulo', 'data', 'texto', 'autor', 'edit... | nilq/baby-python | python |
import json
USERS = "../static/user.json"
def read_JSON(filename):
try:
with open(filename, "r") as file_obj:
return json.load(file_obj)
except:
return dict()
def write_JSON(data, filename):
with open(filename, "w+") as file_obj:
json.dump(data, file_obj)
def append_J... | nilq/baby-python | python |
from utils.code_runner import execute_code
import math
def sum_divisors(n):
if n == 1:
return 1
sqrt_n = math.ceil(math.sqrt(n))
divisor = 2
total_sum = 1
while divisor < sqrt_n:
if n % divisor == 0:
total_sum += divisor
total_sum += n // divisor
... | nilq/baby-python | python |
from datadog import initialize, statsd
import random
import time
options = {
'statsd_host':'127.0.0.1',
'statsd_port':8125
}
initialize(**options)
namespace = "testing7"
# statsd.distribution('example_metric.distribution', random.randint(0, 20), tags=["environment:dev"])
statsd.timing("%s.timing"%namespace, ... | nilq/baby-python | python |
import numpy as np
import ad_path
import antenna_diversity as ad
import matplotlib.pyplot as plt
import h5py
import typing as t
import time
import os
ad_path.nop()
bits_per_slot = 440
slots_per_frame = 1
give_up_value = 1e-6
# How many bits to aim for at give_up_value
certainty = 20
# Stop early at x number of error... | nilq/baby-python | python |
import uuid
import factory.fuzzy
from dataworkspace.apps.request_access import models
from dataworkspace.tests.factories import UserFactory
class AccessRequestFactory(factory.django.DjangoModelFactory):
requester = factory.SubFactory(UserFactory)
contact_email = factory.LazyAttribute(lambda _: f"test.user+{... | nilq/baby-python | python |
# Joey Alexander
# Built by Gautam Mittal (2017)
# Real-time chord detection and improvisation software that uses Fast Fourier Transforms, DSP, and machine learning
import sys
sys.path.append('util')
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from m... | nilq/baby-python | python |
# coding=utf-8
#Author: Chion82<sdspeedonion@gmail.com>
import requests
import urllib
import re
import sys, os
import HTMLParser
import json
from urlparse import urlparse, parse_qs
reload(sys)
sys.setdefaultencoding('utf8')
class PixivHackLib(object):
def __init__(self):
self.__session_id = ''
self.__session... | nilq/baby-python | python |
# Generated by Django 3.0.2 on 2020-01-20 10:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20200117_1430'),
]
operations = [
migrations.AlterField(
model_name='imagefile... | nilq/baby-python | python |
#!/usr/bin/env python
# file_modified.py
# takes input file or string and returns file modified date
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import os.path, sys
parent_dir = os.path.abspath... | nilq/baby-python | python |
#!/usr/bin/env python
"""Normalizes ini files."""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R1702
# pylint: disable=R0912
import re
import sys
from collections import defaultdict
class Processor:
"""Process and normalizes an ini file."""
def __init__(self):
self.r: dict[str,... | nilq/baby-python | python |
import poplib
from email.parser import Parser
email = 'liang_renhong@163.com'
password = 'lrh0000'
pop3_server = 'pop.163.com'
server = poplib.POP3(pop3_server)
print(server.getwelcome().decode('utf8'))
server.user(email)
server.pass_(password)
print('Message: %s. Size: %s' % (server.stat()))
resp, mails, octe... | nilq/baby-python | python |
def test_dictionary():
"""Dictionary"""
fruits_dictionary = {
'cherry': 'red',
'apple': 'green',
'banana': 'yellow',
}
assert isinstance(fruits_dictionary, dict)
assert fruits_dictionary['apple'] == 'green'
assert fruits_dictionary['banana'] == 'yellow'
assert frui... | nilq/baby-python | python |
import os, time, logging, configparser, psutil
# Setting
logging.basicConfig(filename='log/app.log', filemode='w',format='[%(levelname)s][%(name)s][%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
logger.info('Module Loaded')
config = configparser.ConfigParser()
config.read("... | nilq/baby-python | python |
# Copyright 2016 AC Technologies 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 required by applicable... | nilq/baby-python | python |
import os
from shutil import copy
def prepare_iso_linux(iso_base_dir, rootfs_dir):
# copy isolinux files to the corresponding folder
isolinux_files = ['isolinux.bin', 'isolinux.cfg', 'ldlinux.c32']
for file in isolinux_files:
full_file = '/etc/omni-imager/isolinux/' + file
copy(full_file, ... | nilq/baby-python | python |
# Generated by Django 3.1 on 2021-03-02 21:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('waterspout_api', '0007_auto_20201215_1526'),
]
operations = [
migrations.AddField(
model_name='ca... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') # print out 'Greeting!'
colors = ['red','orange',... | nilq/baby-python | python |
import sys
PY3 = (sys.version_info[0] >= 3)
if PY3:
basestring = unicode = str
else:
unicode = unicode
basestring = basestring
if PY3:
from ._py3compat import execfile
else:
execfile = execfile
| nilq/baby-python | python |
#!/usr/bin/env python
import sys
import subprocess
#----------------------------------------------------------------------
## generic pipe-like cleaning functions
def rpl(x, y=''):
def _func(s):
return s.replace(x, y)
return _func
def pipe(*args):
def _func(txt):
return subprocess.run(li... | nilq/baby-python | python |
import flask
from flask import request, jsonify
from secrets import secrets
from babel_categories import BabelCategories
from babel_hypernyms import BabelHypernyms
from babel_lemmas_of_senses import BabelLemmasOfSenses
from babel_parser import BabelParser
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.r... | nilq/baby-python | python |
__author__ = 'Spasley'
| nilq/baby-python | python |
from rest_framework import exceptions, status
from api.services import translation
class PreconditionFailedException(exceptions.APIException):
status_code = status.HTTP_412_PRECONDITION_FAILED
default_detail = translation.Messages.MSG_PRECONDITION_FAILED
default_code = 'precondition_failed'
| nilq/baby-python | python |
import warnings
import pulumi
class Provider(pulumi.ProviderResource):
"""
The provider type for the kubernetes package.
"""
def __init__(self,
resource_name,
opts=None,
cluster=None,
context=None,
enable_dry_run=No... | nilq/baby-python | python |
import json
import pulumi
import pulumi_aws as aws
# CONFIG
DB_NAME='dbdemo'
DB_USER='user1'
DB_PASSWORD='p2mk5JK!'
DB_PORT=6610
IAM_ROLE_NAME = 'redshiftrole'
redshift_role = aws.iam.Role(IAM_ROLE_NAME,
assume_role_policy=json.dumps({
"Version": "2012-10-17",
"Statement": [{
"Action"... | nilq/baby-python | python |
import win32api, mmapfile
import winerror
import tempfile, os
from pywin32_testutil import str2bytes
system_info=win32api.GetSystemInfo()
page_size=system_info[1]
alloc_size=system_info[7]
fname=tempfile.mktemp()
mapping_name=os.path.split(fname)[1]
fsize=8*page_size
print fname, fsize, mapping_name
m1... | nilq/baby-python | python |
# Copyright (c) Microsoft Corporation.
# Copyright (c) 2018 Jensen Group
# Licensed under the MIT License.
"""
Module for generating rdkit molobj/smiles/molecular graph from free atoms
Implementation by Jan H. Jensen, based on the paper
Yeonjoon Kim and Woo Youn Kim
"Universal Structure Conversion Method for O... | nilq/baby-python | python |
import logging
import os
import socket
from logging import Logger
from typing import Any, Dict, List, Optional, Union
from pathlib import Path
import docker
import dockerpty
from docker import DockerClient
from docker.models.images import Image
from docker.errors import APIError, DockerException
from requests import R... | nilq/baby-python | python |
#!/usr/bin/python
# coding=utf-8
import json
import sys
from PIL import Image
from pprint import pprint
import mutual_infor as mi
'''
note: Imager
'''
default_img_path = "img.jpg"
data_dir = "data/map_img/"
class Imager:
def __init__(self, path):
self.path = path
self.entropy = ... | nilq/baby-python | python |
from z3 import Int
class Storage(object):
def __init__(self):
self._storage = {}
def __getitem__(self, item):
if item not in self._storage.keys():
# self._storage[item] = Int("s_" + str(item))
self._storage[item] = 0
return self._storage[item]
def __setite... | nilq/baby-python | python |
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import unittest
import kenlm
from predictor import WordPredictor
from vocabtrie import VocabTrie
import numbers
class TestWordPredictor(unittest.TestCase):
def setUp(self):
self.wordPredictor = WordPredictor('../... | nilq/baby-python | python |
import logging
from pdb import Pdb
import sys
import time
from pathlib import Path
from typing import List
from pprint import pformat
import docker
import yaml
logger = logging.getLogger(__name__)
current_dir = Path(sys.argv[0] if __name__ == "__main__" else __file__).resolve().parent
WAIT_TIME_SECS = 20
RETRY_COUN... | nilq/baby-python | python |
"""Settings for admin panel related to the authors app."""
| nilq/baby-python | python |
import unittest
from yauber_algo.errors import *
class PercentRankTestCase(unittest.TestCase):
def test_category(self):
import yauber_algo.sanitychecks as sc
from numpy import array, nan, inf
import os
import sys
import pandas as pd
import numpy as np
from ... | nilq/baby-python | python |
import sys
import pandas as pd
from sqlalchemy import create_engine
import pickle
import nltk
nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger'])
import re
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.metrics import confusion_matrix, clas... | nilq/baby-python | python |
_base_ = '../pointpillars/hv_pointpillars_secfpn_6x8_160e_kitti-3d-car.py'
voxel_size = [0.16, 0.16, 4]
point_cloud_range = [0, -39.68, -3, 69.12, 39.68, 1]
model = dict(
type='DynamicVoxelNet',
voxel_layer=dict(
max_num_points=-1,
point_cloud_range=point_cloud_range,
voxel_size=voxel_... | nilq/baby-python | python |
import collections
import sys
def main(letters, words):
d = collections.defaultdict(list)
print(d)
print(letters)
print(words)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2:])
| nilq/baby-python | python |
# ### Problem 1
# Ask the user to enter a number.
# Using the provided list of numbers, use a for loop to iterate the array and print out all the values that are smaller than the user input and print out all the values that are larger than the number entered by the user.
# ```
# # Start with this List
# list_of_many_... | nilq/baby-python | python |
import tensorflow as tf
import numpy as np
import json
import argparse
import cv2
import os
import glob
import math
import time
import glob
def infer(frozen_pb_path, output_node_name, img_path, output_path=None):
with tf.gfile.GFile(frozen_pb_path, "rb") as f:
restored_graph_def = tf.GraphDef()
res... | nilq/baby-python | python |
#!flask/bin/python
# -*- coding: utf-8 -*-
from api import app
from flask import jsonify, make_response
@app.errorhandler(401)
def unauthorized(error=None):
mensagem = {'status': 401, 'mensagem': 'Voce nao tem permissao para acessar essa pagina!'}
resp = jsonify(mensagem)
resp.status_code = 401
# RED... | nilq/baby-python | python |
from hwt.hdl.types.bits import Bits
from hwt.hdl.types.stream import HStream
from hwt.hdl.types.struct import HStruct
class USB_VER:
USB1_0 = "1.0"
USB1_1 = "1.1"
USB2_0 = "2.0"
class PID:
"""
USB Protocol layer packet identifier values
:attention: visualy writen in msb-first, transmited in... | nilq/baby-python | python |
###############################################################################
# Author: Wasi Ahmad
# Project: Match Tensor: a Deep Relevance Model for Search
# Date Created: 7/28/2017
#
# File Description: This script contains code related to the sequence-to-sequence
# network.
################################... | nilq/baby-python | python |
"""
Aravind Veerappan
BNFO 601 - Exam 2
Question 2. Protein BLAST
"""
import math
from PAM import PAM
class BLAST(object):
FORWARD = 1 # These are class variables shared by all instances of the BLAST class
BACKWARD = -1
ROW = (0, 1)
COLUMN = (1, 0)
def __init__(self, query=None,... | nilq/baby-python | python |
import sublime, sublimeplugin
import os
class NewPluginCommand(sublimeplugin.WindowCommand):
def run(self, window, args):
view = window.newFile()
path = sublime.packagesPath() + u"/user"
try:
os.chdir(path)
except Exception:
pass
view.options().set("syntax", "Packages/Python/Python.tmLanguag... | nilq/baby-python | python |
#!/usr/bin/env python3
import math
def main():
limit = 999
print(sumOfMultiples(3, limit) + sumOfMultiples(5, limit) - sumOfMultiples(15, limit))
def sumOfMultiples(n, max):
return n * (math.floor(max / n) * (math.floor(max / n) + 1)) / 2
if __name__ == "__main__": main() | nilq/baby-python | python |
from .orders import Order
from .customers import Customer
from .products import Product
from .line_items import LineItem
from .lot_code import LotCode
from .warehouse import Warehouse
from .location import Location
from .inventories import Inventory
from .inventory_adjustments import InventoryAdjustment
from .inventory... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from flask import Flask
from flask import abort
from flask import make_response
from flask import render_template
from flask import request
import sleekxmpp
app = Flask(__name__)
app.config.from_envvar("XMPP_CHAT_BADGE_CONFIG")
# Python versions before 3.0 do... | nilq/baby-python | python |
import chess
from datetime import datetime
from tqdm import tqdm
from os import getcwd
from utils.trans_table_utils import *
from utils.history_utils import *
from utils.heuristics import combined
from agents.alpha_beta_agent import AlphaBetaAgent
from agents.alpha_beta_agent_trans import AlphaBetaAgentTrans
from age... | nilq/baby-python | python |
#!/usr/bin/env python
"""
The galvo voltage control UI
Aditya Venkatramani 04/21 --> Adapted from zStage.py
"""
import os
from PyQt5 import QtCore, QtGui, QtWidgets
import storm_control.sc_library.parameters as params
import storm_control.hal4000.halLib.halDialog as halDialog
import storm_control.hal4000.halLib.hal... | nilq/baby-python | python |
from os import system, name
system('cls' if name == 'nt' else 'clear')
dsc = ('''DESAFIO 019:
Um professor quer sortear um dos seus quatro alunos para apagar
o quadro. Faça um um programa que ajude ele, lendo o nome deles e
escrevendo o nome escolhido.
''')
from random import choice
alunos = []
alunos.append(input('... | nilq/baby-python | python |
#!/usr/bin/env python
import pytest
import sklearn.datasets as datasets
import sklearn.neural_network as nn
import pandas_ml as pdml
import pandas_ml.util.testing as tm
class TestNeuralNtwork(tm.TestCase):
def test_objectmapper(self):
df = pdml.ModelFrame([])
self.assertIs(df.neur... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __BEGIN_LICENSE__
# Copyright (c) 2009-2013, United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The NGT platform is licensed under the Apache License, Version 2.0 (the
# "Lic... | nilq/baby-python | python |
""" Tests for the main server file. """
from unittest import TestCase
from unittest.mock import patch
from app import views
class ViewsTestCase(TestCase):
""" Our main server testcase. """
def test_ping(self):
self.assertEqual(views.ping(None, None), 'pong')
@patch('app.views.notify_recipient')... | nilq/baby-python | python |
#
__doc__ = """
Schema for test/simulator configuration file.
TODO:
- Somehow, validation of test config doesn't work correctly. Only type conversion works.
"""
from configobj import ConfigObj, flatten_errors
from validate import Validator, ValidateError, VdtTypeError
import os
from StringIO import StringIO
impor... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Progress component
"""
from bowtie._component import Component
class Progress(Component):
"""This component is used by all visual components and
is not meant to be used alone.
By default, it is not visible.
It is an opt-in feature and you can happily use Bowtie
withou... | nilq/baby-python | python |
from rest_framework.test import APITestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from requests.auth import HTTPBasicAuth
from django.conf import settings
class JWTViewsTestCase(APITestCase):
def test_fails_when_logged_out(self):
self.client.logout()
respo... | nilq/baby-python | python |
from guhs.guhs_configuration import GuhsConfiguration
def from_guhs_configuration(configuration: GuhsConfiguration):
return {
'targets': [
{'order_id': t.order_id, 'name': t.name}
for t in configuration.targets
],
'boot_selection_timeout': configuration.boot_selecti... | nilq/baby-python | python |
from email.policy import default
from .base import print_done, finalize, SRC_PATH, CONFIG_PATH
import invoke
@invoke.task
def isort(context, src_path=SRC_PATH):
print('Running isort...')
context.run('isort {src_path} -m VERTICAL_HANGING_INDENT --tc'.format(src_path=src_path))
print_done(indent=4)
@invo... | nilq/baby-python | python |
# Escreva um programa que pergunte a quantidade de Km
# percorridos por um carro alugado e a quantidade de dias pelos
# quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro
# custa R$60 por dia e R$0.15 por Km rodado.
km = float(input("Quantos km percorreu?: "))
dia = int(input("Quantos dias ele foi alu... | nilq/baby-python | python |
import os
# import pprint
import re
from datetime import datetime
from pathlib import Path
from nornir_napalm.plugins.tasks import napalm_get
from nornir_utils.plugins.functions import print_result
from nornir_utils.plugins.tasks.files import write_file
# from nornir_netmiko.tasks import netmiko_send_command, netmiko... | nilq/baby-python | python |
from sqlalchemy import exc as sa_exc
from sqlalchemy.orm import state_changes
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_raises_message
from sqlalchemy.testing import fixtures
class StateTestChange(state_changes._StateChangeState):
a = 1
b = 2
c = 3
class StateMachineTest(f... | nilq/baby-python | python |
import operator
import rules
from rules.predicates import is_authenticated
from marketplace.domain import marketplace
rules.add_perm('user.is_same_user', operator.eq)
rules.add_perm('user.is_authenticated', is_authenticated)
rules.add_rule('user.is_site_staff', marketplace.user.is_site_staff)
rules.add_rule('vol... | nilq/baby-python | python |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
This module contains the Parameters class that is used to specify the input parameters of the tree.
"""
import numpy as np
class Parameters():
"""Class to specify the parameters of the fractal tree.
Attributes:
meshfile (str): path and filename to obj file name... | nilq/baby-python | python |
from .fixup_resnet_cifar import *
from .resnet_cifar import *
from .rezero_resnet_cifar import *
from .rezero_dpn import *
from .dpn import *
from .rezero_preact_resnet import *
from .preact_resnet import *
| nilq/baby-python | python |
import os.path
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from ui.mainwindow import Ui_MainWindow
from ui.worldview import WorldView
from world import World
class PsychSimUI(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
self.world = None
super(PsychSimUI, self).__init__(pa... | nilq/baby-python | python |
from torch.optim import Optimizer
class ReduceLROnLambda():
def __init__(self, optimizer, func, factor=0.1,\
verbose=False, min_lr=0, eps=1e-8):
if factor >= 1.0:
raise ValueError('Factor should be < 1.0.')
self.factor = factor
if not isinstance(optimizer, Optimizer):
raise TypeError('{} is not an O... | nilq/baby-python | python |
# --------------
import pandas as pd
from sklearn import preprocessing
#path : File path
# Code starts here
# read the dataset
dataset = pd.read_csv(path)
# look at the first five columns
print(dataset.head())
# Check if there's any column which is not useful and remove it like the column id
dataset = dataset.drop... | nilq/baby-python | python |
import errno
import os
from tqdm import tqdm
from urllib.request import urlretrieve
def maybe_makedir(path: str) -> None:
try:
# Create output directory if it does not exist
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def download_file(url: st... | nilq/baby-python | python |
from typing import Union
import numpy as np
import pandas as pd
from fedot.api.api_utils.data_definition import data_strategy_selector
from fedot.core.data.data import InputData
from fedot.core.repository.tasks import Task, TaskTypesEnum
from fedot.core.pipelines.pipeline import Pipeline
class ApiDataHelper:
def ... | nilq/baby-python | python |
#!/usr/bin/env python
import pandas as pd
import os
import numpy as np
import SNPknock.fastphase as fp
from SNPknock import knockoffHMM
from joblib import Parallel, delayed
import utils_snpko as utils
logger = utils.logger
def make_knockoff(chromosome=None, grouped_by_chromosome=None, df_SNP=None,
... | nilq/baby-python | python |
import datetime
import json
import time
from fate_manager.db.db_models import DeployComponent, FateSiteInfo, FateSiteCount, FateSiteJobInfo, ApplySiteInfo
from fate_manager.entity import item
from fate_manager.entity.types import SiteStatusType, FateJobEndStatus
from fate_manager.operation.db_operator import DBOperato... | nilq/baby-python | python |
from . import ShapeNet, SetMNIST, SetMultiMNIST, ArCH
def get_datasets(args):
if args.dataset_type == 'shapenet15k':
return ShapeNet.build(args)
if args.dataset_type == 'mnist':
return SetMNIST.build(args)
if args.dataset_type == 'multimnist':
return SetMultiMNIST.build(args)
... | nilq/baby-python | python |
# flake8: noqa: W291
# pylint: disable=too-many-lines,trailing-whitespace
"""
AbstractAnnoworkApiのヘッダ部分
Note:
このファイルはopenapi-generatorで自動生成される。詳細は generate/README.mdを参照
"""
from __future__ import annotations
import abc
import warnings # pylint: disable=unused-import
from typing import Any, Optional, Union # py... | nilq/baby-python | python |
#!/usr/bin/env python
from setuptools import setup, os
setup(
name='PyBabel-json-md',
version='0.1.0',
description='PyBabel json metadef (md) gettext strings extractor',
author='Wayne Okuma',
author_email='wayne.okuma@hpe.com',
packages=['pybabel_json_md'],
url="https://github.com/wkoathp... | nilq/baby-python | python |
# Tai Sakuma <tai.sakuma@gmail.com>
import pytest
has_no_ROOT = False
try:
import ROOT
except ImportError:
has_no_ROOT = True
from alphatwirl.roottree import Events
if not has_no_ROOT:
from alphatwirl.roottree import BEvents as BEvents
##_________________________________________________________________... | nilq/baby-python | python |
import qimpy as qp
import numpy as np
from scipy.special import sph_harm
from typing import Sequence, Any, List, Tuple
def get_harmonics_ref(l_max: int, r: np.ndarray) -> np.ndarray:
"""Reference real solid harmonics based on SciPy spherical harmonics."""
rMag = np.linalg.norm(r, axis=-1)
theta = np.arcco... | nilq/baby-python | python |
# Copyright (c) nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compliance ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/app_ui.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, Qt... | nilq/baby-python | python |
from cloudshell.shell.core.resource_driver_interface import ResourceDriverInterface
from cloudshell.shell.core.context import InitCommandContext, ResourceCommandContext
import cloudshell.api.cloudshell_api as api
from natsort import natsorted, ns
import ipcalc
import json
class IpcalcDriver (ResourceDriverInterface):
... | nilq/baby-python | python |
"""
Routine to create the light cones shells
L1 L2 L3 u11 u12 u13 u21 u22 u23 u31 u32 u33 (periodicity)
C2 '2.2361', '1.0954', '0.4082', '2', '1', '0', '1', '0', '1', '1', '0', '0', '(1)'
C15 '1.4142', '1.0000', '0.7071', '1', '1', '0', '0', '0', '1', '1', '0', '0', '(12)'
C6 '5.9161', '0.4140', '0.4082', '5... | nilq/baby-python | python |
# This module is avaible both in the Python and Transcrypt environments
# It is included in-between the __core__ and the __builtin__ module, so the latter can adapt __envir__
# In Transcrypt, __base__ is available inline, it isn't nested and cannot be imported in the normal way
class __Envir__:
def __init__ (... | nilq/baby-python | python |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_im... | nilq/baby-python | python |
import hashlib
class HashUtils(object):
@staticmethod
def md5(string: str):
md5 = hashlib.md5(string.encode("utf-8"))
return md5.hexdigest()
@staticmethod
def sha1(string: str):
sha1 = hashlib.sha1(string.encode("utf-8"))
return sha1.hexdigest()
... | nilq/baby-python | python |
#!/bin/python
# Solution for https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited
import sys
n,k = raw_input().strip().split(' ')
n,k = [int(n),int(k)]
c = map(int,raw_input().strip().split(' '))
E = 100
current = 0
time = 0
while not (time > 0 and current == 0):
current += k
... | nilq/baby-python | python |
import pickle
import pandas as pd
import numpy as np
import time
from sklearn.model_selection import TimeSeriesSplit, GridSearchCV
from sklearn.ensemble import RandomForestClassifier
import os
def feat_eng(df_fe):
'''
Función que realiza la selección de los features que serán utilizdos para la clasificación
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: transaction/v4/transaction_service.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import s... | nilq/baby-python | python |
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# 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, publ... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.