content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/python3 """ Importing models using the FileStorage class """ import json import models import os.path class FileStorage: """ Class that serializes instances to a JSON file and deserializes JSON file to instances """ __file_path = "file.json" __objects = {} def all(self): ...
nilq/baby-python
python
#coding: utf-8 from lxml import etree as ET import re import plumber SUPPLBEG_REGEX = re.compile(r'^0 ') SUPPLEND_REGEX = re.compile(r' 0$') ISO6392T_TO_ISO6392B = { u'sqi': u'alb', u'hye': u'arm', u'eus': u'baq', u'mya': u'bur', u'zho': u'chi', u'ces': u'cze', u'nld': u'dut', u'fra':...
nilq/baby-python
python
# Generated by Django 3.1.2 on 2020-10-12 22:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dominios', '0002_dominio_data_updated'), ] operations = [ migrations.AddField( model_name='dominio', name='uid_anter...
nilq/baby-python
python
# -*- coding: utf-8 -*- from datetime import datetime DISCOUNT_RATE = 0.125 BASE_BID = {'NBUdiscountRate': DISCOUNT_RATE, 'annualCostsReduction': [92.47] + [250] * 20, 'yearlyPaymentsPercentage': 0.70, 'contractDuration': {'years': 2, 'days': 10}, 'announcementDate': d...
nilq/baby-python
python
import copy from rest_framework import viewsets from rest_framework.decorators import api_view from rest_framework.response import Response from dashboard.models import Place from api_v1.containers.place.serializers import PlaceSerializer from api_v1.serializers import BatchRequestSerializer class PlaceViewSet(viewset...
nilq/baby-python
python
import re import string import numpy as np from math import log from typing import List from collections import Counter from .document import Document class CountVectorizer: @staticmethod def split_iter(document_content: str): """ Splits document in words and returns it as generator. ...
nilq/baby-python
python
from django.contrib.auth.decorators import login_required from django.shortcuts import render,redirect,get_object_or_404 from django.contrib.auth.models import User from django.http import Http404,HttpResponse from django.contrib import messages from django.db.models import Q from .forms import * from .models import * ...
nilq/baby-python
python
import healpy as hp import numpy as np def iqu2teb(IQU, nside, lmax=None): alms = hp.map2alm(IQU, lmax=lmax, pol=True) return hp.alm2map(alms, nside=nside, lmax=lmax, pol=False) def teb2iqu(TEB, nside, lmax=None): alms = hp.map2alm(TEB, lmax=lmax, pol=False) return hp.alm2map(alms, nside=nside, lmax=...
nilq/baby-python
python
# Copyright 2014 Pierre de Buyl # # This file is part of pmi-h5py # # pmi-h5py is free software and is licensed under the modified BSD license (see # LICENSE file). import test_pmi_mod mytest = test_pmi_mod.MyTest('myllfile.h5', 1024) mytest.fill() mytest.close()
nilq/baby-python
python
#!/usr/bin/env python #-*- mode: Python;-*- import ConfigParser import json import logging import os import sys import tempfile import traceback import click from requests.exceptions import HTTPError from ecxclient.sdk import client import util cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__), 'c...
nilq/baby-python
python
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ import unittest.mock as mock import unittest import time import pytest import ly_test_tools.environment.waite...
nilq/baby-python
python
# -*- encoding: utf-8 -*- """ keri.kli.commands module """ import argparse import json from hio.base import doing from keri import kering from keri.db import basing from ... import habbing, keeping, agenting, indirecting, directing parser = argparse.ArgumentParser(description='Rotate keys') parser.set_defaults(hand...
nilq/baby-python
python
from ucsmsdk.ucsexception import UcsException import re, sys # given an array and a string of numbers, make sure they are all in the array: # def check_values(array, csv): indexes = csv.split(',') for i in indexes: try: i = int(i) - 1 except: print "bad value: " + i ...
nilq/baby-python
python
from django.test import TestCase class geopollTest(TestCase): """ Tests for django-geopoll """ def test_geopoll(self): pass
nilq/baby-python
python
import settings import json import unittest import requests from inventory.tests import fixture class ApiTests(unittest.TestCase): def setUp(self): # Verify Server is running. # Verify Elastic Search is running. self.endpoint = 'http://{hostname}:{port}/v1/inventory'.format( h...
nilq/baby-python
python
import requests from bs4 import BeautifulSoup import json from smtp import send_mail header = {"User-agent": "Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1 "} euro = 4.25 def items(): try: with open('items.json','r') as file: data = file.read() global li...
nilq/baby-python
python
import subprocess import time from timeit import default_timer as timer start = timer() commands_node1 = ''' export NODE_ID=3001 ''' addresses = [ '13XfCX8bLpdu8YgnXPD4BDeBC5RyvqBfPh', '14L3zLQWPiXM6hZXdfmgjET8crM52VJpXX', '1C4tyo8poeG1uFioZjtgnLZKotEUZFJyVh', '18Nt9jiYVjm2TxCTHNSeYquriaauh5wfux', ...
nilq/baby-python
python
from rest_framework import serializers from can_server.models import DbcFile, CanSettings class DbcFileSerializer(serializers.ModelSerializer): class Meta: model = DbcFile fields = ('FileName', 'FileData') class CanSettingsSerializer(serializers.ModelSerializer): class Meta: model = ...
nilq/baby-python
python
from django.core import mail from django.test import override_settings, TestCase from django.urls import reverse from opentech.apply.utils.testing.tests import BaseViewTestCase from .factories import OAuthUserFactory, StaffFactory, UserFactory @override_settings(ROOT_URLCONF='opentech.apply.urls') class BaseTestProf...
nilq/baby-python
python
import xlrd class ReadExcel: def readexcel(self, url): data = xlrd.open_workbook(url) # 打开xls文件 table = data.sheets()[0] # 打开第一张表 nrows = table.nrows # 获取表的行数 htmlhead = '''<!DOCTYPE html> <html lang="en"> <head> ...
nilq/baby-python
python
from __future__ import absolute_import from six.moves import range try: import h5py except: pass import logging import scipy as sp from fastlmm.pyplink.snpset import * from fastlmm.pyplink.altset_list import * #!!document the format class Hdf5(object): def __init__(self,filename, order = 'F',blocksize=...
nilq/baby-python
python
__author__ = 'lionel' #!/usr/bin/python # -*- coding: utf-8 -*- import struct import sys # 搜狗的scel词库就是保存的文本的unicode编码,每两个字节一个字符(中文汉字或者英文字母) # 找出其每部分的偏移位置即可 # 主要两部分 # 1.全局拼音表,貌似是所有的拼音组合,字典序 # 格式为(index,len,pinyin)的列表 # index: 两个字节的整数 代表这个拼音的索引 # len: 两个字节的整数 拼音的字节长度 # pinyin: 当前的拼音,每个字符两个字节,总...
nilq/baby-python
python
from . import upgrade_0_to_1 from . import upgrade_2_to_3 from . import upgrade_7_to_8 from . import upgrade_8_to_9 def init_new_testsuite(engine, session, name): """When all the metadata fields are setup for a suite, call this to provision the tables.""" # We only need to do the test-suite agnostic upgra...
nilq/baby-python
python
class Field: def __init__(self, left_lb, sv, e, right_lb): self._parameter = None self._left_lb = left_lb self._sv = sv self._e = e self._right_lb = right_lb def set_parameter(self, parameter): self._parameter = parameter def get_parameter(self): ret...
nilq/baby-python
python
from django.core.validators import RegexValidator from django.utils.translation import gettext_lazy as _ class BusinessIDValidator(RegexValidator): regex = r"^[0-9]{7}\-[0-9]{1}\Z" message = _("Enter a valid business ID.")
nilq/baby-python
python
# Import libnacl libs import libnacl.public import libnacl.dual # Import python libs import unittest class TestDual(unittest.TestCase): ''' ''' def test_secretkey(self): ''' ''' msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.' bob = libna...
nilq/baby-python
python
import numpy as np import zengl from objloader import Obj from PIL import Image from progress.bar import Bar from skimage.filters import gaussian import assets from window import Window window = Window(720, 720) ctx = zengl.context() image = ctx.image(window.size, 'rgba8unorm', samples=4) depth = ctx.image(window.si...
nilq/baby-python
python
import FWCore.ParameterSet.Config as cms process = cms.Process("Demo") ##process.load("AuxCode.CheckTkCollection.Run123151_RECO_cff") process.load("FWCore.MessageService.MessageLogger_cfi") MessageLogger = cms.Service("MessageLogger", cout = cms.untracked.PSet( ...
nilq/baby-python
python
import numpy as np # a = np.array([[1, 2], [3, 4]]) # a = np.array([[[1, 2], [3, 4]], [[5,6],[7,8]]]) a = np.array([[[0, 1], [2, 3]], [[4,5],[6,7]]]) print(a.sum(axis = 0)) print(a.sum(axis = 1))
nilq/baby-python
python
import numpy as np import abc import os from typing import NamedTuple, Optional, List, Dict, Tuple, Iterable from representation.code2vec.common import common from representation.code2vec.vocabularies import Code2VecVocabs, VocabType from representation.code2vec.config import Config class ModelEvaluationResults(Name...
nilq/baby-python
python
from tkinter import * from tkinter import filedialog from tkinter.constants import * import platform import os import re class Window(Frame): desktop_path = os.path.expanduser("~/Desktop") def __init__(self, master=None): Frame.__init__(self, master) self.master = master ...
nilq/baby-python
python
import heroku3 from config import Config client = heroku3.from_key(Config.HEROKU_API_KEY) class HerokuHelper: def __init__(self,appName,apiKey): self.API_KEY = apiKey self.APP_NAME = appName self.client = self.getClient() self.app = self.client.apps()[self.APP_NAME] def getCli...
nilq/baby-python
python
from django.apps import AppConfig class LoverRecorderConfig(AppConfig): name = 'lover_recorder'
nilq/baby-python
python
import numpy SCENARIO_VERSION = '2020a' # default scenario version for writing scenario files SUPPORTED_COMMONROAD_VERSIONS = {'2018b', '2020a'} # supported version for reading scenario files TWO_PI = 2.0 * numpy.pi
nilq/baby-python
python
import random print("Hi, please enter your name") name = input() #input 1 secretNumber = random.randint(1, 50) print(name + ' Guess the number between 1 & 50', '\nYou have 4 tries') attempts = 0 for attempts in range(1, 5): print('Take a guess') while True: try: guess...
nilq/baby-python
python
class PrettyEnv(RenderBasic): def __init__( ): def getBestEnv def getEnvList
nilq/baby-python
python
# Copyright 2020 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
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: globalids.py # # Tests: libsim - connecting to simulation and retrieving data from it. # mesh - 3D unstructured mesh. # global node and cell ids # unstructur...
nilq/baby-python
python
import sys import typing def equation(a: int, b: int, c: int) -> typing.Tuple[int, int]: x1 = (-1*b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a) x2 = (-1*b - (b ** 2 - 4 * a * c) ** 0.5) / (2 * a) return int(x1), int(x2) def test() -> None: assert equation(1, -3, -4) == (4, -1) assert equation(13, 2...
nilq/baby-python
python
# # PySNMP MIB module CISCO-MOBILITY-TAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-MOBILITY-TAP-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:07:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
nilq/baby-python
python
from conans import ConanFile, tools class McapConan(ConanFile): name = "mcap" version = "0.0.1" url = "https://github.com/foxglove/mcap" homepage = "https://github.com/foxglove/mcap" description = "A C++ implementation of the MCAP file format" license = "Apache-2.0" topics = ("mcap", "seri...
nilq/baby-python
python
# ----------------------------------- # import # ----------------------------------- from .basebox import FullBox from heifpy.file import BinaryFileReader # ----------------------------------- # define # ----------------------------------- # ----------------------------------- # function # -------------...
nilq/baby-python
python
import base64 def decode(data): # adding extra = for padding if needed pad = len(data) % 4 if pad > 0: data += "=" * (4 - pad) return base64.urlsafe_b64decode(data)
nilq/baby-python
python
import screendetect import os import sys import time import keyboard import pyautogui import playsound import pydirectinput def play(): pass def start(): time.sleep(3) pydirectinput.click(900, 550) pydirectinput.click(1239, 957) pydirectinput.click(670, 1018) screendetect.wait_for_screen('l...
nilq/baby-python
python
#!/usr/bin/env python3 # # Tool for upgrading/converting a db # Requirements: # 1) Databse Schema - schema for the new database you what to upgrade to # 2) Config File - the config file that describes how to convert the db # # Notes: # 1) Will attempt to convert the db defined in /etc/planetlab/plc_config # 2) Does no...
nilq/baby-python
python
"""Support for user- and CDC-based flu info sensors from Flu Near You.""" from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_STATE, CONF_LATITUDE, CONF_LONGITUDE, ) from homeassistant.core import callback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import CA...
nilq/baby-python
python
# License: BSD 3 clause import unittest from tick.solver import SGD from tick.solver.tests import TestSolver class SGDTest(object): def test_solver_sgd(self): """...Check SGD solver for Logistic Regression with Ridge penalization """ solver = SGD(max_iter=100, verbose=False, seed...
nilq/baby-python
python
""" Tests for the `kpal.kmer` module. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from future import standard_library from future.builtins import str, zip import itertools from io import open, StringIO from Bio import Seq import numpy as np from...
nilq/baby-python
python
__author__ = 'wei' __all__=["gt_req_pb2" ]
nilq/baby-python
python
import os import toml from test_common import make_source_dic from rcwa.tmm import tmm_ def make_layer_dic(epsilon, mu, thickness): return {'epsilon': epsilon, 'mu': mu, 'thickness': thickness} def test_benchmark(): '''Test case from Computational Electromagnetics Course Assignment by Raymond Rumpf''' t...
nilq/baby-python
python
from bs4 import BeautifulSoup with open('cooking.html') as f: body = f.read() soup = BeautifulSoup(body, 'lxml') def rows(soup): item = soup.find(id='Recipes').find_next('table').tr while item: if item: item = item.next_sibling if item: item = item.next_sibling if item: yield item...
nilq/baby-python
python
from collections import OrderedDict from flask import Flask from werkzeug.wsgi import DispatcherMiddleware, SharedDataMiddleware import config from ext import sse from views import home, json_api def create_app(): app = Flask(__name__) app.config.from_object(config) app.register_blueprint(home.bp) ...
nilq/baby-python
python
# -*- coding: utf-8 -*- import sys import glob import codecs args = sys.argv #FilePath product_path_name = args[1] grep_file_name = product_path_name + "\**\*.txt" result_file_name = "ResultGrep.txt" hit_word = "TODO" #サブディレクトリまで対象にする list_up = glob.glob(grep_file_name, recursive=True) result_open = codecs.open(r...
nilq/baby-python
python
from osgeo import gdal import os import numpy as np from scipy import ndimage as ndi from skimage.morphology import remove_small_objects, watershed import tqdm def rlencode(x, dropna=False): """ Run length encoding. Based on http://stackoverflow.com/a/32681075, which is based on the rle func...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Thu Nov 15 17:39:25 2018 Good morning! Here's your coding interview problem for today. This problem was asked by Amazon. Given a N by M matrix of numbers, print out the matrix in a clockwise spiral. For example, given the following matrix: [[1, 2, 3, 4, 5], [6...
nilq/baby-python
python
from flask import request, render_template, redirect, flash, Blueprint, session, current_app from ..config import CLIENT_ID, CALLBACK_URL from bs4 import BeautifulSoup import requests import hashlib import base64 import string import random auth = Blueprint('auth', __name__) @auth.route("/callback") def indieauth_cal...
nilq/baby-python
python
import datetime import os # from heavy import special_commit def modify(): file = open('zero.md', 'r') flag = int(file.readline()) == 0 file.close() file = open('zero.md', 'w+') if flag: file.write('1') else: file.write('0') file.close() def commit(): os.system('...
nilq/baby-python
python
""" Additional Activation functions not yet present in tensorflow Creation Date: April 2020 Creator: GranScudetto """ import tensorflow as tf def mish_activation(x): """ Mish activation function as described in: "Mish: A Self Regularized Non-Monotonic Neural Activation Function" https://arx...
nilq/baby-python
python
# coding: utf-8 from __future__ import absolute_import import unittest from unittest import mock from swagger_server.test import BaseTestCase from swagger_server.wml_util import get_wml_credentials from swagger_server.test_mocked.util import mock_wml_env, MOCKED_CREDENTIALS_VARS class TestWMLUtil(BaseTestCase, un...
nilq/baby-python
python
""" Code to represent a dataset release. """ from enum import Enum import json import copy from dataclasses import dataclass from typing import Dict, List, Tuple #################### # Utility functions and enums. def load_jsonl(fname): return [json.loads(line) for line in open(fname)] class Label(Enum): ...
nilq/baby-python
python
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User from .forms import CustomUserChangeForm,CustomUserCreationForm class UserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = User fieldsets = ( ('Us...
nilq/baby-python
python
import ptypes, math, logging from ptypes import * from .primitives import * ptypes.setbyteorder(ptypes.config.byteorder.bigendian) ### primitives ## float types class FLOAT16(pfloat.half): pass class FLOAT(pfloat.single): pass class DOUBLE(pfloat.double): pass ## int types class SI8(pint.int8_t): pass class SI16(pi...
nilq/baby-python
python
# This should work on python 3.6+ import ahip URL = "http://httpbin.org/uuid" async def main(backend=None): with ahip.PoolManager(backend=backend) as http: print("URL:", URL) r = await http.request("GET", URL, preload_content=False) print("Status:", r.status) print("Data:", await ...
nilq/baby-python
python
#!/usr/bin/env python from netmiko import ConnectHandler iosv_l2_SW5 = { 'device_type': 'cisco_ios', 'ip': '192.168.10.100', 'username': 'admin', 'password': 'cisco', } iosv_l2_SW1 = { 'device_type': 'cisco_ios', 'ip': '192.168.10.101', 'username': 'admin', 'password': 'cisco', } iosv_...
nilq/baby-python
python
from django.conf import settings from django.utils.deprecation import MiddlewareMixin from django.utils.functional import SimpleLazyObject from mediawiki_auth import mediawiki def get_user(request): if not hasattr(request, '_cached_user'): request._cached_user = mediawiki.get_or_create_django_user(request...
nilq/baby-python
python
""" Module to run something """ def hello_world(message='Hello World'): """ Print demo message to stdout """ print(message)
nilq/baby-python
python
""" This example shows how EasyNMT can be used for sentence translation """ import datetime from easynmt import EasyNMT sentences = [ # '薄雾', # 'Voici un exemple d\'utilisation d\'EasyNMT.', # 'This is an example how to use EasyNMT.', '南瓜人?', # 'Cada frase es luego traducida al idioma de destino sele...
nilq/baby-python
python
from . import argument_magics as _args from . import data_magics as _data from .list_magic import L as _LType from .seq_magic import N as _NType # Argument magics X_i = _args.X_i() F = _args.F() # Sequence type N = _NType() # Data magics L = _LType() D = _data.D() S = _data.S() B = _data.B() T = _data.T()
nilq/baby-python
python
""" 実績作業時間に関するutil関数を定義しています。 """ from __future__ import annotations import datetime from collections import defaultdict from typing import Any, Dict, Optional, Tuple from annoworkapi.utils import datetime_to_str, str_to_datetime _ActualWorkingHoursDict = Dict[Tuple[datetime.date, str, str], float] """実績作業時間の日ごとの情報を...
nilq/baby-python
python
from __future__ import unicode_literals from django_markdown.models import MarkdownField from django.db import models from django.contrib.auth.models import User from taggit.managers import TaggableManager from taggit.models import TaggedItemBase from os.path import join as isfile from django.conf import settings im...
nilq/baby-python
python
import xsimlab as xs from ..processes.boundary import BorderBoundary from ..processes.channel import (StreamPowerChannel, DifferentialStreamPowerChannelTD) from ..processes.context import FastscapelibContext from ..processes.flow import DrainageArea, SingleFlowRouter, MultipleFlowRoute...
nilq/baby-python
python
""" Effects classes added to show because they track themselves over time have one or more targets that they can apply the effect to in unison change some attribute over time - generally using envelopes """ import random from birdfish.envelope import (Envelope, EnvelopeSegment, ColorEnvelope) from birdfish.li...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # python-json-patch - An implementation of the JSON Patch format # https://github.com/stefankoegl/python-json-patch # # Copyright (c) 2011 Stefan Kögl <stefan@skoegl.net> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted...
nilq/baby-python
python
import argparse import os class Parameters(): def __init__(self):### # Training settings self.LR=0.001 self.clsLR=0.001 self.batch_size=30 self.nthreads=8 self.tensorname='IDeMNet' self.ways=5 self.shots=5 self.test_num=15 self.augn...
nilq/baby-python
python
from posixpath import join import threading from civis.response import PaginatedResponse, convert_response_data_type def tostr_urljoin(*x): return join(*map(str, x)) class CivisJobFailure(Exception): def __init__(self, err_msg, response=None): self.error_message = err_msg self.response = re...
nilq/baby-python
python
class InstantTest: pass
nilq/baby-python
python
import os import numpy as np from PIL import Image import cv2 import pickle BASE_DIR = os.path.dirname(os.path.abspath(__file__)) image_dir = os.path.join(BASE_DIR, "images") face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml') recognizer = cv2.face.LBPHFaceRecognizer_create() curre...
nilq/baby-python
python
from rest_framework import status from .base_test import BaseTestCase class TestProfile(BaseTestCase): """Test the User profile GET responses""" all_profiles_url = 'http://127.0.0.1:8000/api/profiles/' my_profile_url = 'http://127.0.0.1:8000/api/profiles/jane' def test_get_all_profiles_without_accou...
nilq/baby-python
python
import lambdser import multiprocessing as mp def make_proxy(para, *funcs): # make proxy for the mp ser_list = [] for f in funcs: ser_list.append(lambdser.dumps(f)) return para, ser_list def processor(*ser): # unzip the proxy and to the work para, funcs = ser funcs = [lambdser.loa...
nilq/baby-python
python
from numbers import Number import torch from torch.distributions import constraints, Gamma, MultivariateNormal from torch.distributions.multivariate_normal import _batch_mv, _batch_mahalanobis from torch.distributions.distribution import Distribution from torch.distributions.utils import broadcast_all, _standard_normal...
nilq/baby-python
python
import json from pathlib import Path from typing import Tuple from segmantic.seg import dataset def dataset_mockup(root_path: Path, size: int = 3) -> Tuple[Path, Path]: image_dir, labels_dir = root_path / "image", root_path / "label" image_dir.mkdir() labels_dir.mkdir() for idx in range(size): ...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Created on Mon Apr 10 17:41:24 2017 # DEPENDENCIES: import numpy as np import random # FUNCTION THAT CREATES GAUSSIAN MULTIVARIATE 2D DATASETS, D = features, N = observations def create_multivariate_Gauss_2D_dataset(mean, sigma, N_observations): np.random.seed(444...
nilq/baby-python
python
# Generated by Django 3.1.7 on 2021-03-17 12:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backoffice', '0027_auto_20210317_1314'), ] operations = [ migrations.AlterField( model_name='partitionformulla', nam...
nilq/baby-python
python
# -*- coding: utf8 -*- from __future__ import unicode_literals from django.db import models from datetime import datetime from users.models import UserProfile # Create your models here. class Tab(models.Model): name = models.CharField(max_length=50, verbose_name='标签名称') add_time = models.DateTimeField(defa...
nilq/baby-python
python
import unittest import requests from pyalt.api.objects import AltObject class TestAPIObjects(unittest.TestCase): def setUp(self): url_fmt = "https://online-shkola.com.ua/api/v2/users/1269/thematic/subject/{}" self.responses = { requests.get(url_fmt.format(n)) for n in (3...
nilq/baby-python
python
import logging import re from collections import OrderedDict from io import StringIO import numpy as np from .._exceptions import ReadError from .._files import open_file from .._helpers import register from .._mesh import CellBlock, Mesh float_pattern = r"[+-]?(?:\d+\.?\d*|\d*\.?\d+)" float_re = re.compile(float_pa...
nilq/baby-python
python
# -*- coding:utf-8 -*- # author:Anson from __future__ import unicode_literals import os import sys import re from datetime import date, datetime, timedelta from docx import Document import xlwt from settings import MD_PATH, SITE_1, SITE_2, CELL reload(sys) sys.setdefaultencoding('utf-8') def get_file_path(path, ...
nilq/baby-python
python
############################################################################## # Copyright 2016 IBM Corp. # # 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/LI...
nilq/baby-python
python
#!/usr/bin/env python # -*- encoding: utf-8 -*- from __future__ import unicode_literals from collections import OrderedDict as odict from copy import deepcopy from functools import partial import sys import bindings as bi from custom import get_customizations_for, reformat_block PY3 = sys.version_info[0] == 3 str_typ...
nilq/baby-python
python
""" 1. Clarification 2. Possible solutions - Dynamic programming - Divide and Conquer 3. Coding 4. Tests """ # T=O(n), S=O(1) class Solution: def maxSubArray(self, nums: List[int]) -> int: if not nums: return 0 maxn, subSum = -math.inf, 0 for num in nums: subSum += num ...
nilq/baby-python
python
import logging from easyjoblite import state, constants from easyjoblite.utils import kill_process logger = logging.getLogger(__name__) class WorkerManager(object): @staticmethod def stop_all_workers(worker_type): """ stops all the workers of the given type :param worker_type: ...
nilq/baby-python
python
#!/usr/bin/env python2 # Copyright (C) 2001 Jeff Epler <jepler@unpythonic.dhs.org> # Copyright (C) 2006 Csaba Henk <csaba.henk@creo.hu> # Copyright (C) 2011 Marek Kubica <marek@xivilization.net> # # This program can be distributed under the terms of the GNU LGPLv3. import os, sys from errno import * from stat import *...
nilq/baby-python
python
import igraph import numpy as np import pandas as pd from tqdm import tqdm from feature_engineering.tools import lit_eval_nan_proof # this script adds the feature shortest_path to the files training_features and testing_features # this script takes approximately 1000 minutes to execute # progress bar for pandas tqdm...
nilq/baby-python
python
# encoding: utf-8 """ lxml custom element classes for shape tree-related XML elements. """ from __future__ import absolute_import from .autoshape import CT_Shape from .connector import CT_Connector from ...enum.shapes import MSO_CONNECTOR_TYPE from .graphfrm import CT_GraphicalObjectFrame from ..ns import qn from .p...
nilq/baby-python
python
import sys import sh def app(name, *args, _out=sys.stdout, _err=sys.stderr, _tee=True, **kwargs): try: return sh.Command(name).bake( *args, _out=_out, _err=_err, _tee=_tee, **kwargs ) except sh.CommandNotFound: return sh.Command(sys.executable).bake( "-c", ...
nilq/baby-python
python
""" This options file demonstrates how to run a stripping line from a specific stripping version on a local MC DST file It is based on the minimal DaVinci DecayTreeTuple example """ from StrippingConf.Configuration import StrippingConf, StrippingStream from StrippingSettings.Utils import strippingConfiguration from St...
nilq/baby-python
python
from .base import BaseField class IntegerField(BaseField): pass
nilq/baby-python
python
def ingredients(count): """Prints ingredients for making `count` arepas.""" print('{:.2} cups arepa flour'.format(0.1*count)) print('{:.2} cups cheese'.format(0.1*count)) print('{:.2} cups water'.format(0.025*count))
nilq/baby-python
python
from __future__ import absolute_import, unicode_literals import os import celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_project.settings') app = celery.Celery('test_project') # noqa: pylint=invalid-name # Using a string here means the...
nilq/baby-python
python
''' Created on Apr 15, 2016 @author: Drew ''' class CogTV: def __init__(self): pass def setScreen(self, scene): pass
nilq/baby-python
python