content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/python import unittest import sys import autocertkit.utils class DevTestCase(unittest.TestCase): """Subclass unittest for extended setup/tear down functionality""" session = "nonexistent" config = {} @classmethod def setUpClass(cls): # Read user config from file ...
nilq/baby-python
python
import logging import numpy as np from scipy.special import jv from aspire.basis import FBBasisMixin, SteerableBasis2D from aspire.basis.basis_utils import unique_coords_nd from aspire.image import Image from aspire.utils import complex_type, real_type, roll_dim, unroll_dim from aspire.utils.matlab_compat import m_fl...
nilq/baby-python
python
#! /usr/bin/python3 import os import sys import argparse import time import signal from ivy.std_api import * import logging PPRZ_HOME = os.getenv("PAPARAZZI_HOME", os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../../'))) sys.path.append(PPRZ_HOME + "/var/lib/python") from pprzlink.iv...
nilq/baby-python
python
# Program to generate random account names # Start simple. Just considering distribution of consonants and # vowels first. And then look into including the other arrays. # Compare which will give better results. Just distribution of letters? # Or taking into account other rules and distribution of other morphemes :) ...
nilq/baby-python
python
from __future__ import unicode_literals from cradmin_legacy.crispylayouts import CradminSubmitButton class BulkFileUploadSubmit(CradminSubmitButton): template = 'cradmin_legacy/apps/cradmin_temporaryfileuploadstore/bulkfileupload-submit.django.html' extra_button_attributes = { 'cradmin-legacy-bulkfile...
nilq/baby-python
python
# coding:utf-8 import os import timeit import tensorflow as tf from tensorflow.python.keras.api._v2.keras import backend as K from core.get_model import create_EEGNet, create_TSGLEEGNet from core.training import crossValidate, gridSearch from core.dataloaders import RawDataloader from core.generators import RawGenerat...
nilq/baby-python
python
"""Manipulate tem variants.""" import os import sys from tem import util, var from tem.cli import common as cli from .common import print_cli_err def setup_parser(p): cli.add_general_options(p) p.add_argument("variants", nargs="*", help="set the active variant") mutex = p.add_mutually_exclusive_group()...
nilq/baby-python
python
import os import pathlib import random import json import kinpy as kp import numpy as np from tests.test_urdf_parser import ( urdf_path_to_json_path, PRECOMPUTED_KINEMATICS_DIR_NAME, URDF_EXAMPLES_DIR ) def initialize_state(robot): """Creates a dictionary whose entries each correspond ...
nilq/baby-python
python
""" Object representation of features. Includes an abstract feature class that is also used by transcripts. Each object is capable of exporting itself to BED and GFF3. """ from typing import Optional, Any, Dict, List, Set, Iterable, Hashable from uuid import UUID from inscripta.biocantor.exc import ( EmptyLocatio...
nilq/baby-python
python
from django.urls import url from .views import SignUpView,ProfilePageView, ProfileEditPageView urlpatterns = [ url(r'', SignUpView.as_view(), name='signup'), url(r'profile/$', ProfilePageView.as_view(), name='profile'), url(r'profile_edit/$', ProfileEditPageView, name='profile_edit') ]
nilq/baby-python
python
#!/usr/bin/python import numpy as np import theano import theano.tensor as T import reberGrammar dtype = theano.config.floatX # SET the random number generator's seeds for consistency SEED = 123 np.random.seed(SEED) # refer to the tutorial # http://christianherta.de/lehre/dataScience/machineLearning/neuralNetworks/...
nilq/baby-python
python
import os import sys import time import json import h5py import argparse import librosa import numpy as np from tqdm import tqdm from glob import glob from typing import Any from tf_lite.filter import Filter from tf_lite.tf_lite import TFLiteModel import webrtcvad class Dataset_Filter: def __init__(self, ...
nilq/baby-python
python
import sys import hmac import time import crypt import hashlib import sqlite3 import ConfigParser from flask import session, render_template, g, flash, redirect, url_for, request, jsonify """ cgroup_ext is a data structure where for each input of edit.html we have an array with: position 0: the lxc container opt...
nilq/baby-python
python
import numpy as np import pandas as pd # generate a daily signal covering one year 2016 in a pandas dataframe N = 365 np.random.seed(seed=1960) df_train = pd.DataFrame({"Date" : pd.date_range(start="2016-01-25", periods=N, freq='D'), "Signal" : (np.arange(N)//40 + np.arange(N) % 21 + np.random...
nilq/baby-python
python
import warnings from asl_data import SinglesData def recognize(models: dict, test_set: SinglesData): """ Recognize test word sequences from word models set :param models: dict of trained models {'SOMEWORD': GaussianHMM model object, 'SOMEOTHERWORD': GaussianHMM model object, ...} :param test_set: SinglesData obj...
nilq/baby-python
python
from django.template.loaders.app_directories import Loader as AppDirectoriesLoader from .mixins import TemplateMinifierMixin class Loader(TemplateMinifierMixin, AppDirectoriesLoader): pass
nilq/baby-python
python
import pygame from pygame import mixer from pygame import time from pygame.locals import * import random pygame.mixer.pre_init(44100, -16, 2, 512) mixer.init() pygame.font.init() # define fps clock = pygame.time.Clock() fps = 60 screen_width = 600 screen_height = 800 screen = pygame.display.set_mode((screen_width,...
nilq/baby-python
python
if __name__ == '__main__': n = int(input()) numbers = [None]*(n+1) a = list(map(int,input().split())) for i in a: numbers[i] = True for i in range(1,n+1): if numbers[i] is None: print(i)
nilq/baby-python
python
import zmq import uuid from random import randint from common.settings import * context = zmq.Context() servers = SERVERS_LOCAL connections = [] for i in xrange(N_SERVERS): socket = context.socket(zmq.REQ) socket.connect("tcp://" + servers[i]["client2server"]) connections.append(socket) for i in range(6...
nilq/baby-python
python
#!/usr/bin/env python import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np plt.rcParams.update({'font.size': 16}) dt = 0.02 dims = 201, 201 x = range(-100, 101) for i in range(0,1100, 100): input_file = 'tsunami_h_' + '%4.4i' % i + '.dat' print('Plotting ' + input_file) field ...
nilq/baby-python
python
import filecmp import os.path class dircmp(filecmp.dircmp): """ Compare the content of dir1 and dir2. In contrast with filecmp.dircmp, this subclass compares the content of files with the same path. """ def phase3(self): """ Find out differences between common files. Ensure ...
nilq/baby-python
python
wrf_dir="/home/WRFV4.1.3/run_tutorial/" wrf_input_file="wrfinput_d01" wrf_bdy_file="wrfbdy_d01" wrf_met_dir="/home/WPSV4.1.3/run_tutorial/" wrf_met_files="met_em.d01.2010*" mera_dir="/home/Merra2_data/" mera_files="svc_MERRA2_300.inst3_3d_aer_Nv.2010*" do_IC=True do_BC=True #########################################...
nilq/baby-python
python
import pathlib import numpy as np from scipy import sparse import pandas as pd from sklearn.preprocessing import normalize from sklearn.utils.extmath import safe_sparse_dot from nilearn import image from neuroquery.img_utils import get_masker from neuroquery import tokenization, smoothed_regression, ridge _MAX_SIMIL...
nilq/baby-python
python
def dutch(arr): low = 0 mid = 0 high = len(arr) - 1 while mid <= high: if arr[mid] == 0: arr[low], arr[mid] = arr[mid], arr[low] low += 1 mid += 1 elif arr[mid] == 1: mid += 1 else: arr[mid], arr[high] = arr[high], arr[m...
nilq/baby-python
python
# find an specific element of a list import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.aer import QasmSimulator from qiskit.visualization import plot_histogram # Use Aer's qasm_simulator simulator = QasmSimulator() # Create a oracle operator oracle ...
nilq/baby-python
python
import re regex = r"\*\*(?P<bold>\S+)\*\*|\*(?P<italic>\S+)\*|==(?P<wrap>\S+)==|\[(?P<url>\S+\]\(\S+)\)" p = re.compile(regex, re.MULTILINE) func_dict = { 'wrap': lambda x: (f"<mark>{x}</mark>", f"=={x}=="), 'bold': lambda x: (f"<b>{x}</b>", f"**{x}**"), 'italic': lambda x: (f"<i>{x}</i>", f"*{x}*"), ...
nilq/baby-python
python
import numpy as np import math import rospy from tf.transformations import quaternion_from_euler, euler_from_quaternion from geometry_msgs.msg import Quaternion from geometry_msgs.msg import Point, PoseArray from visualization_msgs.msg import Marker from visualization_msgs.msg import MarkerArray from ackermann_msgs.m...
nilq/baby-python
python
from sqlalchemy.orm.collections import attribute_mapped_collection from emonitor.extensions import db from emonitor.modules.alarmkeys.alarmkeycar import AlarmkeyCars from emonitor.modules.alarmkeys.alarmkeyset import AlarmkeySet class Alarmkey(db.Model): """Alarmkey class""" __tablename__ = 'alarmkeys' __...
nilq/baby-python
python
n1 = float(input('Nota 1: ')) n2 = float(input('Nota 2: ')) m = (n1 + n2) / 2 if m < 5: print('REPROVADO :(') elif m < 7: print('RECUPERAÇÃO...') else: print('APROVADO!! :D')
nilq/baby-python
python
''' prompt = "If you tell us who you are, we can personalize the messages you see" prompt += "\nWhat is your first name: " name = input(prompt) print("\nHello, " + name + "!\n") age = int(input("how old are you? ")) print(age, end="\n\n") height = float(input("How tall are you, in meters? ")) if height >= 1.50: ...
nilq/baby-python
python
''' Get the residue depth for each residue in BioLiP run as: python -m ResidueDepth.Controller ''' from Bio.PDB import PDBParser from Bio.PDB import Selection from Bio.PDB.ResidueDepth import get_surface, residue_depth, ca_depth from Bio.PDB.Polypeptide import is_aa import os from AABindingSiteDist.Controll...
nilq/baby-python
python
# Copyright (c) 2012 NetApp, Inc. All rights reserved. # Copyright (c) 2014 Ben Swartzlander. All rights reserved. # Copyright (c) 2014 Navneet Singh. All rights reserved. # Copyright (c) 2014 Clinton Knight. All rights reserved. # Copyright (c) 2015 Tom Barron. All rights reserved. # Copyright (c) 2015 Alex Meade...
nilq/baby-python
python
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('transmittals', '0047_auto_20160224_1220'), ] operations = [ migrations.AlterField( model_name='outgoingtransmittal', name='latest_revision'...
nilq/baby-python
python
""" 一键编译测试版本的app给qa: 1、改库版本号为测试版本号 2、改app的库依赖为测试版本号依赖 3、编库 4、编app """ import json import sys from base import sb_nexus, sb_jenkins, sb_config, sb_gitlab def _print_task(task): print(f'apps: {str(task["apps"])}') print(f'libs: {str(task["libs"])}') print(f'branch: {task["branch"]}') print(f'release_n...
nilq/baby-python
python
from typing import Any from unittest.mock import MagicMock, patch import pytest from operatorcert import pyxis from requests import HTTPError, Response def test_is_internal(monkeypatch: Any) -> None: assert not pyxis.is_internal() monkeypatch.setenv("PYXIS_CERT_PATH", "/path/to/cert.pem") monkeypatch.se...
nilq/baby-python
python
from pybuilder.core import use_plugin, init use_plugin("python.core") use_plugin("python.unittest") default_task = "publish" @init def initialize(project): project.version = "0.1.0.SNAPSHOT"
nilq/baby-python
python
from drpg.sync import DrpgSync __all__ = ["DrpgSync"] __version__ = "2021.11.0"
nilq/baby-python
python
import logging from django.contrib.auth.decorators import login_required from django.contrib.auth.signals import user_logged_in from django.core.urlresolvers import reverse from django.dispatch import receiver from django.http import HttpResponse, Http404 from django.shortcuts import redirect, render from django.utils...
nilq/baby-python
python
import unittest from skills import ( Match, Matches, Team, ) from skills.glicko import ( GlickoCalculator, GlickoGameInfo ) class CalculatorTests(object): ERROR_TOLERANCE_RATING = 0.085 ERROR_TOLERANCE_MATCH_QUALITY = 0.0005 def assertAlmostEqual(self, first, second, places, msg, delta): ...
nilq/baby-python
python
#! /bin/python __author__ = "glender" __copyright__ = "Copyright (c) 2018 glender" __credits__ = [ "glender" ] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "glender" __email__ = "None" __status__ = "Production" DEBUG = False alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ" message = ("6340 8309 14010") for i in me...
nilq/baby-python
python
from __future__ import print_function import sys import os import sysconfig import filecmp def diff_q(first_file, second_file): """Simulate call to POSIX diff with -q argument""" if not filecmp.cmp(first_file, second_file, shallow=False): print("Files %s and %s differ" % (first_file, second_file), ...
nilq/baby-python
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import random from collections import namedtuple import re import numpy as np import tensorflow as tf import csv import tokenization from mask import Mask, PinyinConfusionSet, Strok...
nilq/baby-python
python
"""Calculate autosome ratios for each cell. This script calculates the {X, 4, and Y} to autosome ratios for each individual cell. I consider chromosomes 2L, 2R, 3L, and 3R as autosomes. 1. Pull out target FBgns. 2. Sum the number of raw reads for each chromosome. 3. Normalize totals by the number of genes on each chr...
nilq/baby-python
python
from django.conf.urls import url from . import views urlpatterns = [ url('api/product/search', views.GoodsSearch), url('api/product/history', views.GetHistory) ]
nilq/baby-python
python
import logging import importlib from volttron.platform.agent import utils import volttron.pnnl.models.input_names as data_names _log = logging.getLogger(__name__) utils.setup_logging() class ahuchiller(object): def __init__(self, config, parent, **kwargs): self.parent = parent equipment_conf = c...
nilq/baby-python
python
import sys sys.path.append('../') import lcm import time from exlcm import ax_control_t from exlcm import veh_status_t from exlcm import net_status_t from exlcm import mode_control_t from exlcm import eng_toggle_t lc = lcm.LCM() test_message = veh_status_t() test_message.running = True test_message.rpm = 3110 test_m...
nilq/baby-python
python
import datetime import json import pathlib import time import httpx import xmltodict import yaml nyaa_url = 'https://nyaa.si' transmission_rpc_url = "http://localhost:9091/transmission/rpc" session_field = 'X-Transmission-Session-Id' class TransmissionApi(): def __init__(self): self.restar...
nilq/baby-python
python
from cedar_settings.default_settings import default_settings default_settings['assets__default_search_results_per_page'] = ('int', 20) # integer hours. default_settings['assets__default_asset_source_string'] = ('text', "Miscellaneous") default_settings['assets__default_files_div_id'] = ('text', "#tab-files")
nilq/baby-python
python
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See LICENSE import click import frappe @frappe.whitelist() def download_pdf(doctype, name, print_format, letterhead=None): doc = frappe.get_doc(doctype, name) generator = PrintFormatGenerator(print_format, doc, letterhead) pdf = g...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys import argparse import abc from six import add_metaclass, text_type import argparse import re from mCli.utils import get_resource_classes, Singleton from mCli.commands.base import Command @add_metaclass(abc.ABCMeta) class CommandManager(Singl...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ This package defines the astrophysics-specific units. They are also available in the `astropy.units` namespace. """ from . import si from astropy.constants import si as _si from .core import (UnitBase, def_unit, si_prefixes,...
nilq/baby-python
python
""" ######################### Linalg (``utils.linalg``) ######################### Linear algebra helper routines and wrapper functions for handling sparse matrices and dense matrices representation. """ import sys import copy import numpy as np import scipy import scipy.sparse as sp import sci...
nilq/baby-python
python
import wx class SimpleSizer(wx.BoxSizer): def __init__(self, first, second, gap=0, leftHeavy=False, rightHeavy=False, topHeavy=False, bottomHeavy=False): self.first = first self.second = second horizontal = leftHeavy or rightHeavy vertical = topHeavy or bottomHeavy assert horizontal or verti...
nilq/baby-python
python
from bank_account import BankAccount class User(object): def __init__(self, username, email_address): self.name = username # and we use the values passed in to set the name attribute self.email = email_address # and the email attribute self.accounts = { 'default': BankAccount(int_rate=0.02, bala...
nilq/baby-python
python
from boids.code.boids import Boids import pytest from os.path import dirname, split, join import yaml import numpy as np config = yaml.load(open(split(dirname(__file__))[0] + '/code/config.yaml')) def test_bad_boids_regression(): ''' test compares a single position update of the refactored code to the...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Top-level package for appliapps.""" __author__ = """Lars Malmstroem""" __email__ = 'lars@malmstroem.net' __version__ = '0.1.0'
nilq/baby-python
python
import socket from datetime import datetime import os.path as osp import huepy as hue import numpy as np import torch from torch.backends import cudnn from torch.utils.tensorboard import SummaryWriter import sys sys.path.append('./') from configs import args_faster_rcnn_hoim from lib.datasets import get_data_loader ...
nilq/baby-python
python
import smtplib import os import mimetypes from email import encoders from email.mime.base import MIMEBase from email.mime...
nilq/baby-python
python
import os from typing import Union import sqlite3 from sqlite3 import Error from coordinates import Coordinates class SqlHandler: def __init__(self): self._database = "data.db" self._connection = None self._cursor = None self.connected = False def _create_new_database(self) ->...
nilq/baby-python
python
# -*- coding: utf8 -*- __description__ = "Pick a random item from a given list of items. The trigger is 'pick'." __version__ = "1.0" __author__ = "Dingo" from core.plugin import Plugin import re import random async def pick(command): message = " ".join(command.args) message = message.replace(" and say:", ":...
nilq/baby-python
python
#! /usr/bin/env python # -*- coding:UTF-8 -*- """ ------------------------------------------------------------------------------------------ It is used to get the longest mRNA of gene and filter pep and cds result with a certain length; usage: python xx.py -i GFF -f FASTA -g out.gff -o out.fa -s species_short_n...
nilq/baby-python
python
import httpx group_types = ("group", "supergroup") http = httpx.AsyncClient(http2=True) class Permissions: can_be_edited = "can_be_edited" delete_messages = "can_delete_messages" restrict_members = "can_restrict_members" promote_members = "can_promote_members" change_info = "can_change_info" ...
nilq/baby-python
python
#!/usr/bin/python3 from pwn import * binary = ELF('./dead-canary') libc = ELF('/lib/x86_64-linux-gnu/libc.so.6') context.update(arch='amd64',os='linux') binary.symbols['main'] = 0x400737 offset = 6 libcoffset = 41 #p = process(binary.path) p = remote('2020.redpwnc.tf', 31744) # first pass, inf. retries if we blow ...
nilq/baby-python
python
""" Typcasting w. Integers & Floats """ # Convert these numbers into floats and back. Print out each result as well as its data type. five = 5 zero = 0 neg_8 = -8 neg_22 = -22 five = float(five) zero = float(zero) neg_8 = float(neg_8) neg_22 = float(neg_22) print(five, type(five)) # 5.0 <class 'float'> print(zero,...
nilq/baby-python
python
from io import StringIO import json import streamlit as st from water_rocket import WaterRocket def page_introduction(wr: WaterRocket) -> WaterRocket: st.title("Open Water Rocket") st.write(""" ## Objectives The goal of this app to provide a simple platform for analysing wate...
nilq/baby-python
python
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class SurfaceClassifier(nn.Module): def __init__(self, filter_channels, num_views=1, no_residual=True, last_op=None): super(SurfaceClassifier, self).__init__() self.filters = [] self.num_views = num_view...
nilq/baby-python
python
class PushwooshException(Exception): pass class PushwooshCommandException(PushwooshException): pass class PushwooshNotificationException(PushwooshException): pass class PushwooshFilterException(PushwooshException): pass class PushwooshFilterInvalidOperatorException(PushwooshFilterException): ...
nilq/baby-python
python
import socket from smtplib import SMTPException from django.core.mail import EmailMessage from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ def send_email(instance): context = { "user": instance, "api_key": instance.client.api_key, } ...
nilq/baby-python
python
import numpy as np from scipy.spatial import Delaunay import matplotlib.pyplot as plt from matplotlib.collections import LineCollection class AlphaVisualization: """ Visualization methods for AlphaShapes class. """ def plot_boundary(self, color='k', ax=None, **kwargs): """ Plot boundary of c...
nilq/baby-python
python
import os.path import argparse import json import yaml from datetime import datetime import numpy as np import plotly.graph_objects as go import plotly.express as px import ctypes import PySimpleGUI as sg class Stats: '''Yliluokka, joka sisältää päivämäärät sekä metodin näiden muuttamiseksi oikeaan muotoon ja meto...
nilq/baby-python
python
from keg_elements.extensions import lazy_gettext as _ def base36_to_int(s): """ Convert a base 36 string to an int. Raise ValueError if the input won't fit into an int. https://git.io/vydSi """ # To prevent overconsumption of server resources, reject any # base36 string that is longer tha...
nilq/baby-python
python
from ..data.context import setCurTxn, getCurTxn from ..data.txn import Transaction from ..constants import classNameKey, methodNameKey, preHookKey, postHookKey def captureTxn(args, kwargs): txn = Transaction() setCurTxn(txn) def endTxn(args, kwargs): txn = getCurTxn() if txn is None or args is None: ...
nilq/baby-python
python
from django.contrib.auth.models import User, Group from django.db import models from primer.db.models import UUIDField # Monkey Patch User Model User.add_to_class('uuid', UUIDField()) User.add_to_class('created', models.DateTimeField(auto_now_add=True, editable = False, blank = True, null = True)) User.add_to_class('m...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import import collections import os from contextlib import contextmanager import six from python_pachyderm.client.pfs.pfs_pb2 import * from python_pachyderm.client.pfs.pfs_pb2_grpc import * BUFFER_SIZE = 3 * 1024 * 1024 # 3MB TODO: Base this on some grpc va...
nilq/baby-python
python
__author__ = 'Irina.Chegodaeva'
nilq/baby-python
python
from django.shortcuts import render, get_object_or_404 from .models import BlogPost def blogIndex(request): blogposts = BlogPost.objects.order_by('-pub_date') context = { 'heading':'The Blog', 'subheading':'', 'title':'Blog', 'copyright':'Pending', 'blogposts':blogposts, } return render(request,'blog-hom...
nilq/baby-python
python
"""Module test_listwrapper. The MIT License Copyright 2022 Thomas Lehmann. 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, co...
nilq/baby-python
python
import cv2 import dlib import imutils from imutils import face_utils import winsound from scipy.spatial import distance detector=dlib.get_frontal_face_detector() predict=dlib.shape_predictor("C:/Users/kushal asn/Downloads/shape_predictor_68_face_landmarks.dat") def eye_aspect_ratio(Eye): A=distance.eucli...
nilq/baby-python
python
import re import cltk.corpus.persian.alphabet as alphabet from cltk.corpus.arabic.alphabet import * to_reform = [ { "characters": [ HAMZA, HAMZA_BELOW, HAMZA_ABOVE, HAMZA_ISOLATED, MINI_ALEF, SMALL_ALEF, SMAL...
nilq/baby-python
python
from __future__ import absolute_import, division, print_function VERSION = '1.4.0' def get_version(): return VERSION __version__ = get_version() def get_changelist(): # Legacy from the perforce era, but keeping this. It's not worth breaking return "UnknownChangelist"
nilq/baby-python
python
""" * Copyright 2019 TIBCO Software 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. * A copy of the License is included in the distribution package with this file. * You also may obtain a copy of the L...
nilq/baby-python
python
import base64 import requests import uuid import time class MGTV: def __init__(self, url): self.url = url def get_video_id(self): return self.url.split("/", 5)[-1].split(".")[0] def get_pm2(self): did = "e6e13014-393b-43e7-b6be-2323e4960939" suuid = uuid.uuid4() p...
nilq/baby-python
python
import copy import pickle import torch import types from . import layers from . import rules Rules = rules.Rules def flatten_model(module): ''' flatten modul to base operation like Conv2, Linear, ... ''' modules_list = [] for m_1 in module.children(): if len(list(m_1.children())) == 0: ...
nilq/baby-python
python
import pytest import os from tddc import common def test_get_base_filename(): assert common.get_base_filename('/Users/foo/bar.txt') == 'bar' assert common.get_base_filename('bar.txt') == 'bar' assert common.get_base_filename('bar') == 'bar' assert common.get_base_filename('bar.txt.gz') == 'bar.txt' ...
nilq/baby-python
python
# compare gene numbers in different samples import pandas as pd import scanpy as sc import matplotlib.pyplot as plt import seaborn as sns from pathlib import Path from scipy.stats import ttest_ind import scipy.stats as stats import scikit_posthocs as sp #-------------------variable-------------------------------- fmt...
nilq/baby-python
python
# # Este arquivo é parte do programa multi_agenda # # Esta obra está licenciada com uma # Licença Creative Commons Atribuição 4.0 Internacional. # (CC BY 4.0 Internacional) # # Para ver uma cópia da licença, visite # https://creativecommons.org/licenses/by/4.0/legalcode # # WELLINGTON SAMPAIO - wsampaio@yahoo.com #...
nilq/baby-python
python
# Generated by Django 2.2.16 on 2020-09-21 16:18 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('contest', '0001_initial'), ('lecture', '0001_initial'), ] operations = [ migrations.AddField( ...
nilq/baby-python
python
import torch.nn as nn import torch.nn.functional as F from torch import cat, stack, sqrt class MLPNetwork(nn.Module): """ MLP network (can be used as value or policy) """ def __init__(self, input_dim, out_dim, hidden_dim=64, nonlin=F.relu, constrain_out=False, norm_in=True, discrete_ac...
nilq/baby-python
python
import re from datetime import date, datetime, timezone from urllib.parse import urljoin, urlparse import pytest from swpt_debtors import procedures as p from swpt_debtors import models as m @pytest.fixture(scope='function') def client(app, db_session): return app.test_client() @pytest.fixture(scope='function')...
nilq/baby-python
python
from lxml import etree from defusedxml.lxml import fromstring import uuid from django.db import models from django.http import HttpResponse from django.urls import reverse from django.core.exceptions import ObjectDoesNotExist from acs.response import get_soap_envelope from acs.models import AcsHttpBaseModel from acs....
nilq/baby-python
python
from typing import List from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Product(BaseModel): id: str class Review(BaseModel): body: str product: Product class User(BaseModel): reviews: List[Review] USER_DATA = { "1": User(reviews=[Review(body="Great!", produ...
nilq/baby-python
python
import bpy from bpy.props import * PROP_TYPE_ICONS = { "String": "SORTALPHA", "Int": "CHECKBOX_DEHLT", "Float": "RADIOBUT_OFF", "Bool": "CHECKMARK", "Vec2": "ORIENTATION_VIEW", "Vec3": "ORIENTATION_GLOBAL", "Vec4": "MESH_ICOSPHERE", "Object": "OBJECT_DATA", "CameraObject": "CAMERA_D...
nilq/baby-python
python
import numpy as np import pandas as pd import sklearn from typing import Dict, Tuple from sklearn.base import BaseEstimator class RuleAugmentedEstimator(BaseEstimator): """Augments sklearn estimators with rule-based logic. This class is a wrapper class for sklearn estimators with the additional possibilit...
nilq/baby-python
python
# jay mahakal import Resources.Work_By_Raj.Google_Calender_api.Resources.Setup import Resources.Work_By_Raj.Google_Calender_api.Resources.Return_events_info # below function [Setup.setup_calendar_credentials_return_service()] should run only once # service = Setup.setup_calendar_credentials_return_service() # pri...
nilq/baby-python
python
print "Ejercicio de ciclos -Granizada-" def par(n): n=n/2 def impar(n): n=n*3+1 n=int(raw_input("digite numero ")) while n>=1: if n%2==0: par(n) print n else: impar(n) print n
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 1 15:39:06 2020 @author: jireh.park """ import pandas as pd import os from tqdm import tqdm from google.cloud import storage os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))+ '/key/level-...
nilq/baby-python
python
#!/usr/bin/env python2.7 import os import codecs import json import random with codecs.open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "apps.txt"), encoding="utf-8") as f: apps = f.read().splitlines() with codecs.open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "networks.txt"), encodin...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """user表测试""" from executor.database.models.user import Users from executor.tests.database.base import DatabaseTestCase from executor.exceptions import UserAlreadyExistException, \ IncorrectPasswordException class TestOperatorUser(DatabaseTestCase): data_file_path...
nilq/baby-python
python
# Copyright 2020 Google LLC # # 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, ...
nilq/baby-python
python
# OBS # Imagem celular original do vírus recentemente descoberto SARS-CoV-2, # popularmente chamado de COVID-19 ou Coronavirus. import cv2 as cv import numpy as np import matplotlib.pyplot as plt !wget "https://raw.githubusercontent.com/PedroHaupenthal/Image-Processing/master/watershed/covid_19.jpg" -O "covid_19.jpg...
nilq/baby-python
python