content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/python # # Example of complex # Graph representing a network # import gvgen # Creates the new graph instance graph = gvgen.GvGen(None, "overlap=\"scale\";\nlabelfloat=\"true\";\nsplines=\"true\";") # We define different styles graph.styleAppend("router", "shapefile", "router.png") graph.styleAppend("router...
nilq/baby-python
python
""" Functions related to calculating the rotational energy of asymmetric molecules. Townes and Schawlow, Ch. 4 """ from pylab import poly1d def asymmetry (A,B,C): """ Ray's asymmetry parameter for molecular rotation. For a prolate symmetric top (B = C), kappa = -1. For an oblate symmetric top (B = A), kappa =...
nilq/baby-python
python
import matplotlib.pyplot as plt import numpy as np import torch # from scipy.special import softmax # from mpl_toolkits.axes_grid1 import make_axes_locatable def compare_distogram(outputs, targets): plt.figure(num=1, figsize=[15, 10]) plt.clf() # names = ['Distance','Omega','Phi','Theta'] names = ['dN...
nilq/baby-python
python
import functools import requests import suds.transport as transport import traceback try: import cStringIO as StringIO except ImportError: import StringIO __all__ = ['RequestsTransport'] def handle_errors(f): @functools.wraps(f) def wrapper(*args, **kwargs): try: return f(*args,...
nilq/baby-python
python
''' @author: Frank ''' import zstacklib.utils.http as http import zstacklib.utils.log as log import zstacklib.utils.plugin as plugin import zstacklib.utils.jsonobject as jsonobject import zstacklib.utils.daemon as daemon import zstacklib.utils.iptables as iptables import os.path import functools import t...
nilq/baby-python
python
#a POC of queue manager with two button to increment and decrement the current value and broadcast it by wifi import machine from machine import I2C, Pin import time import network #set to True to enable a display, False to disable it use_display=True if use_display: #display setup, i have a 128x32 oled on this...
nilq/baby-python
python
import sys import PyNexusZipCrawler # GET NEXUS MODS MOD ID FROM USER INPUT f_id = raw_input("Enter the Nexus Mods File ID you want to crawl: ") # CRAWL IT PyNexusZipCrawler.crawl_zip_content(f_id, "110")
nilq/baby-python
python
import logging import os import pyaudio, wave, pylab import numpy as np import librosa, librosa.display import matplotlib.pyplot as plt from scipy.io.wavfile import write from setup_logging import setup_logging INPUT_DEVICE = 0 MAX_INPUT_CHANNELS = 1 # Max input channels DEFAULT_SAMPLE_RATE = 44100 # Default sample...
nilq/baby-python
python
# ------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you unde...
nilq/baby-python
python
from flask import Flask, jsonify import json from flask import Flask, render_template import numpy as np from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func engine = create_engine("sqlite:///Resources/hawaii.sqlite") # reflect an ...
nilq/baby-python
python
class User(): def __init__(self, first_name, last_name, gender, email): self.first_name = first_name self.last_name = last_name self.gender = gender self.email = email self.login_attempts = 0 def describe_user(self): print(self.first_name) print...
nilq/baby-python
python
#!/usr/bin/env python import pod import sys, binascii from StringIO import StringIO def ConvertMac(dotted): if dotted.find(":") == -1: str = binascii.unhexlify(dotted) else: str = "".join([chr(eval("0x"+i)) for i in dotted.split(":")]) if len(str) != 6: raise ValueError("Not a MAC address") ret...
nilq/baby-python
python
from typing import List from ..codes import * from dataclasses import dataclass @dataclass(repr=True, eq=True) class OppoCommand: """Represents a command to an OppoDevice""" code: OppoCodeType _parameters: List[str] _response_codes: List[str] def __init__(self, code: OppoCodeType, parameters: List[str] = No...
nilq/baby-python
python
from django.urls import path from rest_framework import routers from .views import * router = routers.DefaultRouter() router.register('notes', NoteViewSet, basename='notes') router.register('projects', ProjectViewSet, basename='projects') router.register('habits', HabitViewSet, basename='habits') urlpatterns = router...
nilq/baby-python
python
import torch.nn as nn import torch from Postional import PositionalEncoding class TransAm(nn.Module): def __init__(self, feature_size=200, num_layers=1, dropout=0.1): super(TransAm, self).__init__() self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalE...
nilq/baby-python
python
# just a package
nilq/baby-python
python
class Solution: def isPalindrome(self, x: int) -> bool: temp = str(x) length = len(temp) flag = 0 for i in range(0,length): if temp[i:i+1] != temp[length-1-i:length-i]: flag = 1 if flag == 1: return False else: retur...
nilq/baby-python
python
from django.contrib import admin from .models import Pokemon admin.site.register(Pokemon)
nilq/baby-python
python
#!/usr/local/bin/python3 #-*- encoding: utf-8 -*- from flask import Flask from flask_restx import Api from setting import config from app.api.client import worker_client def run(): app = Flask(__name__) api = Api( app, version='dev_0.1', title='Integrated Worker Server API', de...
nilq/baby-python
python
# ==============================CS-199================================== # FILE: MyAI.py # # AUTHOR: Vaibhav Yengul # # DESCRIPTION: This file contains the MyAI class. You will implement your # agent in this file. You will write the 'getAction' function, # the constructor, and...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import getopt import os.path sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) from datetime import datetime from TwitterEngine import instances, BackendChooser def parseargs(name, argv): date = datetime.now() execut...
nilq/baby-python
python
from django.contrib import admin from django.contrib.auth.decorators import login_required, permission_required from django.urls import path from . import views from .api import views as api_views app_name = 'main_app' urlpatterns = [ path('api/sites/', api_views.SitesListCreateAPIView.as_view(), name='sites_rest_...
nilq/baby-python
python
import numpy as np from features.DetectorDescriptorTemplate import DetectorDescriptorBundle from features.cv_sift import cv_sift class SiftDetectorDescriptorBundle(DetectorDescriptorBundle): def __init__(self, descriptor): sift = cv_sift() super(SiftDetectorDescriptorBundle, self).__init__(sift, d...
nilq/baby-python
python
import torch import torch.nn.functional as F import torch.nn as nn from transformers import BertModel # Convlution,MaxPooling層からの出力次元の算出用関数 def out_size(sequence_length, filter_size, padding = 0, dilation = 1, stride = 1): length = sequence_length + 2 * padding - dilation * (filter_size - 1) - 1 length...
nilq/baby-python
python
from pi import KafkaProducerClient class LogProducer(object): # TODO: Implement parallel processing producer = KafkaProducerClient() for idx in range(1000): data = { "res": { "body": { "success": False, "code": "INTERNAL_SERVER_ER...
nilq/baby-python
python
#!/usr/bin/env python import os, sys from typing import Union, List import pprint pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr) from google.protobuf.compiler import plugin_pb2 as plugin from google.protobuf.descriptor_pool import DescriptorPool from google.protobuf.descriptor import Descriptor, FieldDescrip...
nilq/baby-python
python
import json import os import toml # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CONFIG_FILE = 'config.toml' CONFIG_FILE_DIR = os.path.join(BASE_DIR, CONFIG_FILE) CONFIG_DATA = toml.load(CONFIG_FILE_DIR) # SECURITY WARNI...
nilq/baby-python
python
from location import GeoCoordinate, geo_to_cartesian import time class Value: def __init__(self, value, unit): self.value = value self.unit = unit class Measurement: def __init__(self, row): self.parameter = row["parameter"] self.value = Value(row["value"], row["unit"]) ...
nilq/baby-python
python
""" LC89. Gray Code The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0. Example 1: Input: 2 Output: [0,1,3,2] Explanation...
nilq/baby-python
python
"""The IPython HTML Notebook""" import os # Packagers: modify this line if you store the notebook static files elsewhere DEFAULT_STATIC_FILES_PATH = os.path.join(os.path.dirname(__file__), "static") del os from .nbextensions import install_nbextension
nilq/baby-python
python
import unittest import pytest from anchore_engine.db import Image, get_thread_scoped_session from anchore_engine.services.policy_engine.engine.tasks import ImageLoadTask from anchore_engine.services.policy_engine.engine.policy.gate import ExecutionContext from anchore_engine.services.policy_engine import _init_distro_m...
nilq/baby-python
python
#!/usr/bin/python import csv import pycurl import json def insertToElasticSearch(data): esData={'year' : data[0], 'week': data[1], 'state' : data[2], 'area': data[3], 'location' : data[4], 'totalCase' :...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2015 Metaswitch Networks # # 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 applicab...
nilq/baby-python
python
# vim: fdm=marker ''' author: Fabio Zanini date: 11/12/14 content: Get trees of haplotype alignments. ''' # Modules import os import argparse from operator import itemgetter, attrgetter import numpy as np from matplotlib import cm import matplotlib.pyplot as plt from Bio import Phylo from hivwholeseq.pati...
nilq/baby-python
python
#!/usr/bin/env python from csvkit.unicsv import UnicodeCSVReader, UnicodeCSVWriter class CSVKitReader(UnicodeCSVReader): """ A unicode-aware CSV reader with some additional features. """ pass class CSVKitWriter(UnicodeCSVWriter): """ A unicode-aware CSV writer with some additional features. ...
nilq/baby-python
python
#! /usr/bin/env python from tkinter import NoDefaultRoot, Tk, ttk, filedialog from _tkinter import getbusywaitinterval from tkinter.constants import * from math import sin, pi import base64, zlib, os ################################################################################ ICON = b'eJxjYGAEQgEBBiApwZDBzMAgxsDA...
nilq/baby-python
python
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import subprocess from typing import Tuple import torch try: torch.classes.load_library( f"{os.environ['CONDA_PREFIX']}/...
nilq/baby-python
python
from unittest.mock import patch from datetime import datetime import httpx import pytest from src.zever_local.inverter import ( Inverter, InverterData, ZeversolarError, ZeversolarTimeout, ) _registry_id = "EAB241277A36" _registry_key = "ZYXTBGERTXJLTSVS" _hardware_version = "M11" _software_version = ...
nilq/baby-python
python
""" Tests for the game class """ import unittest import numpy as np from nashpy.algorithms.vertex_enumeration import vertex_enumeration class TestVertexEnumeration(unittest.TestCase): """ Tests for the vertex enumeration algorithm """ def test_three_by_two_vertex_enumeration(self): A = np.a...
nilq/baby-python
python
#!/usr/bin/env python3 __author__ = "Will Kamp" __copyright__ = "Copyright 2013, Matrix Mariner Inc." __license__ = "BSD" __email__ = "will@mxmariner.com" __status__ = "Development" # "Prototype", "Development", or "Production" '''This is the wrapper program that ties it all together to complete this set of programs...
nilq/baby-python
python
import time import numpy as np import dolfin as df from finmag.energies import Demag from finmag.field import Field from finmag.util.meshes import sphere import matplotlib.pyplot as plt radius = 5.0 maxhs = [0.2, 0.4, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95, 1.0] unit_length = 1e-9 m_0 = (1, 0, 0) Ms = 1 H_ref = np.array(...
nilq/baby-python
python
from datetime import datetime, timezone from hamcrest.core.string_description import StringDescription from pytest import mark, raises from preacher.core.datetime import DatetimeWithFormat from preacher.core.verification.hamcrest import after, before ORIGIN = datetime(2019, 12, 15, 12, 34, 56, tzinfo=timezone.utc) ...
nilq/baby-python
python
#!/usr/bin/env python from setuptools import setup, find_packages import dbbackup def get_requirements(): return open('requirements.txt').read().splitlines() def get_test_requirements(): return open('requirements-tests.txt').read().splitlines() keywords = [ 'django', 'database', 'media', 'backup', ...
nilq/baby-python
python
from utils.rooster_utils import prediction, get_model, load_configurations, set_seed import torch import sys TARGET_SR = 44100 settings = load_configurations(mode="detector") if(settings == -1): print("Error: Failed while loading configurations") sys.exit() set_seed(settings["globals"]["seed"]) melspectrogra...
nilq/baby-python
python
# Given an integer array nums, find the contiguous # subarray (containing at least one number) which # has the largest sum and return its sum. # Example: # Input: [-2,1,-3,4,-1,2,1,-5,4], # Output: 6 # Explanation: [4,-1,2,1] has the largest sum = 6. # Follow up: # If you have figured out the O(n) solution, try c...
nilq/baby-python
python
from funcx_endpoint.endpoint.utils.config import Config from parsl.providers import LocalProvider config = Config( scaling_enabled=True, provider=LocalProvider( init_blocks=1, min_blocks=1, max_blocks=1, ), max_workers_per_node=2, funcx_service_address='https://api.funcx.org...
nilq/baby-python
python
import abc from numpy import ndarray class AbstractGAN(abc.ABC): def __init__(self, run_dir: str, outputs_dir: str, model_dir: str, generated_datasets_dir: str, resolution: int, channels: int, epochs: int, output_save_frequency: int, model_save_frequency: int, loss_save_frequenc...
nilq/baby-python
python
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import os from comnetsemu.cli import CLI, spawnXtermDocker from comnetsemu.net import Containernet, VNFManager from mininet.link import TCLink from mininet.log import info, setLogLevel from mininet.node import Controller, RemoteController if __name__ == "__main__": ...
nilq/baby-python
python
import streamlit as st import pandas as pd import joblib model = joblib.load('/content/drive/MyDrive/models/cc_foodrcmdns.pkl') df = pd.read_csv('dataset/indianfoodMAIN.csv') recp_name = st.selectbox("Select Recipe", df['recp_name'].values) st.write(recp_name) def findRcmdn(value): data = [] index = df[df['...
nilq/baby-python
python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn # Some utility functions def average_norm_clip(grad, clip_val): ''' Compute...
nilq/baby-python
python
import gc import numpy as np import pandas as pd from datetime import datetime from functools import partial import tensorflow as tf from sklearn import preprocessing from .. import utils from ..config import cfg from .base_model import BaseModel class Graph(): '''Container class for tf.Graph and associated variab...
nilq/baby-python
python
import cosypose import os import yaml from joblib import Memory from pathlib import Path import getpass import socket import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system') hostname = socket.gethostname() username = getpass.getuser() PROJECT_ROOT = Path(cosypose.__file__)....
nilq/baby-python
python
from django.contrib.auth.models import User from django.core import mail from django.test import TestCase from hc.api.models import Check from hc.test import BaseTestCase class LogoutTestCase(BaseTestCase): def test_it_logs_out_users(self): form = {'email': 'alice@example.org', 'password': 'password'} ...
nilq/baby-python
python
""" Human-explainable AI. This is the class and function reference of FACET for advanced model selection, inspection, and simulation. """ __version__ = "1.2.0" __logo__ = ( r""" _ ____ _ _ ___ __ ___ _____ _-´ _- / ___\ / \ /\ /\ /\ /\ / \ ...
nilq/baby-python
python
"""LiveSimulator: This class reads in various Bro IDS logs. The class utilizes the BroLogReader and simply loops over the static bro log file, replaying rows and changing any time stamps Args: eps (int): Events Per Second that the simulator will emit events (default...
nilq/baby-python
python
from unittest import TestCase from dynamic_fixtures.fixtures.basefixture import BaseFixture class BaseFixtureTestCase(TestCase): def test_load_not_implemented(self): """ Case: load is not implemented Expected: Error get raised """ fixture = BaseFixture("Name", "Module") ...
nilq/baby-python
python
from empregado import Empregado class Operario(Empregado): def __init__(self, nome, endereco, telefone, codigo_setor, salario_base, imposto, valor_producao, comissao): super().__init__(nome, endereco, telefone, codigo_setor, salario_base, imposto) self._valor_producao = valor_producao self...
nilq/baby-python
python
import inspect import typing from chia import instrumentation class Factory: name_to_class_mapping: typing.Optional[typing.Dict] = None default_section: typing.Optional[str] = None i_know_that_var_args_are_not_supported = False @classmethod def create(cls, config: dict, observers=(), **kwargs): ...
nilq/baby-python
python
from useintest.modules.consul.consul import ConsulServiceController, consul_service_controllers, \ Consul1_0_0ServiceController, Consul0_8_4ServiceController, ConsulDockerisedService
nilq/baby-python
python
import math # S1: A quick brown dog jumps over the lazy fox. # S2: A quick brown fox jumps over the lazy dog. # With the two sentences above I will implement the calculation based on calculation # values. def magnitude(v1): vResult = [abs(a * b) for a, b in zip(v1, v1)] mag = math.sqrt(sum(vResult, 0)) r...
nilq/baby-python
python
import time import asyncio from typing import List import threading import numpy as np import spotipy from spotipy.oauth2 import SpotifyOAuth from eventhook import EventHook class NotPlayingError(Exception): def __init__(self): self.message = "Spotify not playing" class MonitorConfig: def __init_...
nilq/baby-python
python
a, b = input().split() print("Yes" if (int(a + b) ** (1 / 2)).is_integer() else "No")
nilq/baby-python
python
# pip3 install PySocks import socks import socket from urllib import request from urllib.error import URLError socks.set_default_proxy(socks.SOCKS5, '127.0.0.1', 9742) socket.socket = socks.socksocket try: response = request.urlopen('http://httpbin.org/get') print(response.read().decode('utf-8')) except URLE...
nilq/baby-python
python
import torch from kondo import Spec from torchrl.experiments import BaseExperiment from torchrl.utils.storage import TransitionTupleDataset from torchrl.contrib.controllers import DDPGController class DDPGExperiment(BaseExperiment): def __init__(self, actor_lr=1e-4, critic_lr=1e-3, gamma=0.99, tau=1e...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from numap import NuMap def hello_world(element, *args, **kwargs): print "Hello element: %s " % element, print "Hello args: %s" % (args,), print "Hello kwargs: %s" % (kwargs,) return element ELEMENTS = ('element_0', 'element_1', 'element_2', 'element_3', '...
nilq/baby-python
python
import collections import itertools import json from pathlib import Path import re import sqlite3 import string import attr import nltk import numpy as np def clamp(value, abs_max): value = max(-abs_max, value) value = min(abs_max, value) return value def to_dict_with_sorted_values(d, key=None): re...
nilq/baby-python
python
# SPDX-FileCopyrightText: 2022 Eva Herrada for Adafruit Industries # SPDX-License-Identifier: MIT import board from kmk.kmk_keyboard import KMKKeyboard as _KMKKeyboard from kmk.matrix import DiodeOrientation class KMKKeyboard(_KMKKeyboard): row_pins = (board.D10, board.MOSI, board.MISO, board.D8) col_pins =...
nilq/baby-python
python
# -*- coding: utf-8 -*- counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print (counter) print (miles) print (name)
nilq/baby-python
python
from .tests import _index def main(): suites = _index.suites passes = 0 fails = 0 for s in suites: s.run() print(s) passes += s.passes fails += s.fails print(f'###################\nSUMMARY OF ALL TEST SUITES\nTotal Passing Tests: {passes}\nTotal Failing Tests: {fails...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: latin-1 -*- import os, subprocess import numpy as np import GenericUsefulScripts as GUS from astropy import units as u from astropy.io import ascii, fits from astropy.convolution import convolve from astropy.stats import SigmaClip from astropy.coordinates import SkyCoord from photutils....
nilq/baby-python
python
def model_to_dicts(Schema, model): # 如果是分页器返回,需要传入model.items common_schema = Schema(many=True) # 用已继承ma.ModelSchema类的自定制类生成序列化类 output = common_schema.dump(model) # 生成可序列化对象 return output
nilq/baby-python
python
"""OsservaPrezzi class for aio_osservaprezzi.""" from .const import ENDPOINT, REGIONS from .models import Station from .exceptions import ( RegionNotFoundException, StationsNotFoundException, OsservaPrezziConnectionError, OsservaPrezziException, ) from typing import Any import asyncio import aiohttp im...
nilq/baby-python
python
import telebot import os TOKEN = os.getenv('TELE_TOKEN') bot = telebot.TeleBot(TOKEN) @bot.message_handler(commands=['start']) def start_message(message): markup = telebot.types.ReplyKeyboardMarkup() # start_btn = telebot.types.KeyboardButton("/start") help_btn = telebot.types.KeyboardButton("/help") ...
nilq/baby-python
python
# [h] paint and arrange groups '''Paint each group of glyphs in the font with a different color.''' # debug import hTools2 reload(hTools2) if hTools2.DEBUG: import hTools2.modules.color reload(hTools2.modules.color) # import from hTools2.modules.color import paint_groups # run f = CurrentFont() paint_gr...
nilq/baby-python
python
""" 3->7->5->12->None """ class SinglyListNode(object): def __init__(self, value): self.value = value self.next = None a = SinglyListNode(3) b = SinglyListNode(7) c = SinglyListNode(5) d = SinglyListNode(12) a.next = b b.next = c c.next = d print(a.next) print(b) print(b.next) print(c) d...
nilq/baby-python
python
from __future__ import absolute_import, unicode_literals import logging from django.core.management.base import BaseCommand from housing_counselor.geocoder import BulkZipCodeGeocoder, GeocodedZipCodeCsv logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Geocode all possible zipcodes' ...
nilq/baby-python
python
""" Ejercicio 6 Escriba un programa que pida la fecha segun el formato 04/12/1973 y lo retome segun el formato 1973/12/04 """ from datetime import date from datetime import datetime fecha = str(input("Ingrese una fecha(formato dd/mm/aaaa): ")) fecha1 = datetime.strptime(fecha, "%d/%m/%Y") fecha3 = datetime.strftime(f...
nilq/baby-python
python
from .registries import Registry, meta_registry, QuerySet, Manager, MultipleObjectsReturned, DoesNotExist __version__ = "0.2.1"
nilq/baby-python
python
# Copyright 2019 The MACE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the tag_linux.txt tagging file.""" import unittest from plaso.containers import events from plaso.lib import definitions from plaso.parsers import bash_history from plaso.parsers import docker from plaso.parsers import dpkg from plaso.parsers import selinux ...
nilq/baby-python
python
__author__ = 'surya' # plot each IntegralInteraction S values and save a plot in the end for the respective plate def plot(file,nslen,slen): import matplotlib.pyplot as plt start=5 list=[] with open(file+"_IntegralIntensity.txt") as files: next(files) for lines in files: s...
nilq/baby-python
python
from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.postgres import fields as pgfields from django.contrib.auth.models import User # about user # h...
nilq/baby-python
python
import requests from bs4 import BeautifulSoup #define a founction that get text from a html page def gettext(url, kv=None): try: r = requests.get(url,headers = kv) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: print("Failure") #defi...
nilq/baby-python
python
"""\ wxDatePickerCtrl objects @copyright: 2002-2007 Alberto Griggio @copyright: 2014-2016 Carsten Grohmann @copyright: 2016 Dietmar Schwertberger @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY """ import wx from edit_windows import ManagedBase, EditStylesMixin from tree import Node import commo...
nilq/baby-python
python
from util.html import HTML import numpy as np import os import ntpath import time from . import util import matplotlib.pyplot as plt from util.util import load_validation_from_file, smooth_kernel, load_loss_from_file class Visualizer(): """This class includes several functions that can display/save images and prin...
nilq/baby-python
python
# Copyright 2009-2010 by Ka-Ping Yee # # 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 w...
nilq/baby-python
python
import pytest import NAME
nilq/baby-python
python
import os import numpy as np import joblib class proba_model_manager(): def __init__(self, static_data, params={}): if len(params)>0: self.params = params self.test = params['test'] self.test_dir = os.path.join(self.model_dir, 'test_' + str(self.test)) self.istra...
nilq/baby-python
python
"""Test the cli_data_download tool outputs.""" # TODO review and edit this import argparse from pathlib import Path from cmatools.cli_data_download import cli_data_download from cmatools.definitions import SRC_DIR DEBUG = True """bool: Debugging module-level constant (Default: True).""" # Define cli filepath CLI =...
nilq/baby-python
python
import sys, json from PIL import Image from parser.png_diff import PNG_DIFF from format.util import * def diff(file_before, file_after): """diff png file args: file_before (str) file_after (str) returns: png_diff (PNG_DIFF) """ png_before = Image.open(file_before) png_...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Check if the move of v can satisfied, makebetter, or notsatisfied from .FMConstrMgr import FMConstrMgr class FMBiConstrMgr(FMConstrMgr): def select_togo(self): """[summary] Returns: dtype: description """ return 0 if self.diff[0] < self.diff...
nilq/baby-python
python
from django.shortcuts import get_object_or_404, render from .models import Card, Group, Product def searching(request, keyword): products = Product.objects.filter(title__contains=keyword) return render(request, 'main/catalog.html', {'products': products, 'keyword': keyword}) def index(request): offers =...
nilq/baby-python
python
# # project-k Forth kernel in python # Use the same kernel code for all applications. # FigTaiwan H.C. Chen hcchen5600@gmail.com 21:14 2017-07-31 # import re, sys name = "peforth" vm = __import__(__name__) major_version = 1; # major version, peforth.py kernel version, integer. ip = 0; stack = [] ; rstack = []; voc...
nilq/baby-python
python
from wallet import Wallet wallet = Wallet() address = wallet.getnewaddress() print address
nilq/baby-python
python
from config.settings_base import * ##### EDIT BELOW API_KEY = "Paste your key in between these quotation marks"
nilq/baby-python
python
from rest_framework import serializers from .models import Homework class HomeworkStudentSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') course = serializers.ReadOnlyField(source='course.id') lecture = serializers.ReadOnlyField(source='lecture.id') g...
nilq/baby-python
python
#!/usr/bin/env python ''' Copyright (C) 2019, WAFW00F Developers. See the LICENSE file for copying permission. ''' NAME = 'Open-Resty Lua Nginx (FLOSS)' def is_waf(self): schema1 = [ self.matchHeader(('Server', r'^openresty/[0-9\.]+?')), self.matchStatus(403) ] schema2 = [ self.ma...
nilq/baby-python
python
from pypy.rlib import _rffi_stacklet as _c from pypy.rlib import objectmodel, debug from pypy.rpython.annlowlevel import llhelper from pypy.tool.staticmethods import StaticMethods class StackletGcRootFinder: __metaclass__ = StaticMethods def new(thrd, callback, arg): h = _c.new(thrd._thrd, llhelper(_...
nilq/baby-python
python
# coding: utf-8 from __future__ import unicode_literals import re from django import forms from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.utils.encoding import iri_to_uri, smart_text try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin _...
nilq/baby-python
python
from typing import List import torch import numpy as np # details about math operation in torch can be found in: http://pytorch.org/docs/torch.html#math-operations # convert numpy to tensor or vise versa np_data = np.arange(6).reshape((2, 3)) # reshape 重塑 把1X6矩阵变为2X3矩阵 # numpy.arange([start=0, ]stop, [step=1, ]dtype...
nilq/baby-python
python