content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from .forms import UserProfileForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Profile
def display_login(request):
context = {}
ret... | nilq/baby-python | python |
import tensorflow as tf
import numpy as np
import os
from scipy.io import loadmat
from epi.util import dbg_check
import matplotlib.pyplot as plt
# import tensorflow_probability as tfp
FANO_EPS = 1e-6
neuron_inds = {"E": 0, "P": 1, "S": 2, "V": 3}
def load_SSSN_variable(v, ind=0):
# npzfile = np.load("data/V1_Zs... | nilq/baby-python | python |
from schematics.types import ModelType, StringType, PolyModelType, FloatType, DateTimeType
from spaceone.inventory.model.sqldatabase.data import Database
from spaceone.inventory.libs.schema.metadata.dynamic_field import TextDyField, DateTimeDyField, EnumDyField, \
ListDyField
from spaceone.inventory.libs.schema.me... | nilq/baby-python | python |
"""Adam Integer Check"""
def prime_adam_check(number: int) -> bool:
"""
Check if a number is Adam Integer.
A number is Adam if the square of the number and square
of the reverse of the number are reverse of each other.
Example : 11 (11^2 and 11^2 are reverse of each other).
"""
# Get the... | nilq/baby-python | python |
import re
import urllib2
import urllib
import urlparse
import socket
# sniff for python2.x / python3k compatibility "fixes'
try:
basestring = basestring
except NameError:
# 'basestring' is undefined, must be python3k
basestring = str
try:
next = next
except NameError:
# builtin next function doesn... | nilq/baby-python | python |
class SPI(object):
def __init__(self, clk, MOSI=None, MISO=None):
self.clk = clk
self.MOSI = MOSI
self.MISO = MISO
| nilq/baby-python | python |
from core.entity.entity_exceptions import EntityOperationNotPermitted, EntityNotFoundException
from core.test.media_files_test_case import MediaFilesTestCase
class BaseTestClass(MediaFilesTestCase):
"""
provides the base class for all test cases
_check_default_fields and _check_default_change must be re-... | nilq/baby-python | python |
import numpy as np
import torch
from .mask_gen import BoxMaskGenerator
class CutmixCollateWrapper(object):
def __init__(self, batch_aug_fn=None):
self.batch_aug_fn = batch_aug_fn
self.mask_generator = BoxMaskGenerator(
prop_range = (0.25, 0.5),
n_boxes = 3,
rand... | nilq/baby-python | python |
"""
# BEGIN BINGO_DEMO
>>> bingo = BingoCage(range(3))
>>> bingo()
2
>>> bingo()
0
>>> callable(bingo)
True
# END BINGO_DEMO
"""
# BEGIN BINGO
import random
class BingoCage:
def __init__(self, items):
self._items = list(items) # <1>
random.shuffle(self._items) # <2>
def __call__(self):
... | nilq/baby-python | python |
from json import dumps
class Node:
def __init__(self, line = 0, column = 0):
self.line = line
self.column = column
@property
def clsname(self):
return str(self.__class__.__name__)
def to_tuple(self):
return tuple([
("node_class_name", self.clsname)
... | nilq/baby-python | python |
from ckan.common import config
def get_ytp_recommendation_recaptcha_sitekey():
return config.get('ckanext.ytp_recommendation.recaptcha_sitekey')
| nilq/baby-python | python |
# The MIT License(MIT)
# Copyright (c) 2013-2014 Matt Thomson
# 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, mo... | nilq/baby-python | python |
import itertools
a = input()
s = input().split()
n = int(input())
L = list(itertools.combinations(s, n))
f = filter(lambda x: 'a' in x, L)
print("{:.4f}".format(len(list(f))/len(L)))
| nilq/baby-python | python |
from django.conf.urls import include, url
urlpatterns = [
# browsable REST API
url(r'^api/', include('osmaxx.rest_api.urls')),
url(r'^version/', include('osmaxx.version.urls', namespace='version')),
]
| nilq/baby-python | python |
"""
Copyright MIT and Harvey Mudd College
MIT License
Summer 2020
Lab 1 - Driving in Shapes
"""
########################################################################################
# Imports
########################################################################################
import sys
sys.path.insert(1, ".... | nilq/baby-python | python |
import pyOcean_cpu as ocean
a = ocean.zeros([5,5])
a[1,...,3] = 99
print(a)
| nilq/baby-python | python |
import sqlite3
import pandas as pd
from .. import CONFIG
import datetime
from ..scrape.utils import PROPER_DATE_FORMAT
class DB_Query():
def __init__(self, column_names, rows):
self.column_names = column_names
self.rows = rows
def to_df(self):
return pd.DataFrame(self.rows, columns=s... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
This is the player application called by remctl or
through SSH; it is the replacement for the Perl command
'acoustics' and provides the same functionality.
"""
import sys
import os
import importlib
sys.path.append(os.path.dirname(sys.argv[0]) + '/lib')
from amp import db, config
if __na... | nilq/baby-python | python |
import argparse
import yaml
import os
import anndata as ad
from morphelia.preprocessing import *
from morphelia.features import *
def run(inp):
"""Preprocess morphological annotated data."""
# where to save figures
figdir = os.path.join(inp['output'], './figures/')
# load data
inp_data = os.path.... | nilq/baby-python | python |
"""Encoder definition for transformer-transducer models."""
import torch
from espnet.nets.pytorch_backend.transducer.blocks import build_blocks
from espnet.nets.pytorch_backend.transducer.vgg2l import VGG2L
from espnet.nets.pytorch_backend.transformer.layer_norm import LayerNorm
from espnet.nets.pytorch_backend.tran... | nilq/baby-python | python |
import gym
import quadruped_gym.gym # noqa: F401
def test_reset():
env = gym.make('A1BulletGymEnv-v0')
observation = env.reset()
assert observation in env.observation_space
def test_step():
env = gym.make('A1BulletGymEnv-v0')
env.reset()
for _ in range(10):
env.step(env.action_spac... | nilq/baby-python | python |
import numpy as np
if __name__=="__main__":
N=list(map(int,input().split()))
print(np.zeros(N,int))
print(np.ones(N,int)) | nilq/baby-python | python |
from jivago.jivago_application import JivagoApplication
from jivago.wsgi.annotations import Resource
from jivago.wsgi.methods import GET
@Resource("/")
class HelloResource(object):
@GET
def get_hello(self) -> str:
return "Hello World!"
app = JivagoApplication()
if __name__ == '__main__':
app.r... | nilq/baby-python | python |
import pandas
from matplotlib import pyplot
df = pandas.DataFrame([431-106,106])
df = df.transpose()
df.columns=['complete','incomplete']
df.plot(kind='bar', stacked=True, legend=False)
pyplot.show()
| nilq/baby-python | python |
from typing import Tuple, Union, List, Optional
from sectionproperties.pre import sections
import numpy as np
import shapely
def create_line_segment(
point_on_line: Union[Tuple[float, float], np.ndarray],
vector: np.ndarray,
bounds: tuple,
):
"""
Return a LineString of a line that contains 'point... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
class Config(object):
def __init__(self, config_path):
config_path = Config.validate_path(config_path)
self.config_path = config_path
self._config = Config.validate_format_and_parse(config_path)
def __getitem__(self, key):
return self._config.get(key)
... | nilq/baby-python | python |
from django.conf.urls import include, url
from django.contrib import admin
#handler400 = 'world.views.error400page'
#AEN: THIS doesn't work!
import voxel_globe.main.views
urlpatterns = [
#Admin site apps
url(r'^admin/', include(admin.site.urls)),
#Test app for development reasons
url(r'^world/', inc... | nilq/baby-python | python |
"""added column to DT and created NewTable
Revision ID: 1100598db8eb
Revises: 66362e7784fd
Create Date: 2021-02-21 13:56:05.307362
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1100598db8eb'
down_revision = '66362e7784fd'
branch_labels = None
depends_on = No... | nilq/baby-python | python |
import time
import multiprocessing
import subprocess
import sys
import os
def run(name):
dir_path = os.path.dirname(os.path.realpath(__file__))
subprocess.Popen(('%s' % sys.executable, os.path.join(dir_path, "test_remote.py"), name, "etc etc"))
if __name__ == '__main__':
multiprocessing.Process(target=ru... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
from concurrent.futures import TimeoutError
from kikimr.public.sdk.python import client as ydb
import random
EXPIRATION_QUEUE_COUNT = 4
DOC_TABLE_PARTITION_COUNT = 4
ADD_DOCUMENT_TRANSACTION = """PRAGMA TablePathPrefix("%s");
DECLARE $url AS Ut... | nilq/baby-python | python |
#Elsa by Frostmeister
import discord
import math
import time
import googlesearch as gs
import urbandictionary as ud
import random
import asyncio
from discord.ext import commands
####### General
class General:
def __init__(self , bot):
self.bot = bot
@commands.command()
async def in... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
"""
jsondict <-> dict <-> model object
\______________________/
"""
def _datetime(*args):
import pytz
from datetime import datetime
args = list(args)
args.append(pytz.utc)
return datetime(*args)
def _getTarget():
from alchemyjsonschema.mapping import Draft4MappingF... | nilq/baby-python | python |
import numpy as np
'''
Reorient the mesh represented by @vertices so that the z-axis is aligned with @axis
'''
def orient_mesh(vertices, axis):
vector_norm = np.sqrt(axis[0]**2 + axis[1]**2 + axis[2]**2)
yz_length = np.sqrt(axis[1]**2 + axis[2]**2)
# Rotate around the y-axis
if vector_norm != 0:
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import logging
import math
import random
from PIL import Image, ImageDraw
from .wallpaper_filter import WallpaperFilter
from ..geom.point import Point
from ..geom.size import Size
logger = logging.getLogger(__name__)
class Tunnel(WallpaperFilter):
def _centroid(self, size) -> Point:
... | nilq/baby-python | python |
#!/usr/bin/env python
#-*- coding=UTF-8 -*-
import httplib2
import json
import random
import string
import time
import urllib
from securUtil import SecurUtil
class smsUtil():
@staticmethod
def baseHTTPSRequest(url, data):
# 配置 HTTP Request Header
AppKey = '1958cd7bc542a299b0c3bc428f14006e'... | nilq/baby-python | python |
"""
drift
=====
Drift calculation methods.
"""
from .continuous import drift_continuous
from .roman import drift_roman
| nilq/baby-python | python |
# Copyright (c) 2019, Digi International, Inc.
#
# 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, merge, pu... | nilq/baby-python | python |
import math, glm
class Camera:
def __init__(self, position):
self.position = position
self.up = glm.vec3(0, 1, 0)
self.worldUp = glm.vec3(0, 1, 0)
self.pitch = 0
self.yaw = 0
self.speed = 20
self.sensitivity = 0.25
self.updateVectors()
def moveRi... | nilq/baby-python | python |
from bfieldtools import contour
import pytest
import numpy as np
from numpy.testing import (
assert_array_almost_equal,
assert_array_equal,
assert_allclose,
assert_equal,
)
def setup_contour_input():
""" Load example mesh and create scalars data
"""
from bfieldtools.utils import load_exa... | nilq/baby-python | python |
# Leia um valor de comprimento em jardas e apresente-o convertido em metros
# A foruma de conversão é: M = 0.91 * J
J = float(input("Digite um valor em jardas: "))
M = 0.91 * J
print("O valor em de jardas para metros é: %0.2f" % M)
| nilq/baby-python | python |
from .arch import Arch
from .debian import Debian
from .ubuntu import Ubuntu
from .redhat import RedHat
from .centos import CentOS
| nilq/baby-python | python |
import argparse
import torch
from torch.autograd import Variable
import model
import util
import data
import time
import torchvision.transforms as transforms
import shutil
model_names = sorted(name for name in model.__dict__
if name.startswith("Planet")
and callable(model.__dict__[name]))
print model_names
... | nilq/baby-python | python |
import abc
class RecurrentSupervisedLearningEnv(metaclass=abc.ABCMeta):
"""
An environment that's really just a supervised learning task.
"""
@abc.abstractmethod
def get_batch(self, batch_size):
"""
:param batch_size: Size of the batch size
:return: tuple (X, Y) where
... | nilq/baby-python | python |
'''
Created on Aug 9, 2013
@author: salchoman@gmail.com - salcho
'''
class wsResponse:
def __init__(self, id=-1, params=None, size=-1, response=None, payload=None, plugin=None):
self.id = id
self.params = params
self.size = size
self.http_code = -1
self.response = None... | nilq/baby-python | python |
import tensorflow as tf
def iou(source, target):
"""Calculates intersection over union (IoU) and intersection areas for two sets
of objects with box representations.
This uses simple arithmetic and outer products to calculate the IoU and intersections
between all pairs without looping.
Parameter... | nilq/baby-python | python |
# Generated by Django 3.0.3 on 2020-08-10 13:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ecommerce_platform', '0015_auto_20200810_1252'),
]
operations = [
migrations.RenameField(
model_name='coupon',
... | nilq/baby-python | python |
import pytest
from pytest import approx
import os
import shutil
import numpy as np
import pandas as pd
from tarpan.testutils.a03_cars.cars import get_fit
from tarpan.cmdstanpy.waic import (
waic, compare_waic, save_compare_waic_csv, save_compare_waic_txt,
waic_compared_to_df,
WaicData, WaicModelCompared,
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @Date : 2019-07-26
# @Author : Xinyu Gong (xy_gong@tamu.edu)
# @Link : None
# @Version : 0.0
import os
import glob
import argparse
import numpy as np
from scipy.misc import imread
import tensorflow as tf
import utils.fid_score as fid
def parse_args():
parser = argparse.Argument... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
'''
@author: Jinpeng LI
@contact: mr.li.jinpeng@gmail.com
@organization: I2BM, Neurospin, Gif-sur-Yvette, France
@organization: CATI, France
@organization: U{IFR 49<http://www.ifr49.org>}
@license: U{CeCILL version 2<http://www.cecill.info/licences/Lice... | nilq/baby-python | python |
from dataclasses import dataclass, field
from typing import Dict
from lf3py.serialization.deserializer import DictDeserializer
@dataclass
class SNSMessage(DictDeserializer):
message: str = ''
attributes: Dict[str, Dict[str, str]] = field(default_factory=dict)
| nilq/baby-python | python |
from utils import *
def cross_val_split(dataset, folds):
"""
Splits the dataset into folds number of subsets of almost equal size after randomly shuffling it, for cross
validation.
:param dataset: The dataset to be splitted.
:param folds: The number of folds to be created.
:return: The datase... | nilq/baby-python | python |
import random
from abc import ABCMeta, abstractmethod
from collections import defaultdict, Counter, OrderedDict
import math
import numpy as np
from gtd.log import indent
from wge.rl import Trace
def normalize_counts(counts):
"""Return a normalized Counter object."""
normed = Counter()
total = float(sum(... | nilq/baby-python | python |
#
# PySNMP MIB module FNCNMS (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FNCNMS
# Produced by pysmi-0.3.4 at Wed May 1 13:14:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
... | nilq/baby-python | python |
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x' 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', ... | nilq/baby-python | python |
"""
Determine an optimal list of hotel to visit.
```
$ python src/domain/solver.py \
-s "/Users/fpaupier/projects/samu_social/data/hotels_subset.csv
```
Note that the first record should be the adress of the starting point (let's say the HQ of the Samu Social)
"""
import argparse
import numpy as... | nilq/baby-python | python |
import torch.nn as nn
import math
import torch.nn.functional as F
__all__ = ['SENet', 'Sphere20a', 'senet50']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
# ... | nilq/baby-python | python |
# Create your views here.
from django.conf import settings
from django.core.cache import cache
from django.db.models import Prefetch
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.generics import RetrieveAPIView, ListAPIView
from question.m... | nilq/baby-python | python |
import os.path
import random
import multiprocessing
import pandas as pd
from utils import load_library, correct_full_sequence, get_precursor_indice, tear_library, flatten_list
from mz_calculator import calc_fragment_mz
def shuffle_seq(seq = None, seed = None):
"""Fisher-Yates algorithm. Modified from PECAN's deco... | nilq/baby-python | python |
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2020-2021 Micron Technology, Inc. All rights reserved.
import argparse
import datetime
import os
import time
import subprocess
import sys
import requests_unixsocket
import yaml
TZ_LOCAL = datetime.datetime.now(datetime.timezone.utc).ast... | nilq/baby-python | python |
import csv
import six
import io
import json
import logging
from collections import Mapping
from ..util import resolve_file_path
logger = logging.getLogger(__name__)
EPILOG = __doc__
class MappingTableIntakeException(Exception):
""" Specific type of exception we'd like to throw if we fail in this stage
du... | nilq/baby-python | python |
import numpy as np
import torch
import itertools
from torch.autograd import Variable
def getGridMask(frame, dimensions, num_person, neighborhood_size, grid_size, is_occupancy = False):
'''
This function computes the binary mask that represents the
occupancy of each ped in the other's grid
params:
... | nilq/baby-python | python |
# Copyright 2021 The KaiJIN 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 ... | nilq/baby-python | python |
import anyio
from anyio_mqtt import AnyIOMQTTClient
import logging
_LOG = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("anyio_mqtt").setLevel(logging.DEBUG)
PAHO_LOGGER = logging.getLogger("paho")
PAHO_LOGGER.setLevel(logging.DEBUG)
async def main() -> None:
_LOG.debu... | nilq/baby-python | python |
import time
import random
import numpy as np
import torch
from torchtuples import tuplefy, TupleTree
def make_name_hash(name='', file_ending='.pt'):
year, month, day, hour, minute, second = time.localtime()[:6]
ascii_letters_digits = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
random_h... | nilq/baby-python | python |
# Copyright (c) Andrey Sobolev, 2019. Distributed under MIT license, see LICENSE file.
GEOMETRY_LABEL = 'Geometry optimization'
PHONON_LABEL = 'Phonon frequency'
ELASTIC_LABEL = 'Elastic constants'
PROPERTIES_LABEL = 'One-electron properties'
| nilq/baby-python | python |
import django # this verifies local libraries can be packed into the egg
def addition(first, second):
return first + second
| nilq/baby-python | python |
import sys
import os
import argparse
import pandas as pd
from fr.tagc.rainet.core.util.exception.RainetException import RainetException
from fr.tagc.rainet.core.util.log.Logger import Logger
from fr.tagc.rainet.core.util.time.Timer import Timer
from fr.tagc.rainet.core.util.subprocess.SubprocessUtil import SubprocessU... | nilq/baby-python | python |
"""
参数及配置
"""
# main.py
small_dataset = False # 选择数据集规模
small_train_path = "../data/small_dataset/train.conll" # 小数据集-训练集
small_dev_path = "../data/small_dataset/dev.conll" # 小数据集-验证集
big_train_path = "../data/big_dataset/train" # 大数据集-训练集
big_dev_path = "../data/big_dataset/dev" # 大数据集-验证集
big_test_pat... | nilq/baby-python | python |
from cakechat.utils.data_structures import create_namedtuple_instance
SPECIAL_TOKENS = create_namedtuple_instance(
'SPECIAL_TOKENS', PAD_TOKEN=u'_pad_', UNKNOWN_TOKEN=u'_unk_', START_TOKEN=u'_start_', EOS_TOKEN=u'_end_')
DIALOG_TEXT_FIELD = 'text'
DIALOG_CONDITION_FIELD = 'condition'
| nilq/baby-python | python |
from models.models import Departamento | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Python implementation of Tanner Helland's color color conversion code.
http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
"""
import math
# Aproximate colour temperatures for common lighting conditions.
COLOR_TEMPERATURES = {
'candle': 1900,
'sunrise': 2000,
... | nilq/baby-python | python |
# The MIT license:
#
# Copyright 2017 Andre Netzeband
#
# 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, merg... | nilq/baby-python | python |
# Generated by Django 2.2.5 on 2019-10-07 17:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cases', '0016_datetimes_to_dates'),
]
operations = [
migrations.AlterField(
model_name='preliminarycase',
name='comp... | nilq/baby-python | python |
from pyvisdk.esxcli.executer import execute_soap
from pyvisdk.esxcli.base import Base
class IscsiNetworkportalIpconfig(Base):
'''
Operations that can be performed on iSCSI Network Portal (iSCSI vmknic)'s IP configuration
'''
moid = 'ha-cli-handler-iscsi-networkportal-ipconfig'
def set(self, adapte... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Tests dict input objects for `tackle.providers.system.hooks.lists` module."""
from tackle.main import tackle
def test_provider_system_hook_lists(change_dir):
"""Verify the hook call works properly."""
output = tackle('.', no_input=True)
assert 'donkey' in output['appended_list... | nilq/baby-python | python |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField,SelectField
from wtforms.validators import Required
class PitchForm(FlaskForm):
title = StringField('Pitch title',validators=[Required()])
text = TextAreaField('Text',validators=[Required()])
category = SelectField('... | nilq/baby-python | python |
#!/usr/bin/env python
"""
ROS node implementing Rhinohawk global mission state. See rh_msgs.msg.State for a full description of the state data.
The state node aggregates state from many different sources and makes it available to other nodes in the Rhinohawk System, particularly the controller node which is responsibl... | nilq/baby-python | python |
class Tuners(object):
"""Enum class for mapping symbols to string names."""
UNIFORM = "uniform"
GP = "gp"
GP_EI = "gp_ei"
GP_EI_VEL = "gp_eivel"
| nilq/baby-python | python |
# coding=utf-8
import re
from jinja2 import Environment, PackageLoader
class ViewModel(object):
class Property(object):
def __init__(self, name, type_name):
super(ViewModel.Property, self).__init__()
self.name = name
self.type_name = type_name
def __str__(sel... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import numpy as np
from plotting import *
def PID(x,I,dx,KP,KI,KD):
u = -np.dot(KP,x)-np.dot(KI,I)-np.dot(KD,dx)
return u
def PID_trajectory(A,B,c,D,x0,dx0,KP,KI,KD,dt=1e-3,T=10,xdes=None,dxdes=None):
"""
For 2nd order system Ax + Bdx + c + Du and PID controller
Ret... | nilq/baby-python | python |
"""
Copyright (c) 2018 Intel Corporation
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 writin... | nilq/baby-python | python |
#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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 ... | nilq/baby-python | python |
from sentence_transformers import SentenceTransformer, InputExample, losses
from torch.utils.data import DataLoader
#Define the model. Either from scratch of by loading a pre-trained model
model = SentenceTransformer('distilbert-base-nli-mean-tokens')
#Define your train examples. You need more than just two examples.... | nilq/baby-python | python |
from ..core import Dimensioned, AttrTree
try:
import pandas
from .pandas import DFrame # noqa (API import)
except:
pandas = None
try:
import seaborn
from .seaborn import * # noqa (API import)
except:
seaborn = None
from .collector import * # noqa (API import)
def public(obj):
i... | nilq/baby-python | python |
#! /bin/python3
import socket
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
listener.bind(('127.0.0.1', 8080))
listener.listen(0)
print("[+] Esperando por conexiones")
connection, addr = listener.accept()
print("[+] Conexion de " + str(ad... | nilq/baby-python | python |
from collections import defaultdict, deque
import math
from .models import Node, Edge
class Graph(object):
def __init__(self):
self.nodes = set() # Nodes models
self.edges = defaultdict(list) # Edges models
self.distances = {}
# mimic Nodes model
def add_node(self, valu... | nilq/baby-python | python |
from client.nogui import DirManager
dm = DirManager()
dm.run() | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright CNRS 2012
# Roman Yurchak (LULI)
# This software is governed by the CeCILL-B license under French law and
# abiding by the rules of distribution of free software.
import numpy as np
from scipy.constants import e, c, m_e, epsilon_0, k, N_A
from scipy.constants impo... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import humps
import re
def main():
comp = re.compile(r"^(0x[\da-f]+) ([\w \,]*) (\d)", re.M | re.I)
match = None
op_input = "utils/opcodes.txt"
op_output = "src/op.rs"
dis_output = "src/dis/mod.rs"
asm_output = "src/asm/mod.rs"
with open(o... | nilq/baby-python | python |
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | nilq/baby-python | python |
import CustomVLCClass
import serial
import time
import threading
time.sleep(20)
while True:
def inputListener():
inputdata = input('0 to quit the first song, 1 to quit the second song')
if(inputdata == '0'):
if a.mediaplayer.is_playing() :
a.pause()
else:
... | nilq/baby-python | python |
import torch
from kobart import get_kobart_tokenizer
from transformers.models.bart import BartForConditionalGeneration
class KoBART_title():
def __init__(self, ckpt_path="./n_title_epoch_3"):
self.model = BartForConditionalGeneration.from_pretrained(ckpt_path).cuda()
self.tokenizer = get_kobart_to... | nilq/baby-python | python |
from scripts.game_objects.game_object import GameObject
from scripts.consts import IRON_SWORD, WOODEN_BOW
class Weapon(GameObject):
def __init__(self, game, type, damage, x, y):
weapon_dict = {'iron_sword': IRON_SWORD, 'wooden_bow': WOODEN_BOW}
super().__init__(game, weapon_dict[type], x, y, game.... | nilq/baby-python | python |
# Copyright (c) 2014 ITOCHU Techno-Solutions Corporation.
#
# 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... | nilq/baby-python | python |
from __future__ import unicode_literals
__all__ = (
'Key',
'Keys',
)
class Key(object):
def __init__(self, name):
#: Descriptive way of writing keys in configuration files. e.g. <C-A>
#: for ``Control-A``.
self.name = name
def __repr__(self):
return 'Key(%s)' % self.... | nilq/baby-python | python |
import autograd
import autograd.numpy as np
import scipy as sp
from copy import deepcopy
import paragami
from paragami.autograd_supplement_lib import grouped_sum
import vittles
import time
def _validate(y, x):
n_obs = x.shape[0]
x_dim = x.shape[1]
if len(y) != n_obs:
raise ValueError(
... | nilq/baby-python | python |
import json
import numpy as np
import os.path as osp
import warnings
from collections import defaultdict
from plyfile import PlyData
from six import b
from ..utils.point_clouds import uniform_sample
from ..utils import invert_dictionary, read_dict
from ..utils.plotting import plot_pointcloud
from .three_d_object impo... | nilq/baby-python | python |
"""Voorstudie voor een DTD editor (wxPython versie) - not actively maintained
"""
import os,sys,shutil,copy
from xml.etree.ElementTree import Element, ElementTree, SubElement
import parsedtd as pd
ELTYPES = ('pcdata','one','opt','mul','mulopt')
ATTTYPES = ('cdata','enum','id')
VALTYPES = ('opt','req','fix','dflt... | nilq/baby-python | python |
def register(mf):
mf.overwrite_defaults({
"testvar": 42
}, scope="..notexistentmodule")
| nilq/baby-python | python |
# <caret> | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.