content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from rest_framework import serializers from rest_framework.authtoken.models import Token from .models import User from .authentication import token_expire_handler, expires_in class UserSerializer(serializers.HyperlinkedModelSerializer): money_deposits = serializers.HyperlinkedRelatedField( many=True, rea...
nilq/baby-python
python
# example environment, rolegroup, and role defs environmentdefs = { "environment1": ["host1", "host2"], } roledefs = { "role1": ["host1"], } componentdefs = { "role1": ["component1"], }
nilq/baby-python
python
import json from climate_simulation_platform.db import save_revision, save_step from climate_simulation_platform.message_broker import send_preprocessing_message from climpy.interactive import ValueChanger import panel as pn import xarray as xr import numpy from scipy.ndimage import measurements import holoviews as h...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Tue Aug 4 10:56:00 2020 @author: Jimit.Dholakia """ import feedparser import time import urllib.parse import os os.environ['TZ'] = 'Asia/Kolkata' time.tzset() #updated ='Last Updated on: ' + time.strftime('%b %d, %Y %X %Z', time.localtime()) current_time = ...
nilq/baby-python
python
import re from argparse import ArgumentParser from dodo_commands.dependencies import yaml_round_trip_dump from dodo_commands.framework.singleton import Dodo def _args(): parser = ArgumentParser(description="Print the full configuration.") parser.add_argument("key", nargs="?") args = Dodo.parse_args(parse...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Thu Feb 2 10:56:02 2017 @author: FuckYouMicrosoft """ high = 100 low = 0 ans = (high+low)//2 print('Please think of a number between 0 and 100') print('Is your secret number '+ str(ans)+'?') userInput = str(input("Enter 'h' to indicate the guess is too high. Enter '...
nilq/baby-python
python
import numpy as np import tkinter import matplotlib.pyplot as pyplot from matplotlib.path import Path import matplotlib.patches as patches class GridWorldMDP(object): # Construct an GridWorld representation of the form # # 20 21 22 23 24 # 15 x 17 18 19 # 10 x 12 x 14 # 5 ...
nilq/baby-python
python
from django import forms from .models import Loan from books.models import Book class LoanForm(forms.ModelForm): code = forms.CharField(label='Book Code') class Meta: model = Loan fields = [ 'to', ]
nilq/baby-python
python
from time import sleep from operator import itemgetter oficial = str(input('Palpite oficial: ')).strip().split("/") jogadores = int(input('Quantos jogadores vão participar na rodada ? ')) print ('-'* 50) print ('Analizando',end=' ') sleep(1) print ('.',end=' ') sleep(1) print ('.',end=' ') sleep(2) print('.', end=' //...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Sun Mar 15 19:58:26 2020 @author: Ravi """ from collections import Counter def gameOfThrones(s): odd = 0 se = Counter(s) for i in se.values(): if i%2!=0: odd+=1 if odd>1: return 'NO' return 'YES' s = in...
nilq/baby-python
python
"""Simple heartbeat library""" import logging from datetime import timedelta from typing import Optional import requests import isodate heartbeat_app_url = "http://localhost:5000/" __VERSION__ = "0.1.2" __AUTHOR__ = "Joshua Coales" __EMAIL__ = "dr-spangle@dr-spangle.com" __URL__ = "https://github.com/joshcoales/simp...
nilq/baby-python
python
# Generated by Django 3.0.6 on 2020-10-15 14:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('limb', '0004_metalsite_ion'), ] operations = [ migrations.AddField( model_name='metalsite', name='ready_for_presenta...
nilq/baby-python
python
# Generated by Django 2.2 on 2019-06-28 12:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0006_auto_20190628_1200'), ] operations = [ migrations.RenameModel( old_name='Roles', new_name='Role', ), ...
nilq/baby-python
python
from conftest import data_path from kitt.image.objdetect.annotation import AnnotationType from kitt.image.objdetect.voc import voc_to_annotated_image def test_load_voc_xml(): annotated = voc_to_annotated_image(data_path("example.xml")) width, height = annotated.width, annotated.height assert width == 500...
nilq/baby-python
python
import numpy as np import glob, os import random from imageio import imread, imwrite import shutil from skimage import img_as_ubyte, img_as_float from math import ceil, sqrt, pi from scipy.signal import convolve2d import tensorflow as tf from tensorflow.keras.layers import UpSampling2D def generate_patches_pngs(noisy_...
nilq/baby-python
python
import os from landolfio.settings.base import * # noqa # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["landolfio.vofdoesburg.nl"] SESSION_COOKIE_SE...
nilq/baby-python
python
import sys import json from mlscratch.measurer import ProbsMeasurer, Measurer from sacnn.core import SacnnModel, get_arch, compute_labels_accuracy, ConfusionMatrixMeasurer from sacnn.core.fs_utils import load_np_tensor def get_test_data(num_labels): load_folder = 'data_reduced' if num_labels == 3 else 'data' ...
nilq/baby-python
python
"""Auto-generated file, do not edit by hand. AM metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_AM = PhoneMetadata(id='AM', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='[148]\\d{2,4}', possible_length=(3, 4, ...
nilq/baby-python
python
import numpy as np import sys sys.path.insert(0, '../QLearning/' ) from simpleQLearning import QLearningAgent import matplotlib.pyplot as plt import os import random from collections import deque class ReplayBuffer(object): def __init__(self, size): """ Create Replay buffer. Parameters ...
nilq/baby-python
python
class ChromeSpider(object): pass
nilq/baby-python
python
class TestExample: def test_me(self): assert True def but_me(self): assert True class DescribeExample: def it_has_some(self): assert True
nilq/baby-python
python
# -*- coding: utf-8 -*- """Indexing hdf5 files""" ext = '.h5' import os from .. import csutil from .interface import SharedFile class FileManager(object): file_class = SharedFile def __init__(self, store=False): if store is False: self.log = csutil.FakeLogger() else: ...
nilq/baby-python
python
import numpy as np from utils import * def main(): DIMS = (500, 500) data_path = './data/' # load 4 cat images img1 = img_to_array(data_path + 'cat1.jpg', DIMS) img2 = img_to_array(data_path + 'cat2.jpg', DIMS, view=True) # concat into tensor of shape (2, 400, 400, 3) input_img = np.con...
nilq/baby-python
python
import sys import pygame from checkerboard import * import ai_minmax as am def _get_init_player(): flag = input("输入 0(人)/ 1(电脑)指定先手(执黑): ") if flag == "0": return BLACK_CHESSMAN, 0 elif flag == "1": return WHITE_CHESSMAN, 1 else: return None, None def _get_next(cur_runner): ...
nilq/baby-python
python
""" Useful functions for making pretty plots in matplotlib of accuracy of stock predictions. @author: Riley Smith Created: 1-21-2021 """ import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np from utils import COLORS def plot_predicted_close(ticker, pred, true, save_to=None): ""...
nilq/baby-python
python
from threading import Semaphore import threading, random from arg import args from profe import profesor,Materias,profesores mutexP = [Semaphore(1) for i in range(args.profeso)] listA = [Semaphore(0) for i in range(args.profeso)] contadorA= 0 mutexC= Semaphore(1) class Alumno(threading.Thread): def __init__(self,...
nilq/baby-python
python
from datetime import date history_date = {'上期标准仓单交易正式上线': [date(2018, 5, 28), date(2018, 6, 1)], '中东局势动荡': [date(2018, 4, 10), date(2018, 4, 20)], '中国对美国加征关税': [date(2018, 4, 4), date(2018, 4, 11)], '美国再次开启贸易战': [date(2018, 6, 15), date(2018, 6, 30)], '中美...
nilq/baby-python
python
#!/usr/bin/env python """ BehaviorModule ^^^^^^^^^^^^^^ .. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de> Starts the body behavior """ import actionlib import os import rospy from geometry_msgs.msg import PoseWithCovarianceStamped from tf2_geometry_msgs import PoseStamped from humanoid_league_ms...
nilq/baby-python
python
# https://adventofcode.com/2018/day/6 def dist(a,b): return abs(b[0]-a[0]) + abs(b[1]-a[1]) def find_single_closest(x,y, points): closest_points = [] closest_dist = -1 for p in range(len(points)): d = dist(points[p], (x,y)) if d < closest_dist or closest_dist == -1: closest...
nilq/baby-python
python
import eventlet import eventlet.event import logging logger = logging.getLogger(__name__) class GreenletRace: def __init__(self, tasks): self._event = eventlet.event.Event() self._tasks = [eventlet.spawn(self._wrap, fn) for fn in tasks] def _resolve(self, value=None): if not self._ev...
nilq/baby-python
python
import pytest from ceph_deploy.cli import get_parser SUBCMDS_WITH_ARGS = ['push', 'pull'] class TestParserConfig(object): def setup(self): self.parser = get_parser() def test_config_help(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('config --help'.split...
nilq/baby-python
python
import sqlite3 import os import random, string def randomword(length): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length)) class DBWrapper: def __init__(self): self.dbname = randomword(16) + ".db" os.system("touch " + self.dbname) self.conne...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Course : GTI770 — Systèmes intelligents et apprentissage machine Project : Lab # X - Lab's name Students : Names — Permanent Code Group : GTI770-H18-0X """ from __future__ import division, print_function, absolute_import import tensorflow as tf imp...
nilq/baby-python
python
# coding=utf-8 from argparse import ArgumentParser import os from torchvision import models import cv2 import torch import shutil from torchvision import transforms as T from torch.autograd import Variable car_label = ["GMC_SAVANA", "Jeep(进口)_大切诺基(进口)", "Jeep(进口)_牧马人", "Jeep(进口)_自由侠(海外)", "MINI_MINICOUNTRYMAN", "smart...
nilq/baby-python
python
# adjuster.py Demo of Adjusters linked to Labels # Released under the MIT License (MIT). See LICENSE. # Copyright (c) 2021 Peter Hinch # hardware_setup must be imported before other modules because of RAM use. import hardware_setup # Create a display instance from gui.core.ugui import Screen, ssd from gui.widgets.l...
nilq/baby-python
python
from copy import copy NL_type = 'NEWLINE' INDENT_type = 'INDENT' DEDENT_type = 'DEDENT' PAREN_OPENERS = 'LPAR', 'LBRACE', 'LSQB' PAREN_CLOSERS = 'RPAR', 'RBRACE', 'RSQB' class Tok(): def __init__(self, type=None, value=None, lexer=None): self.type = type self.value = value self.lineno = N...
nilq/baby-python
python
import numpy as np import matplotlib.pyplot as plt import os import glob def matlab_multiply(Array_A, Array_B): '''perform matlab style matrix multiplication with implicit expansion of dimesion''' assert np.ndim(Array_A)==1 & np.ndim(Array_B)==1 NewArray = np.zeros((len(Array_B), len(Array_A))) fo...
nilq/baby-python
python
from .run import _reifiers from .unify import _converters, _occurs_checkers, _unifiers def register(key, *, convert=None, unify=None, occurs=None, reify=None): if convert: _converters.add(key, convert) if unify: _unifiers.add(key, unify) if occurs: _occurs_checkers.add(key, occurs)...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ :Author: Jaekyoung Kim :Date: 2018. 8. 24. """ from unittest import TestCase from pandas.util.testing import assert_frame_equal from ksif import * class TestBenchmark(TestCase): def test_benchmark(self): pf = Portfolio() # The return of Portfolio.benchmark should be...
nilq/baby-python
python
from collections import Counter from datetime import datetime import os import requests from subprocess import Popen, PIPE from pathlib import Path import json from typing import Dict, Union, TYPE_CHECKING from kipoi_utils.external.torchvision.dataset_utils import download_url if TYPE_CHECKING: import zenodoclien...
nilq/baby-python
python
"""Nearly empty __init__.py to keep pylint happy.""" from __future__ import annotations
nilq/baby-python
python
from Rules import Rules import random import copy class Montecarlo: def __init__(self, n=1000): self.iterations = n self.game = Rules() def gameOver(self): winner = self.game.get_winner(end=True) if winner == 1: print('AI Winner') elif winner == 0: ...
nilq/baby-python
python
import sys import re import os from setuptools import setup from setuptools import find_packages PY_VER = sys.version_info if PY_VER < (3, 6): raise RuntimeError("asynceth doesn't support Python version prior 3.6") install_requires = [ 'regex', 'ethereum', 'eth_abi>=2.0.0-beta.1' ] tests_require = [...
nilq/baby-python
python
from hashlib import md5 from os.path import join, dirname, exists, samefile from os import walk, unlink, chmod, rename, link, symlink, stat from logging import info, error from tempfile import mktemp from stat import S_ISREG, S_IWUSR class Database(dict): def add(self, path, size, ino, dev, mtime): # dev...
nilq/baby-python
python
# Run this if you want to see that a simple network can be set up and left idle # Just tries to make a CH and a CM and have them connect to each other import CM,CH import time from common import handlers if __name__ == "__main__": head = CH.ClusterHead(CH.UDPHandler,CH.TCPHandler,spoofContract=True) mem = CM.C...
nilq/baby-python
python
nome=input('Digite o nome do aluno: ') n1=float(input('Digite a nota da primeira prova: ')) n2=float(input('Digite a nota da segunda prova: ')) n3=float(input('Digite a nota da terceira prova: ')) nt=(n1+n2+n3) md=(nt/3) print('A nota final do aluno(a) {} foi de {:.2f}.'.format(nome,md))
nilq/baby-python
python
import tensorflow as tf def model_softmax(x,batch_size,total_speakers): print('I/P shape ',x.get_shape()) x=tf.reshape(x,[batch_size,-1,64,1]) with tf.variable_scope('conv2D_A'): x=tf.layers.conv2d(x,filters=32,kernel_size=5, strides=(2,2),padding='SAME',kernel_initializer=tf.contrib.layers.x...
nilq/baby-python
python
# (C) Datadog, Inc. 2022-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) # This file is autogenerated. # To change this file you should edit assets/configuration/spec.yaml and then run the following commands: # ddev -x validate config -s <INTEGRATION_NAME> # ddev -x va...
nilq/baby-python
python
import datetime import logging from typing import Any, Dict, Optional, List, Generic, TypeVar from urbanairship import common, Airship logger = logging.getLogger("urbanairship") ChannelInfoType = TypeVar("ChannelInfoType", bound="ChannelInfo") class ChannelInfo(object): """Information object for iOS, Android, ...
nilq/baby-python
python
import requests import os from forms.utils import get_config_dict, send_message def create_formatted_message(response, breaks='\n'): config = get_config_dict(response['Config']) question_mapping = {} for count, question in enumerate(config['questions'], 1): question_mapping[question['title']] = ...
nilq/baby-python
python
import tkinter as tk import mysql.connector import tkinter.font as tf from tkinter import * def search_user_account(): mydb = mysql.connector.connect( host="localhost", user="root", password="aniket123", database='project_dbms' ) mycursor = mydb.cursor() ...
nilq/baby-python
python
# Demonstration of a magnifier on a map import simplegui # 1521x1818 pixel map of native American language # source - Gutenberg project image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/gutenberg.jpg") # Image dimensions MAP_WIDTH = 1521 MAP_HEIGHT = 1818 # Scal...
nilq/baby-python
python
def call(g): next(g)
nilq/baby-python
python
import sys Height = 48 Width = 128 def is_too_far(cell): dist_sqrt = cell.real*cell.real + cell.imag * cell.imag return dist_sqrt > 4 def iterations(x,y): c = complex(x,y) z = 0 for i in range(0,250): if is_too_far(z): return i z = z*z + c return 256 def plot(): start_posX = -3.0 end_posX = 1.0 ...
nilq/baby-python
python
############################################################ # -*- coding: utf-8 -*- # # # # # # # # # ## ## # ## # # # # # # # # # # # # # # # ## # ## ## ###### # # # # # # # # # Python-based Tool for interaction with the 10micron mounts # GUI with PyQT5 fo...
nilq/baby-python
python
import string import re import nltk class LimpiadorDeTexto(): def __init__(self,dir_stopwords): """ Inicializa y carga lista de stopwords desde el path recibido """ arc = open(dir_stopwords, "r", encoding='utf-8') self.stp_wrds = [line.strip() for line in arc] ...
nilq/baby-python
python
import requests import facebook from Reposter.utils.logger import logger import urllib.request import os class PostSubmitter: def __init__(self, page_id, token, message=False): self.page_id = page_id self.oauth_access_token = token self.message = message ...
nilq/baby-python
python
import textwrap import wx from utils.logger import get_logger from utils.utils import SetIcon2Frame logger = get_logger(__name__) class QRcodeFrame(wx.Frame): def __init__(self, image, meeting_dict, *args, **kwds): self.image = image self.config = args[0].config self.icon_path = args[0]....
nilq/baby-python
python
"""This script deletes all duplicate sentences in a parallel corpus of two languages, L1 and L2. A sentence is considered to be duplicate if the same string appears in L1 in two lines and if in the same two lines in L2, the strings are also the same (with regard to each other only in L2). This means if the L1 corpus e...
nilq/baby-python
python
""" dmt/data/loading/oto_loader.py OTO = OneToOne. Meaning 1 subject loads exactly 1 batch example. Daemon loader wraps torch's Dataloader by continuously loading into a queue. 'Daemon' here refers to its original software interpretation (not Python's) where a process works continuously in the background. Added Func...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Mod: test_package_pool :Synopsis: :Author: servilla :Created: 7/26/20 """ from dateutil import tz from pathlib import Path import pytest from sniffer.config import Config from sniffer.package.package_pool import PackagePool ABQ_TZ = tz.gettz("America/De...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Django Markdownx documentation build configuration file, created by # sphinx-quickstart on Fri Mar 10 22:41:38 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in ...
nilq/baby-python
python
""" Since our development environment is controlled completely by passing environment variables from one process to its children, in general we allow all variables to flow freely. There are, however, a few circumstances in which we need to inhibit this flow. Maya and Nuke, for example, add to the :envvar:`python:PYTH...
nilq/baby-python
python
import os import time def os_walk(folder_dir): for root, dirs, files in os.walk(folder_dir): files = sorted(files, reverse=True) dirs = sorted(dirs, reverse=True) return root, dirs, files def time_now(): '''return current time in format of 2000-01-01 12:01:01''' return time.strft...
nilq/baby-python
python
from setuptools import find_packages, setup with open('README.md', encoding='utf-8') as f: long_description = f.read() setup( name='RailgunS', version='0.56', author='NY', author_email='nyssance@icloud.com', description='Only My Railgun', long_description=long_description, long_descr...
nilq/baby-python
python
from django import forms from loginApp.models import User, Profile class smsForm(forms.ModelForm): field_10_student = forms.MultipleChoiceField(required=False, label='دانش آموزان پایه دهم') field_10_mom = forms.MultipleChoiceField(required=False, label='مادر دانش آموزان پایه دهم') field_10_dad = forms.Mul...
nilq/baby-python
python
#!/usr/bin/env python # -*-coding:utf8 -*- ''' 合并webface数据集和vggface2数据集 注意相同类别的进行合并 ''' import os from PIL import Image def read_overlap(file): # 读取overlap文档,输出对应的dict simi_dict = {} with open(file, 'r') as f: alllines = f.readlines() for line in alllines: line_split = line.str...
nilq/baby-python
python
import numpy as np import math c = 2.9979 * pow(10,8) #Practice test question 1 Type def MagneticField(): dielecConst = float(input("Input the Dielectric Constant: ")) Speed = (c / math.sqrt(dielecConst)) * pow(10,-8) print("Speed:", Speed , "x10^8 m/s") MagneticField()
nilq/baby-python
python
# -*- coding: utf-8 -*- import maths.parser import util.html from .AstNode import * from .IdentifierNode import * from .NumberNode import * from .StringNode import StringNode class BinOpNode(AstNode): """Binary (two operands) operator node left -- left operand (AstNode) right -- right operand (AstNode...
nilq/baby-python
python
import sys import unittest import mock from datetime import datetime import json from .messages import HipchatMessage def setup_mock_request(mock_method, status_code, json_data): mock_response = mock.Mock() mock_response.read.return_value = json.dumps(json_data) mock_response.getcode.return_value = status...
nilq/baby-python
python
class ColourImage(object): def __init__(self,r,g,b): self.r=r self.g=g self.b=b def _determineColorValue(self): return str("#%02x%02x%02x" % (self.r, self.g, self.b)) # return ("hello")
nilq/baby-python
python
#!/usr/bin/env python import os import socket import requests server = os.environ.get("RATSERVER", "localhost") port = os.environ.get("RATPORT", "8000") username = os.environ.get("USER", "") hostname = socket.gethostname() data = { "user": username, "host": hostname, } def rat(message): data["message...
nilq/baby-python
python
import tensorflow as tf from layers import SparseDense, KWinner, SparseConv2D def dense_mlp(): inputs = tf.keras.Input(shape=(784,)) dense1 = tf.keras.layers.Dense(128, activation='relu')(inputs) dense2 = tf.keras.layers.Dense(64, activation='relu')(dense1) logits = tf.keras.layers.Dense(10)(dense2) ...
nilq/baby-python
python
from .base import SampleExtension from application.src.misc.health import ReceivedTreatment, PriorInfection class PatientTreatment(SampleExtension): submit_table_name = "samples_patient_treatment" clean_keys_strings = ["date_of_prior_antiviral_treat", "date_of_prior_sars_cov_2_infe...
nilq/baby-python
python
# coding:utf-8 import time from util.tools import * from util.city import * from search import Search from comment import Comments from exception import InvalidCityUrl from util.http import send_http from util.thread import CrawlThread from decorator.city import recover, \ has_id, has_city_list, map_required from d...
nilq/baby-python
python
def item_already_equipped(lingo, item): if item == 'streak_freeze': return lingo.__dict__['user_data'].__dict__['tracking_properties']['num_item_streak_freeze'] if item == 'rupee_wager': return lingo.__dict__['user_data'].__dict__['tracking_properties']['has_item_rupee_wager'] def process_singl...
nilq/baby-python
python
""" This modul contains benchmark script testing performance of modul cevast.certdb.cert_file_db Run as:> python3 -m cProfile -s calls cert_file_db.py {storage} {10000_certs.gz} {CPUs} > profiles/{commit}_cert_file_db_CPUs """ import sys import time import shutil import cevast.dataset.unifiers as unifier from cev...
nilq/baby-python
python
print("Initializing...")
nilq/baby-python
python
import mock import pytest from utils.objects import immutable from utils.objects import get_attr class ObjectsTestCase(object): @pytest.fixture def simple_object(self): return mock.Mock( first=mock.sentinel.FIRST, second=mock.Mock( first=mock.sentinel.SECOND, ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', description='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license='MIT', version='0.18.0'...
nilq/baby-python
python
#!/usr/bin/env python # Copyright (c) 2014, Tully Foote # 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, ...
nilq/baby-python
python
import tempfile import webbrowser TEMPLATE_FILENAME = 'templates/color_sample.html' class Page: def __init__(self): self.baseHtml = self._get_base_html() @staticmethod def _get_base_html(): with open(TEMPLATE_FILENAME, 'r') as templateFile: return templateFile.read() def...
nilq/baby-python
python
# # Embed a photo data inside a Tk frame # import tkinter as tk import smimgpng as smimg AUTHOR = "Alexandre Gomiero de Oliveira" REPO = "https://github.com/gomiero/bin2src" class App(tk.Frame): def __init__(self, master): super().__init__(master) self.config(width=427, height=640) canvas ...
nilq/baby-python
python
# necessary packages import cv2 import imutils class AspectAwarePreprocessor: def __init__(self, width, height, inter=cv2.INTER_AREA): # store the target image width, height, and interpolation self.width = width self.height = height self.inter = inter def preprocess(self, imag...
nilq/baby-python
python
# Databricks notebook source dbutils.widgets.text("infilefolder", "", "In - Folder Path") infilefolder = dbutils.widgets.get("infilefolder") dbutils.widgets.text("loadid", "", "Load Id") loadid = dbutils.widgets.get("loadid") # COMMAND ---------- import datetime # For testing # infilefolder = 'datalake/data/lnd/201...
nilq/baby-python
python
import torch import torchvision.transforms as transforms import torchvision from tqdm import tqdm from torch.quantization import QuantStub, DeQuantStub import torch.nn as nn import torchvision.models as models transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5,...
nilq/baby-python
python
""" Write a client program permutation.py that takes an integer k as a command-line argument; reads a sequence of strings from standard input, and prints exactly k of them, uniformly at random. Print each item from the sequence at most once. """ import sys from deque import RandomizedQueue if __name__ == "__main__"...
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 ############################################################################### # PARAMETERS # # change these values to change the protocol behavior # ############################################################################### # doesn't matter which units (uM or ug/mL) # as l...
nilq/baby-python
python
""" Quick plot of the dam break outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from numpy import ones, zeros p_st = util.get_output('immersed_bump.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[10] v2=(p2_st.y==v) #p_dev = ...
nilq/baby-python
python
"""Integration tests module. """ from revived.action import action from revived.action import ActionType from revived.reducer import combine_reducers from revived.reducer import Module # from revived.reducer import reducer from revived.store import ActionType as StoreAT from revived.store import Store # # Building rev...
nilq/baby-python
python
from django.db import models from django.utils.translation import ugettext_lazy as _ class OrderStatusName(models.CharField): def __init__( self, verbose_name=_('Name'), max_length=255, *args, **kwargs): super(OrderStatusName, self).__init__( ...
nilq/baby-python
python
from wsrpc.websocket.handler import WebSocketRoute, WebSocket, WebSocketThreaded
nilq/baby-python
python
# # Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list o...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2014, 2015 Robert Simmons # # This file is part of PlagueScanner. # # PlagueScanner is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3...
nilq/baby-python
python
def load_assets(): assets = {} # background do jogo assets['background'] = pygame.image.load(r'img\spacebg.jpg').convert() assets['background']= pygame.transform.scale(assets['background'],(largura,altura)) # tela inicial assets['tela_init'] = pygame.image.load(r'img\screen_start1.png')....
nilq/baby-python
python
import os from ...helpers import DIV PRELOADER = DIV( DIV( DIV( DIV( DIV(_class="phanterpwa_square"), _class="phanterpwa_square_container" ), _class='preloader-wrapper enabled' ), _class="phanterpwa-preloader-wrapper"), ...
nilq/baby-python
python
# Copyright (C) 2015-2021 Swift Navigation Inc. # Contact: https://support.swiftnav.com # # This source is subject to the license found in the file 'LICENSE' which must # be be distributed together with this source. All other rights reserved. # # THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIN...
nilq/baby-python
python
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ if not s: return [] current = [] result = [] self.helper(s, current, result) return result def helper(self, s, cur, r...
nilq/baby-python
python
import logging from nightshift import constants from typing import Dict, List, Tuple import matplotlib.cm from matplotlib.axes import Axes from matplotlib.colors import is_color_like AXIS_LABELS: Dict[str,str] = { 'H': r'$^{1}$H (ppm)', 'N': r'$^{15}$N (ppm)', 'C': r'$^{13}$C (ppm)', } Correlations = ...
nilq/baby-python
python
# Generated by Django 3.0.7 on 2020-08-01 10:48 import django.core.validators from django.db import migrations from django.db import models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Social", fiel...
nilq/baby-python
python