content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from io import StringIO
from django.core.management import call_command
from django.db import connection
import pytest
# aliased, otherwise it's picked up as a test function by pytest
from ctrl_z.db_restore import test_migrations_table as check_migrations
@pytest.mark.django_db(databases=["secondary"])
def test_no... | nilq/baby-python | python |
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
# Python
import contextlib
import logging
import threading
import json
import sys
# Django
from django.db import connection
from django.conf import settings
from django.db.models.signals import (
pre_save,
post_save,
pre_delete,
post_delete,
... | nilq/baby-python | python |
# -*- encoding: utf-8 -*-
"""
hio.demo package
Demo applications that use hio
"""
| nilq/baby-python | python |
from django.utils import timezone
from rest_framework import serializers
from rest_framework.fields import CharField
from rest_framework.relations import PrimaryKeyRelatedField
from api.applications.enums import (
ApplicationExportType,
ApplicationExportLicenceOfficialType,
)
from api.applications.libraries.ge... | nilq/baby-python | python |
"""
This example illustrates how to send a request for the plan database from a system.
"""
import logging
import sys
import pyimc
from pyimc.actors.dynamic import DynamicActor
from pyimc.decorators import Periodic, Subscribe
class PlanActor(DynamicActor):
def __init__(self, target_name):
"""
In... | nilq/baby-python | python |
#!/usr/bin/env python2
# Example 1, iter over some names
def loop_names():
names = ["pichu", "pikachu", "raichu"]
for n in names:
print n
def name_gener():
yield "pichu"
yield "pikachu"
yield "raichu"
def gener_names():
for n in name_gener():
print n
loop_names()
gener_names(... | nilq/baby-python | python |
from output.models.nist_data.list_pkg.hex_binary.schema_instance.nistschema_sv_iv_list_hex_binary_max_length_4_xsd.nistschema_sv_iv_list_hex_binary_max_length_4 import NistschemaSvIvListHexBinaryMaxLength4
__all__ = [
"NistschemaSvIvListHexBinaryMaxLength4",
]
| nilq/baby-python | python |
import urllib
import os.path
import os
import shutil
import zipfile
import glob
from django.conf import settings
from eulexistdb import db
from datetime import date
thisyear = date.today().year
media_root = settings.MEDIA_ROOT
disa_pki_flag = settings.USE_DISA_PKI
root_src_dir = '/tmp/iavms/'
iavm_cve_data_dir = med... | nilq/baby-python | python |
import numpy as np
from glob import glob
from tqdm import tqdm
from chemprop.features import load_features
from chemprop.data.scaler import StandardScaler
def get_dist(dirpath):
mean = list()
std = list()
count = list()
# Get mean and standard deviation of all the features across all the files
f... | nilq/baby-python | python |
from datetime import datetime
import json
from django.conf import settings
def handle(context, err):
print("ERROR:", err)
with open(getattr(settings, "SCRAPE_LOG"), "a+") as log:
log.write(str(datetime.now()) + " Error: " + str(err) + "\n")
log.write("Context: " + json.dumps(context, indent=4)... | nilq/baby-python | python |
from django.conf.urls import url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='website/home.html'), name='home'),
url(r'^about/$', TemplateView.as_view(template_name='website/about.html'), name='about')
] | nilq/baby-python | python |
import numpy as np
import pickle
import json
from keras.utils import Sequence
from collections import Counter
from PIL import Image, ImageDraw
import random
import skimage.io as io
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import os
from keras.preprocessing.image import load_img
from Environme... | nilq/baby-python | python |
# Test name = KidProfile_2
# Script dir = R:\Stingray\Tests\KidProfile_2\functionality\functionality.py
# Rev v.2.0
from time import sleep
from device import handler, updateTestResult
import RC
import UART
import DO
import GRAB
import MOD
import os
from DO import status
import OPER
def runTest():
status("active... | nilq/baby-python | python |
# coding=utf-8
import unittest
from pyprobe.sensors.pegasus.sensor_phy_drive import PegasusPhysicalDriveSensor
__author__ = 'Dirk Dittert'
class PegasusDriveSensorTest(unittest.TestCase):
def test_no_drive_should_throw(self):
subject = PegasusPhysicalDriveSensor()
with self.assertRaises(ValueErr... | nilq/baby-python | python |
class Event(list):
def __call__(self, *args, **kwargs):
for item in self:
item(*args, **kwargs)
class Game:
def __init__(self):
self.events = Event()
def fire(self, args):
self.events(args)
class GoalScoredInfo:
def __init__(self, who_scored, goals... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2019 Richard Sanger, Wand Network Research Group
#
# 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 ... | nilq/baby-python | python |
import re
from random import sample
from django.db.models import Avg
from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import *
from .serializers import *
import requests
from bs4 import Beauti... | nilq/baby-python | python |
import os
import platform
import sys
from datetime import datetime, timezone
from pathlib import Path
from unittest.mock import MagicMock, Mock
import pytest
import tzlocal.unix
import tzlocal.utils
if sys.version_info >= (3, 9):
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
else:
from backports.zonei... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
import pandas as pd
import csv
import os
import argparse
def get_valid_query(data_path, data_name):
print('begin getting valid query')
valid_path=os.path.join(os.path.join(data_path,'valid'),'valid.tsv')
valid_data=pd.read_csv(valid_path, sep='\t')
filename =os.path.join(os.pat... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 5 10:15:25 2021
@author: lenakilian
"""
import pandas as pd
data_directory = "/Users/lenakilian/Documents/Ausbildung/UoLeeds/PhD/Analysis"
output_directory = "/Users/lenakilian/Documents/Ausbildung/UoLeeds/PhD/Analysis/Spatial_Emissions"
lookup ... | nilq/baby-python | python |
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Layer, Dense, Input, Conv1D, Flatten, Dot, RepeatVector, Concatenate, Permute, Add, Multiply
from tensorflow.keras import activations, initializers, regularizers, constraints
from tensorflow.keras.optimizers import Adam
cla... | nilq/baby-python | python |
from floodsystem.plot import plot_water_levels
from floodsystem.stationdata import build_station_list
from floodsystem.analysis import update_water_levels
from floodsystem.flood import stations_highest_rel_level
from floodsystem.datafetcher import fetch_measure_levels
import datetime
def run2e(station, dates, levels):... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# CODE NAME HERE
# CODE DESCRIPTION HERE
Created on 2019-02-04 at 16:40
@author: cook
"""
import numpy as np
import argparse
import sys
import os
import copy
from collections import OrderedDict
from apero.core.instruments.default import pseudo_const
from apero.core ... | nilq/baby-python | python |
import unittest,json
from tqdm import tqdm
from mtgcompiler.parsers.JsonParser import JsonParser
from multiprocessing import Pool
def loadAllSets(fname="tests/parsing/AllSets.json"):
with open(fname) as f:
data = json.load(f)
return data
totalCardsParsed = 0
totalCardsAttempted... | nilq/baby-python | python |
from django.urls import path
from .views import UserReactionView, CommentsLikeReactionAPIView
from .models import UserReaction
from authors.apps.articles.models import Article
from authors.apps.comments.models import Comment
app_name = 'user_reactions'
urlpatterns = [
path('articles/<slug>/like', UserReactionVie... | nilq/baby-python | python |
"""
A plugin that retrieves file paths from backend server.
This module implements a plugin for preview-server that allows preview-server
to proxy requests to a backend server.
Preview requests are received by preview-server, the path is given within the
URL. In order to locate the file on disk, this plugin will make... | nilq/baby-python | python |
"""`main` is the top level module for your Flask application."""
# Import the Flask Framework
from flask import Flask
from flask import render_template,request,send_from_directory
from flask_misaka import Misaka
import ctftools
app = Flask(__name__)
Misaka(app,fenced_code=True)
# Note: We don't need to call run() since... | nilq/baby-python | python |
import torch
import torch.optim as optim
from torch import autograd
import numpy as np
from tqdm import trange
import trimesh
import cv2
from im2mesh.ptf import models
from im2mesh.utils import libmcubes
from im2mesh.common import make_3d_grid
from im2mesh.utils.libsimplify import simplify_mesh
from im2mesh.utils.libmi... | nilq/baby-python | python |
"""This module contains the utilities for the Translations app."""
from django.db import models
from django.db.models.query import prefetch_related_objects
from django.db.models.constants import LOOKUP_SEP
from django.core.exceptions import FieldError
from django.contrib.contenttypes.models import ContentType
import ... | nilq/baby-python | python |
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
def make_rule(line):
""" Object Maker Function """
rule = Rule(line)
return rule
class Rule(object):
""" Used to organize intake from custom_rule config """
valid = False
resourceType = ... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
from pyjunix import (PyJKeys, PyJArray, PyJUnArray, PyJLs, PyJGrep, PyJPrtPrn,
PyJSort, PyJLast, PyJPs, PyJJoin, PyJPaste, PyJCat, PyJSplit,
PyJDiff, PyJUniq)
script_dir = {
"pyjkeys": PyJKeys,
"pyjarray": PyJArra... | nilq/baby-python | python |
with open("words.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for line in lines:
# print ('line is', line)
if len(line) == 6:
f.write(f"'{line}',")
f.truncate() | nilq/baby-python | python |
#!/bin/python
import os, shutil
import numpy as np
import matplotlib.pyplot as plt
import np_helper as nph
# plot 3d points
def plot_pts3d(pts3d, visible_status):
fig_xz = plt.figure()
plt.xlabel('X (m)', fontsize=14)
plt.ylabel('Z (m)', fontsize=14)
plt.axis('equal')
plt.plot(pts3d[0,:], pts3d[2... | nilq/baby-python | python |
from django.conf.urls import url
from . import views
urlpatterns = [
# 购物车 carts
url(r'^carts/$', views.CartsView.as_view(),name='info'),
# 全选购物车/carts/selection/
url(r'^carts/selection/$', views.CartsSelectAllView.as_view(), name='carts_select'),
# 页面简单购物车 /carts/simple/
url(r'^carts/simple/$... | nilq/baby-python | python |
import torch
import torch.nn as nn
from torchvision.models.resnet import resnet50
class Resnet50Extractor(nn.Module):
def __init__(self, representation_size=128):
super().__init__()
original_model = resnet50(pretrained=True, progress=True)
in_features = 1000
self.model = nn.Sequen... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
djcorecap/core
---------------
core module for the djcorecap app
'''
from bokeh.embed import components
from bokeh.plotting import figure
from bokeh.resources import CDN
def bokeh_plot(data, plots, f_config={}, p_config=[]):
'''
create HTML elements for a Bokeh plot
:retur... | nilq/baby-python | python |
from aiocqhttp import Event
from datasource import get_360_boardcast
from .base_bot import BaseBot
class Rss(BaseBot):
def __init__(self):
super()
super().__init__()
def reset_bot(self):
pass
def match(self, event: Event, message: str) -> bool:
if not self.has_at_bot(eve... | nilq/baby-python | python |
""" unit test """
import difflib
import inspect
import json
import logging
import os
import sys
import tempfile
from io import StringIO
from logging import Handler
from random import random
from unittest.case import TestCase
from bzt.cli import CLI
from bzt.engine import SelfDiagnosable
from bzt.modules.aggregator imp... | nilq/baby-python | python |
from magicbot import StateMachine, state, timed_state
from components.climb import Climber
from components.cargo import CargoManipulator, Height
from pyswervedrive.chassis import SwerveChassis
class ClimbAutomation(StateMachine):
chassis: SwerveChassis
climber: Climber
cargo_component: CargoManipulator
... | nilq/baby-python | python |
#The MIT License (MIT)
#
#Copyright (c) 2015 Jiakai Lian
#
#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, mer... | nilq/baby-python | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------------... | nilq/baby-python | python |
import threading
import time
import RPi.GPIO as GPIO
class ContactSwitchRecognizer(threading.Thread):
GPIO_PIN = 21
_contact_switch_listener = None
_last_state_on = False
def __init__(self, contact_switch_listener):
threading.Thread.__init__(self)
GPIO.setmode(GPIO.BCM)
GPIO... | nilq/baby-python | python |
# -*- coding:UTF-8 -*-
import rdkit
import rdkit.Chem as Chem
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
from collections import defaultdict
from rdkit.Chem.EnumerateStereoisomers import EnumerateStereoisomers, StereoEnumerationOptions
import logging
MST_MAX_WEIGHT = 100... | nilq/baby-python | python |
#!/usr/bin/env python3
import rospy
from std_msgs.msg import Int32
import rogata_library as rgt
import numpy as np
def visibility(guard,thief,wall_objects,max_seeing_distance):
distance = np.linalg.norm(thief-guard)
direction = (thief-guard)/distance
direction = np.arctan2(direction[1],direction[0])
... | nilq/baby-python | python |
# coding=utf-8
from model import Balance, Label, Transfer, Internal
# 保存数据库类
class Save:
def __init__(self):
...
# 保存balance
@staticmethod
def save_balance(address, balance) -> None:
balance = Balance(address, balance)
balance.save()
return
# 保存label
@staticm... | nilq/baby-python | python |
import numpy
numpy.set_printoptions(sign=' ')
arr = numpy.array([*map(float, input().split())])
print(numpy.floor(arr), numpy.ceil(arr), numpy.rint(arr), sep='\n')
| nilq/baby-python | python |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from _cffi_src.utils import build_ffi_for_binding
ffi = build_... | nilq/baby-python | python |
"""
Created on Aug 28, 2017
@author: ionut
"""
import json
import logging
import subprocess
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler
from tornado.escape import url_escape
import utils
class BaseHandler(RequestHandler):
"""
Base handler returning 400 for both G... | nilq/baby-python | python |
"""\
Code generator functions for wxFrame objects
@copyright: 2002-2007 Alberto Griggio
@copyright: 2014-2016 Carsten Grohmann
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
import common
import wcodegen
class LispFrameCodeGenerator(wcodegen.LispWidgetCodeWriter):
def get_code(self, ... | nilq/baby-python | python |
import numpy as np
from math import *
import os
import time
import sys
import argparse
from monty.serialization import loadfn
"""
This module implements a core class LatticeConstant that support
lammps data/imput/log files i/o for calculating equilibrium lattice
constant of Re .
"""
__author__ = "Lu Jiang and Tingzh... | nilq/baby-python | python |
import unittest
from kafka.tools.protocol.requests import ArgumentError
from kafka.tools.protocol.requests.offset_commit_v2 import OffsetCommitV2Request
class OffsetCommitV2RequestTests(unittest.TestCase):
def test_process_arguments(self):
val = OffsetCommitV2Request.process_arguments(['groupname', '16',... | nilq/baby-python | python |
from typing import Any, Dict, List, Type, TypeVar
import attr
from ..models.label_count import LabelCount
T = TypeVar("T", bound="CategoriesFacets")
@attr.s(auto_attribs=True)
class CategoriesFacets:
""" """
labels: List[LabelCount]
def to_dict(self) -> Dict[str, Any]:
labels = []
for... | nilq/baby-python | python |
from pin_hcsr04 import HCSR04
import time
measure = HCSR04(trigger = 'X8', echo = 'X7')
while True:
print("%.1f cm" % (measure.distance_mm() / 10))
time.sleep(1)
| nilq/baby-python | python |
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import *
import bcrypt
# ------------------------ Unprotected pages ------------------------
# ------ Main Landing Page ------
def index(request):
if 'user_id' not in request.session:
return render(request, 'ind... | nilq/baby-python | python |
#
# Copyright (c) 2015 CNRS
#
from math import atan2, pi, sqrt
import numpy as np
from . import libpinocchio_pywrap as pin
def npToTTuple(M):
L = M.tolist()
for i in range(len(L)):
L[i] = tuple(L[i])
return tuple(L)
def npToTuple(M):
if M.shape[0] == 1:
return tuple(M.tolist()[0])... | nilq/baby-python | python |
from django import template
import calendar
from django.template import loader, Context
from django.utils.dates import WEEKDAYS, WEEKDAYS_ABBR
from django.template.loader import render_to_string
weekday_names = []
weekday_abbrs = []
# The calendar week starts on Sunday, not Monday
weekday_names.append(WEEKDAYS[6])
w... | nilq/baby-python | python |
# Copyright 2021 Tony Wu +https://github.com/tonywu7/
#
# 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 ... | nilq/baby-python | python |
import pickle
import nltk
class Classifier:
def __init__(self):
with open('/home/ubuntu/backend/scraped_data_classifier', 'rb') as handle:
self.classifier = pickle.load(handle)
def classify(self, name):
return self.classifier.classify(self.feature_extraction(name))
def featur... | nilq/baby-python | python |
from django.urls import reverse
from rest_framework import status
from .test_setup import TestApiEndpoints
class TestOperator(TestApiEndpoints):
fixtures = ['Operator', 'Address', 'Authorization', 'Activity']
def test_operator_list_returns_200(self):
self.setUpClientCredentials([self.READ_SCOPE])
... | nilq/baby-python | python |
import pandas
from bart.bart import Fares, get_stations
def get_fare_table():
stations_abbr = [s.abbr for s in get_stations()]
station_pairs = []
for o in stations_abbr:
for d in stations_abbr:
if o != d:
station_pairs.append((o, d))
fares = Fares()
fares.get_f... | nilq/baby-python | python |
from tqdm import tqdm
import numpy as np
import os
from pathlib import Path
# this script is to be run in an environment with the Python bindings of elsa installed
import pyelsa as elsa
def generate_sparse_npy_images(src_dir, out_dir=None, num_angles=50, no_iterations=20, limit=None):
"""
Generate sparsely s... | nilq/baby-python | python |
#!/usr/bin/env python3
#
# fix field names using the provide schema
#
import os
import sys
import re
import csv
import json
input_path = sys.argv[1]
output_path = sys.argv[2]
schema_path = sys.argv[3]
schema = json.load(open(schema_path))
fields = {field["name"]: field for field in schema["fields"]}
fieldnames = [... | nilq/baby-python | python |
import pytest
from stve.log import Log
from aliez.utility import *
from aliez.script.kancolle import testcase_kancolle
L = Log.get(__name__)
def info(string, cr=True):
desc(string, L, cr)
class TestCase(testcase_kancolle.TestCase):
def __init__(self, *args, **kwargs):
super(TestCase, self).__init__(... | nilq/baby-python | python |
from .mae_vit_base_patch16 import model
model.patch_size = 14
model.embed_dim = 1280
model.depth = 32
model.num_heads = 16
| nilq/baby-python | python |
"""
MIT License
Copyright (c) 2020 Mahdi S. Hosseini
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, mer... | nilq/baby-python | python |
"""
=========================================================================
DORYCMeshRouteUnitRTL.py
=========================================================================
A DOR-Y route unit with val/rdy interface for CMesh.
Author : Yanghui Ou, Cheng Tan
Date : Mar 25, 2019
"""
from pymtl3 import *
from pymtl3... | nilq/baby-python | python |
# DATA
data = []
with open("Data - Day09.txt") as file:
for line in file:
data.append(int(line.strip()))
# GOAL 1
"""
Find the first number in the list (after the preamble) which is not the sum of two of the 25 numbers before it.
What is the first number that does not have this property?
"""
def check_... | nilq/baby-python | python |
from typing import Dict
from torch import Tensor, nn
from ...general import PosEngFrc
class SD(nn.Module):
def __init__(self, evl: nn.Module, lmd: Tensor):
super().__init__()
self.lmd = lmd
self.evl = evl
def forward(self, pef: PosEngFrc, env: Dict[str, Tensor], flt: Tensor,
... | nilq/baby-python | python |
from flask import Flask
import redis
import json
from ...service.entity.author import Author
from ...exception.exception import AuthorAlreadyExistsException
app = Flask(__name__)
AUTHOR_COUNTER = "author_counter"
AUTHOR_ID_PREFIX = "author_"
class AuthorRepository:
def __init__(self):
self.db = redis.R... | nilq/baby-python | python |
# Copyright The PyTorch Lightning team.
#
# 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 i... | nilq/baby-python | python |
def load_ctrlsum(device):
from transformers import AutoModelForSeq2SeqLM, PreTrainedTokenizerFast
model = AutoModelForSeq2SeqLM.from_pretrained("hyunwoongko/ctrlsum-cnndm")
tokenizer = PreTrainedTokenizerFast.from_pretrained("hyunwoongko/ctrlsum-cnndm")
return tokenizer, model
import os, json
import a... | nilq/baby-python | python |
# Python3 function to calculate number of possible stairs arrangements with given number of boxes/bricks
def solution(n):
dp=[[0 for x in range(n + 5)]
for y in range(n + 5)]
for i in range(n+1):
for j in range (n+1):
dp[i][j]=0
dp[3][2]=1
dp[4][2]=1
for i in range(5... | nilq/baby-python | python |
from typing import Union, Optional, Dict
from .core.base import *
from .core.Framebuffer2D import Framebuffer2D
from .core.Texture2D import Texture2D
from .ScreenQuad import ScreenQuad
from .RenderGraph import RenderGraph
from .RenderSettings import RenderSettings
from .RenderNode import RenderNode
from tests.util imp... | nilq/baby-python | python |
'''
Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 ≤ i ≤ j < n.
Follow up: Could you do this in O(n) runtime?
Example 1:
Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.
Example 2:
Input: nums = [0]
Output: 0
Example 3:
Input: nums =... | nilq/baby-python | python |
"""bis URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... | nilq/baby-python | python |
Desc = cellDescClass("CLKBUFX16")
Desc.properties["cell_leakage_power"] = "5029.443900"
Desc.properties["cell_footprint"] = "clkbuf"
Desc.properties["area"] = "63.201600"
Desc.pinOrder = ['A', 'Y']
Desc.add_arc("A","Y","combi")
Desc.set_job("buf") # A
Desc.add_param("area",63.201600);
Desc.add_pin("A","input")
Desc.add... | nilq/baby-python | python |
{
"targets": [{
"target_name": "jimp-native",
"cflags": ["-fexceptions"],
"cflags!": [ "-fno-exceptions" ],
"cflags_cc": [ "-std=c++17", "-fexceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
'defines': ['_HAS_EXCEPTIONS=1'],
"sources": [
"<!@(node... | nilq/baby-python | python |
#!/usr/bin/python3
import matplotlib.pyplot as plt
import logging
import math
from tgblib import util
from tgblib.data import get_data, get_data_ul
logging.getLogger().setLevel(logging.INFO)
if __name__ == '__main__':
util.set_my_fonts(mode='talk')
show = False
label = 'std'
NU_TITLE = {
... | nilq/baby-python | python |
def mandel(x, y, max_iters, value):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
i = 0
c = complex(x,y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
def get_list(path):
j=0
f = open('cemianTrain.txt','w')
for i in os.listdir(path):
print(i)
f.write(os.path.join('/',i))
j+=1
if j%2 == 0:
f.write('\n')
else:
f.write(' ')
... | nilq/baby-python | python |
from core import RunBossSpider
from data.tool.handler import HandlerData
from flask import Flask
def run_proxy():
pass
def run_web():
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello World'
app.run()
def main():
# 开启爬虫
boss_spi = RunBossSpider()
boss_spi.r... | nilq/baby-python | python |
import csv
from django.db.models import Q
from django.http import HttpResponse
from django.template import Context, loader
from django.template.loader import get_template
from pymedtermino.umls import *
from weasyprint import HTML
from modules.cnmb.models import Physic
from modules.cnmb.utils.dto import CnmbDto
from ... | nilq/baby-python | python |
from setuptools import setup, find_packages
version = '1.0.0'
setup(
name="alerta-query",
version=version,
description='Alerta Generic Webhook by query parameters',
url='https://github.com/alerta/alerta-contrib',
license='MIT',
author='Pablo Villaverde',
author_email='pvillaverdecastro@gma... | nilq/baby-python | python |
import requests
from bs4 import BeautifulSoup
import re
from datetime import datetime
from base_bank import BankBase
import unicodedata
class Bank(BankBase):
def __init__(self):
BankBase.__init__(self)
self._bank_session = requests.Session()
self._base_url = 'https://online.bbt.com'
... | nilq/baby-python | python |
from btchippython.btchip.bitcoinTransaction import bitcoinTransaction
from btchippython.btchip.btchip import btchip
from electrum_clone.electrumravencoin.electrum.transaction import Transaction
from electrum_clone.electrumravencoin.electrum.util import bfh
from electrum_clone.electrumravencoin.electrum.ravencoin import... | nilq/baby-python | python |
#!/usr/bin/env python3
# python 3.5 without f strings
import argparse
import os, shutil, sys
import uuid
import itertools
from glob import glob
from snakemake.shell import shell
from snakemake.io import glob_wildcards
from multiprocessing import Pool
def predict_genes(genome,fasta,out_dir,log):
fna = "{}/{}.fn... | nilq/baby-python | python |
"""The genome to be evolved."""
import random
import logging
import hashlib
import copy
from train import train_and_score
from train import trainsimulation
class Genome():
"""
Represents one genome and all relevant utility functions (add, mutate, etc.).
"""
def __init__( self, all_possible_genes = N... | nilq/baby-python | python |
#!/usr/bin/python
import pickle
import numpy
numpy.random.seed(42)
### The words (features) and authors (labels), already largely processed.
### These files should have been created from the previous (Lesson 10)
### mini-project.
words_file = "../text_learning/your_word_data.pkl"
authors_file = "../text_learning/yo... | nilq/baby-python | python |
#!/usr/bin/env python3
from PIL import Image
import requests
from io import BytesIO
import base64
import os
import sys
from Crypto.Cipher import AES
from colorama import *
import random
import json
import mysql.connector
from cmd import Cmd
import hashlib
import time
# these dicts are how we manage options settings f... | nilq/baby-python | python |
"""
Assignment
1 create 5 variable for each data type
2 create 5 list variable with 3 elements like name,address,contact number
"""
# Int Data
a = 5
print(a)
b = 3
print(b)
c = 8
print(c)
d = 7
print(d)
e = 6
print(e)
# Float Data
a = 0.5
print(a)
b = 3.9
print(b)
c = 8.4
print(c)
d = 7.2
print(d)
e = 6.9
print(e)... | nilq/baby-python | python |
dia=int(input("quantos dia alugados"))
km=float(input("quantos km rodado"))
pago=(dia*60)+(km*0.15)
print("o total a pagar e de R${:.2f}".format(pago)) | nilq/baby-python | python |
""" Base class for records. """
from abc import ABCMeta, abstractmethod
from .utils import set_encoded
class InserterRegistry(object):
""" Registry of inserters. """
def __init__(self):
self._inserters = []
self._register_inserters()
def _register_inserters(self):
""" Register ... | nilq/baby-python | python |
import torch
import numpy as np
from torch.nn import functional as F
def create_uv(width, height):
uv = np.flip(np.mgrid[height[0]:height[1], width[0]:width[1]].astype(np.int32), axis=0).copy()
return uv.reshape((2, -1)).T
def create_perpendicular_vectors_vectorized(normals): # Nx3 tensor
def handle_z... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
import IPython
from mm2d.model import ThreeInputModel
# model parameters
# link lengths
L1 = 1
L2 = 1
# input bounds
LB = -1
UB = 1
def pseudoinverse(J):
JJT = J.dot(J.T)
return J.T.dot(np.linalg.inv(JJT))
def weighted_ps(D, J):
A = np.diag(D)
r... | nilq/baby-python | python |
import unittest
from bitmovin import Bitmovin
from tests.utils import get_settings
class BitmovinTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
def setUp(self):
super().setUp()... | nilq/baby-python | python |
import numpy as np
from typing import Dict
from mlagents.torch_utils import torch
from mlagents.trainers.buffer import AgentBuffer
from mlagents.trainers.torch.components.reward_providers.base_reward_provider import (
BaseRewardProvider,
)
from mlagents.trainers.settings import RNDSettings
from mlagents_envs.base... | nilq/baby-python | python |
from django.contrib import admin
from .models import Author, Category, Article, Comment
# Register your models here.
class AuthorModel(admin.ModelAdmin):
list_display = ["__str__"]
search_fields = ["__str__", "details"]
class Meta:
Model = Author
admin.site.register(Author, AuthorModel)
clas... | nilq/baby-python | python |
# Copyright 2019 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 |
"""tipo_hilo_cuerda
Revision ID: 014
Revises: 013
Create Date: 2014-05-28 07:36:03.329028
"""
# revision identifiers, used by Alembic.
revision = '014'
down_revision = '013'
import inspect
import imp
import os
from alembic import op
def upgrade():
utils_path = os.path.join(os.path.dirname(os.path.abspath(inspe... | nilq/baby-python | python |
'''
This file contains functions that help calculate the score and check word
validity in the game.
'''
####################################
# Global Variables
####################################
WORDLENGTH = 4
####################################
# Cows and Bulls Counter
####################################
def r... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.