content stringlengths 5 1.05M |
|---|
from django import forms
from tasks.models import TodoItem
class AddTaskForm(forms.Form):
description = forms.CharField(max_length=64, label="")
class TodoItemForm(forms.ModelForm):
class Meta:
model = TodoItem
fields = ("description", "priority")
labels = {"description": "Описание"... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
import pygame
import math
import random
from pygame.locals import *
from src.Road import Road
class DisplayController:
def __init__(self):
"""
Initializes DisplayController
"""
pygame.init()
self.display_size = 2000, 2000
self.display_surface = pygame.display.set_mo... |
#! /usr/bin/env python3.6
import jieba
import jieba.analyse
import argparse
import pathlib
import re
import numpy as np
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from os import path
from PIL import Image
from pathlib import Path
#########################
# Main-Routine #
###############... |
import numpy as np
import scipy as sp
from scipy.io.wavfile import read
from scipy.io.wavfile import write
from scipy import signal
import matplotlib.pyplot as plt
# from IPython import get_ipython
# get_ipython().magic('matplotlib inline')
(Frequency, array) = read('my_record/1.wav')
len(array)
plt.plot(array)
plt... |
area = float(input("Qual a área em metros quadrados a ser pintada? "))
num_litros = area / 6
num_latas = num_litros / 18
num_galoes = num_litros / 3.6
# preco = num_latas * 80
opcao = int(input(
"Se você pretende comprar somente latas de 18 litros, digite 1. Se você pretende comprar somente galoes de 3.6 litr... |
# --------------------------------------------------------
# OpenVQA
# Written by Yuhao Cui https://github.com/cuiyuhao1996
# Modified at FrostLabs
# --------------------------------------------------------
from importlib import import_module
class ModelLoader:
def __init__(self, __C):
self.model_use = ... |
from PIL import Image,ImageDraw,ImageFont
#w = 638
#h = 1063
im = Image.open(r"名片1.jpg")
(w,h) = im.size
bg = Image.new("RGB",(w,h),(255,255,255))
#im = Image.open(r"名片1.jpg")
draw2 = Image.blend(bg,im,1.0)
draw = ImageDraw.Draw(draw2)
name = "许家印"
site = "地址:"+"广东省清远市某某区屋某村某巷21号"
work = "游戏开... |
from turtle import Screen
import time
import car
import user_turtle
import scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.title("Turtle Crossing Game")
screen.bgcolor("black")
screen.tracer(0)
scoreboard = scoreboard.Scoreboard()
cars = car.Car()
user_turtle_obj = user_turtle.UserTurtle()
sc... |
from django.urls import path
from .views import AgentListView, AgentCreateView, AgentDetailView, AgentUpdateView, AgentDeleteView
app_name = 'agents'
urlpatterns = [
path('', AgentListView.as_view(), name='agent-list'),
path('create/', AgentCreateView.as_view(), name='agent-create'),
path('<int:pk>/', Age... |
"""
Command support for generating backupset configs
"""
import os
import sys
import tempfile
import logging
import subprocess
from StringIO import StringIO
from holland.core.command import Command, option
from holland.core.plugin import load_first_entrypoint, PluginLoadError
from holland.core.config.configobj import... |
import librosa
def determine_tempo(y, sr):
onset_env = librosa.onset.onset_strength(y, sr)
return librosa.beat.estimate_tempo(onset_env, sr=sr)
def determine_time_sig(y, sr):
onset_env = librosa.onset.onset_strength(y, sr)
tempogram = librosa.feature.tempogram(y, sr, onset_env)
|
# 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.
#----------------------------------------------------------------------... |
def swap(a, b):
"""
Swaps the inputs
Parameters
----------
a : object
first object
b : object
second object
Returns
-------
(object,object)
a tuple containing the inputs swapped
"""
return b, a
|
# pylint: skip-file
# Python 3
import tkinter as tk
from tkinter import ttk
from lib.tkToolTip import Tooltip
#########################
# The tab's public class:
#########################
class Tab:
def __init__(self, parentFrame):
""" Put this into the parent frame """
pass
tkLabelCondit... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-03 18:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0026_activity'),
]
operations = [
migrations.AlterModelOptions(
... |
#! /usr/bin/env python
import rospy
from math import sqrt
from tf import TransformListener
from suii_msgs.srv import DistanceToGoal
from tf import TransformListener
from tf.transformations import euler_from_quaternion
class EuclideanDistanceCalculator(object):
def __init__(self):
rospy.init_node("euclidea... |
"""Authentification-related form classes."""
from flask_wtf import FlaskForm
from wtforms import Form, StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo, Length, Regexp
from app.models import User
from flask import render_template, current... |
import ccxt
from ..base.api import ApiBase
class BybitApi(ApiBase, ccxt.bybit):
_ccxt_class = ccxt.bybit
def __init__(self, ccxt_config={}):
ApiBase.__init__(self)
ccxt.bybit.__init__(self, ccxt_config)
self.load_markets()
# silence linter
self.v2_private_get_position... |
from avista_iot import api
from avista_base.service import Service
# from multiprocessing import Process
class IoTServer(Service):
def __init__(self):
""" instantiate the app """
super().__init__()
self.sensor_sweep = None
def _setup_endpoints(self):
super()._setup_endpoints(... |
import argparse
import requests
import re
base_url = 'http://signmaking.rockler.com/'
sign_path = 'base.cfc?method=getTemplate&returnFormat=json'
def request_sign_data(sign_text):
data = {'stringIn': sign_text}
sign_url = '{}{}'.format(base_url, sign_path)
r = requests.post(sign_url, data=data)
return r.js... |
import logging
from abc import ABCMeta, abstractmethod
import torch.nn as nn
class BaseEstimator(nn.Module):
"""Base class for pose estimation"""
__metaclass__ = ABCMeta
def __init__(self):
super(BaseEstimator, self).__init__()
@property
def with_neck(self):
return ... |
#Embedded file name: rdp_vuln_ms12020.py
if 0:
i11iIiiIii
import struct
import socket
if 0:
O0 / iIii1I11I1II1 % OoooooooOO - i1IIi
def assign(service, arg = None):
if service == '''rdp''':
return (True, arg)
if 0:
II111iiii
def audit(arg):
IiII1IiiIiI1, iIiiiI1IiI1I1 = ar... |
'''
writers.py: output-writing utilities for Turf.
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2018 by the California Institute of Technology. This code is
open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" for more... |
from RedisQueue import RedisQueue
import sys
import random
from pymongo import MongoClient
if __name__ == '__main__':
db = MongoClient()
exists = db.zhihu.zhihu_questions
exist_owners = []
for e in exists.find():
exist_owners.append(e['owner'])
all_ids = [line.strip().split('\t')[0] for lin... |
from . import *
from aque.utils import *
from aque import utils
class TestBytesFormatting(TestCase):
def test_format_bytes(self):
self.assertEqual(format_bytes(0), '0B')
self.assertEqual(format_bytes(1), '1B')
self.assertEqual(format_bytes(1023), '1023B')
self.assertEqual(format_... |
from .format import wrangle
from .array import is_array, wrangle_array
from .dataframe import is_dataframe, wrangle_dataframe, is_multiindex_dataframe
from .null import is_null, wrangle_null
from .text import is_text, wrangle_text, get_corpus, apply_text_model, get_text_model, to_str_list, get_text
from ..util.helpers ... |
import os
import sys
import tempfile
import unittest
import mock
import numpy
from chainer import cuda
from chainer import link
from chainer import links
from chainer import optimizers
from chainer.serializers import hdf5
from chainer import testing
from chainer.testing import attr
if hdf5._available:
import h5... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import vibhat
import zipfile
import os
from time import sleep
def main():
"""
runs vibhat every minute, compresses vibhat data
"""
while True:
FDT = vibhat.vibhat()
print(FDT)
print('\n')
zipname = FDT[:-4]
filena... |
from pynaoqi_mate import Robot
from configuration import PepperConfiguration
import qi
import time
class Bumper(object):
def __init__(self, myrobot):
super(Bumper,self).__init__()
session = myrobot.session
self.memory = session.service("ALMemory")
self.subscriberRight = self.memory.... |
import random
from common.models import Position, Region
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APIRequestFactory, APITestCase
from players.api.serializers import P... |
"""
This module manages all of the code around Sprites.
"""
# pylint: disable=too-many-arguments, too-many-locals, too-few-public-methods
import ctypes
import math
import pyglet.gl as GL
from arcade.geometry import rotate
from arcade.draw_commands import load_texture
from arcade.draw_commands import draw_texture_rect... |
#!/usr/bin/env python3
import os, sys, json, time, subprocess, datetime, argparse, traceback, requests
from dateutil.parser import parse as duparse
import dateutil.tz as dutz
#for absolute imports to work in script mode, we need to import from the root folder
opath = os.path.abspath(".")
abspath = os.path.abspath(__fi... |
# Steppers
# This module provides the time-stepping
# functions used for the simulator class.
__author__ = "Ben Storer <bastorer@uwaterloo.ca>"
__date__ = "16th of March, 2015"
# Import the functions
from Euler import Euler
from AB2 import AB2
from AB3 import AB3
from RK4 import RK4
|
import pandas as pd
import numpy as np
from os import path, listdir
def get_CoM(df):
N = df.shape[0]
com_x, com_y = np.sum(df["x"])/N, np.sum(df["y"])/N
return np.array([com_x, com_y])
dir_name = "drawing_csv"
files = listdir(dir_name)
# <============================ FILE CHECKING ==================... |
# Copyright 2016, 2017 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 22 11:39:43 2018
Demonstration of 3D CPU regularisers
@authors: Daniil Kazantsev, Edoardo Pasca
"""
import matplotlib.pyplot as plt
import numpy as np
import os
import timeit
from ccpi.filters.regularisers import ROF_TV, FGP_TV, SB_TV, LLT_ROF, F... |
# -*- coding: utf-8 -*-
"""
requests.core
~~~~~~~~~~~~~
This module implements the main Requests system.
:copyright: (c) 2011 by Kenneth Reitz.
:license: ISC, see LICENSE for more details.
"""
__title__ = 'requests'
__version__ = '0.4.1'
__build__ = 0x000401
__author__ = 'Kenneth Reitz'
__license__ = 'ISC'
__copyr... |
import vaex
import numpy as np
def test_plot_widget_bqplot():
# basic coverage for now
df = vaex.example()
df.plot_widget(df.x, df.y)
df.plot_widget(df.x.astype('float32'), df.y.astype('float32'))
df.plot_widget(df.x.astype('float32'), df.y.astype('float32'), limits='minmax')
def test_widget_hist... |
#!/usr/bin/env python
__author__ = 'weezhard'
__license__ = 'GPL'
__version__ = '1.0.0'
import sys
import argparse
import libvirt
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('-d','--domain', help='Domain libvirt', required=True)
parser.add_argument('-r','--ram', help='Ram', default=2048... |
import itertools
import math
import random
from pytest import approx
import pytest
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence
from torchcrf import CRF
RANDOM_SEED = 1478754
random.seed(RANDOM_SEED)
torch.manual_seed(RANDOM_SEED)
def compute_score(crf, emission, tag):
# emis... |
#!/usr/bin/python
DOCUMENTATION = """
---
module: comware_install_config
short_description: Activate a new current-running config in realtime
description:
- Activate a new current-running config in realtime
version_added: 1.8
category: System (RW)
notes:
- Check mode copies config file to device and still gen... |
# proxy module
from enable.savage.trait_defs.ui.svg_button import *
|
from http import HTTPStatus
from flask import Blueprint, redirect, request
from flask_cors import CORS
bp = Blueprint("eve_routes", __name__)
CORS(bp)
# Eve endpoints can only be configured to respond on a single versioned endpoint. We need to continue to support the
# endpoints served at the root of the server whi... |
# Compare manifold learning methods
#https://scikit-learn.org/stable/auto_examples/manifold/plot_compare_methods.html
# Author: Jake Vanderplas -- <vanderplas@astro.washington.edu>
# Modified by Kevin Murphy
import superimport
from collections import OrderedDict
from functools import partial
from time import time
im... |
#!/usr/bin/env python3
from functools import *
import operator
number = """
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711... |
from docutils import nodes, utils
def api_link_inner(baseurl, rawtext, text, options):
package, varname = text.strip().split( "/")
if package == '':
package = 'com.walmartlabs.lacinia'
else:
package = 'com.walmartlabs.lacinia.' + package
ref = '%s/%s.html#var-%s' % (baseurl, package, varname)
ti... |
import json
class Params:
"""Class for storing parameters information and loading external data
Attributes
----------
state_transitions: dict
Dictionary of state transitions in form
{initial_state: {new_state: {"age_group": probability}}}
generic_infection : float
Generic ... |
from bitmovin_api_sdk.encoding.encodings.muxings.mp4.drm.playready.playready_api import PlayreadyApi
from bitmovin_api_sdk.encoding.encodings.muxings.mp4.drm.playready.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.encoding.encodings.muxings.mp4.drm.playready.play_ready_drm_list_query_params impor... |
from statham.schema.constants import NotPassed
from statham.schema.elements import Object
class PropertyExtension(object):
def get_properties(self):
return []
class CardItemExt(PropertyExtension):
@property
def name(self):
return list(self._dict.keys())[0]
@property
def actions(... |
import numpy as np
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Pie, Bar, Map
key = '帽子'
GOODS_EXCEL_PATH = f'./data/sales_data_{key}.xlsx'
GOODS_STANDARD_EXCEL_PATH = f'./data/sales_data_{key}_standard.xlsx'
DF_STANDARD = pd.read_excel(GOODS_STANDARD_EXCEL_PATH)
def standa... |
#coding=utf-8
#导入公共函数库
from function import *
#导入数据库模型
from appscan.models import navigation,navigation_url
# Create your views here.
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
def index(request):
#navigation = navigation.objects.fiter('你的条件')
#data = navigation_url.objects.all()
result = []
... |
# MIT License
# Copyright (c) 2017 Balazs Bucsay
# 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, ... |
class Solution(object):
def convert(self, s, numRows):
"""
:s的类型: str
:numRows类型: int
:返回类型: str
"""
if numRows <= 1:
return s
n = len(s)
ans = []
step = 2 * numRows - 2
for i in range(numRows):
one = i
two = -i
while one < n or two < n:
if 0 <= ... |
import torch
from transformers import (
AutoTokenizer,
AutoModelWithLMHead
)
from preprocessor import Preprocessor
from decoder import Decoder
import argparse
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
def print_predictions(sentence, preds_probs):
k = min(len(preds_probs),10)
# print(f"... |
from dataclasses import dataclass
from typing import Any
@dataclass(frozen=True)
class Point2D:
"""
2D coordinates in a grid.
"""
x: int # pylint: disable=invalid-name
y: int # pylint: disable=invalid-name
def __contains__(self, other: Any) -> bool:
"""
Assuming other is al... |
import json
import logging
import os
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Preferences(object):
"""
Holds user's preferences.
"""
PATH = os.path.expanduser('~/.sentrycli')
def __init__(self):
self._prefs = {}
self.load();
def loa... |
"""Scrape the Biolinux website to retrieve a list of packages they install.
http://www.jcvi.org/cms/research/projects/jcvi-cloud-biolinux/included-software
This needs to run on a machine with an apt system to check for the existance of
package names.
"""
import sys
import urllib2
import re
import subprocess
import St... |
#!/usr/bin/env python
""" Problem 70 daily-coding-problem.com """
def perfect_number(n: int) -> int:
result = 10
for c in str(n):
result -= int(c)
return int(str(n) + str(result))
if __name__ == "__main__":
assert perfect_number(1) == 19
assert perfect_number(2) == 28
assert per... |
import os
# video_categories = ['ours', 'no_aff', 'no_pose', 'no_ang']
video_categories = ['2_7_39']
base_path = 'W:/Gamma/Gestures'
videos_file_path = os.path.join(base_path, 'videos')
for cat in video_categories:
for seq_num in range(1, 5):
seq = os.path.join(videos_file_path, 'individual_frames_' + cat... |
import numpy as np
from numpy import linalg as LA
x = np.array([2,-1,3,2]).reshape((-1,1))
y = np.array([3,2,1,-4]).reshape((-1,1))
print(LA.norm(x))
print(LA.norm(y))
print(LA.norm(x-y)) |
import collections
import os
import sys
import numpy as np
import scipy.stats
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from ncp.tools import attrdict, plotting
# NOTE
# Use the NOTE marker to indicate changes
def run_experiment(
logdir,
graph,
dataset,
num_epochs,
eval_after_... |
import logging
import os
import random
from datetime import datetime
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from torch import optim
from torch.cuda.amp import GradScaler
try:
import wandb
except ImportError:
wandb = None
try:
import torch.utils.tensorboard as tensorboard
exc... |
# -*- coding: utf-8 -*-
#
# Copyright © 2018- CELLS / ALBA Synchrotron, Bellaterra, Spain
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009-2018 The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Provides QtGui classes and functions.
.. warning:: Co... |
# -*- coding: utf-8 -*-
import numpy as np
from scipy import optimize
from environments.car_controller.cesco_drive.cesco_drive_v0 import CescoDriveV0
from environments.car_controller.utils import *
class CescoDriveV1(CescoDriveV0):
def step(self, action_vector):
# first of all, get the seconds passed from last ste... |
__all__ = ["generate_projection", "plot_grid", "plot_metrics", "plot_projection"]
from src.visualization.metrics import plot_grid, plot_metrics
from src.visualization.projection import plot_projection, generate_projection
|
#!/usr/bin/env python
# coding: utf-8
# # Section 2: Implementation of LDA
# To further understand the importance of topic modeling, we will be looking into a public dataset, i.e. the Jigsaw Unintended Bias dataset.
#
#
# This dataset consists of ~2m public comments from the Civil Comment platform so that research... |
import numpy as np
import math, time
from ..util import make_list
from numpy.random import default_rng
from .rnn import RNNLayer
rng = default_rng()
Use_numba = True
if Use_numba:
try: from numba import jit
except:
print("lstm: failed to import numba")
Use_numba = False
@jit("Tuple((float... |
#!/usr/bin/env python
#
# Copyright (c) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
#! /usr/bin/env python
"""
Script to add MAC addresses to the ISE
Guest MAB ID Group
"""
import sys
import csv
from decouple import config
from pathlib import Path
import urllib3
import network_automation.ise_mac_bypass.mac_bypass.api_calls as api
sys.dont_write_bytecode = True
def csv_to_dict(filename: str) -> dict... |
import json
from PyQt5 import QtCore
from PyQt5.QtCore import QObject
from src.component.Const import Const
from src.model.Music import Music
from src.util.IOs import IOs
class Playlist(QObject):
"""
播放列表
根据path & from 来判断是否是来自同一歌单同一首音乐
TODO: 持久化播放列表
"""
# 信号: 当播放列表发生任何变化时
chang... |
"""
This module provides helpers to define and manage live components, that
is taglibrary components whose instances are client-side JS objects.
Each component must have a unique name in the livepage context. This
name is usually the same as (or derived from) the 'name' field in the
data given to the tag renderer. T... |
from unittest import TestCase
from Blackjack.blackjack import Hand, Card, Deck
class TestDeck(TestCase):
def test_deal(self):
player_hand = []
deck = Deck()
player_hand.append(deck.deal())
player_hand.append(deck.deal())
actual = len(player_hand)
self.assertEqual(a... |
import numpy as np
from pyrr import Vector3
class Primitives:
def __init__(self):
pass
def cube(self):
vertices = [
-1.0, 1.0, 1.0, # Left
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, -1.0,
-1.0, -1.0, -1.0,
-1.0, 1.0, 1... |
'''
Events, Tasks and related stuff
'''
from enum import IntEnum,Enum
import yaml
import json
from . import OnTime
from . import utils
import datetime
import sys
#
global_config={}
def joinEnumsIndices(e,meta):
return ','.join( str(v.value) for v in e if v.isMetaStatus(meta) )
def joinEnumsIndicesExcept(e,meta)... |
from mongoengine import Document, fields
class Image(Document):
name = fields.StringField(required=True)
image_format = fields.StringField(required=True)
image = fields.FileField(required=True)
|
from umap import UMAP
from lib.custom_whatlies.transformers._transformer import SklearnTransformer
class Umap(SklearnTransformer):
"""
This transformer transformers all vectors in an [EmbeddingSet][whatlies.embeddingset.EmbeddingSet]
by means of umap. We're using the implementation in [umap-learn](https:... |
import pickle
from prompt_toolkit import prompt
from prompt_toolkit import completion
from prompt_toolkit.completion import NestedCompleter
from prompt_toolkit.filters.app import vi_recording_macro
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit import PromptSession
from prompt_toolkit.validation imp... |
"""
This plugin adds a message at 00:00 in each of your chat tabs saying that the
date has changed.
"""
import datetime
from gettext import gettext as _
from poezio import timed_events, tabs
from poezio.plugin import BasePlugin
from poezio.ui.types import InfoMessage
class Plugin(BasePlugin):
def init(self):
... |
import numpy as np
from math import sqrt
import time
import multiprocessing
import copy
from functools import partial
from datetime import date
import matplotlib.pyplot as plt
import matplotlib
from ROAI_class import ROAI, RANDOM, RR, WRR
# this function is used to generate the instance
def generate_instance_bernoul... |
import unittest
from mock import Mock, MagicMock, patch
from mangrove.datastore.database import DatabaseManager
from datawinners.search.submission_index import SubmissionSearchStore, FieldTypeChangeException
from mangrove.form_model.field import DateField, UniqueIdField
from mangrove.form_model.form_model import Form... |
# -*- coding: utf-8 -*-
import unittest
import numpy
"""
*******************************************************************************
Tests of the quantarhei.qm.propagators.poppropagator module
*******************************************************************************
"""
from quantarhei import Popu... |
from ..utils import Object
class InlineQueryResultContact(Object):
"""
Represents a user contact
Attributes:
ID (:obj:`str`): ``InlineQueryResultContact``
Args:
id (:obj:`str`):
Unique identifier of the query result
contact (:class:`telegram.api.types.contact`... |
import os
import pandas as pd
import plotly.express as px
# Show numeric output in decimal format e.g., 2.15
pd.options.display.float_format = '{:,.2f}'.format
LOCATION = os.path.realpath(os.path.join(
os.getcwd(), os.path.dirname(__file__)))
df_apps = pd.read_csv(os.path.join(
LOCATION, 'data/apps.csv'))
#... |
import torch
from torch.nn import functional as F
import numpy as np
import kornia
# from numba import jit, njit, prange
def rot6d_to_rotmat(x):
"""Convert 6D rotation representation to 3x3 rotation matrix.
Based on Zhou et al., "On the Continuity of Rotation Representations in Neural Networks", CVPR 2019
... |
from room import Room
from player import Player
from world import World
import random
from ast import literal_eval
# Load world
world = World()
# You may uncomment the smaller graphs for development and testing purposes.
# map_file = "maps/test_line.txt"
# map_file = "maps/test_cross.txt"
# map_file = "maps/test_lo... |
import math
import pathlib
import re
import textwrap
from typing import Dict
MAX_FX8 = 2**23 - 1 # Largest number representable as 24.8 fixed point. We will never run into it with non-ridiculous data.
def float2fx8(n):
return int(n * 256)
class Model:
class ModelParseError(Exception):
pass
cla... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def bazel_toolchains_repositories():
if "bazel_toolchains" in native.existing_rules():
return
http_archive(
name = "bazel_toolchains",
sha256 = "d8c2f20deb2f6143bac792d210db1a4872102d81529fe0ea3476c1696addd7ff",
... |
__author__ = 'Rasto'
# script used by runModernaPredictionBasedOnPairs.py
# ModeRNA has to be installed in the system - I used it only with Windows operating system
from Bio.PDB import *
from Bio.Emboss.Applications import *
from moderna import *
class molecule_structure:
def __init__(self, pdb, chain):
... |
from . import ComicBookCrawlerBase, ChapterItem, ComicBookItem
from ..exceptions import ChapterSourceNotFound
class ComicBookCrawler(ComicBookCrawlerBase):
SOURCE_NAME = '狱友提供'
SITE = "yuyou"
def __init__(self, comicid=None):
super().__init__()
self.comicid = comicid
self.last_cha... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
for s in [*open(0)][2::2]:
a=sorted(map(int,s.split()))
print(max([1]+[i+2 for i,x in enumerate(a)if x<i+2]))
|
from algofi_amm.v0.asset import Asset
from algofi_amm.v0.config import PoolType
from algofi_amm.utils import get_payment_txn, send_and_wait
from metapool.metapoolAMMClient import MetapoolAMMClient
from metapool.testing.resources import startup, newTestToken, update_metapool
from metapool.testing.configTestnet import (
... |
import os
import cv2 as cv
import zipfile
import matplotlib.pyplot as plt
import tensorflow as tf
# base_dir = "/data/oHongMenYan/distracted-driver-detection-dataset"
# img_zip_dir = os.path.join(base_dir, 'imgs.zip')
# f = zipfile.ZipFile(img_zip_dir,'r')
# print('begin')
# for file in f.namelist():
# print(file)... |
# http://www.codewars.com/kata/55d277882e139d0b6000005d/
def find_average(nums):
try:
return float(sum(nums)) / len(nums)
except ZeroDivisionError:
return 0
|
#
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
# @generated
#
from __future__ import absolute_import
import six
from thrift.util.Recursive import fix_spec
from thrift.Thrift import *
from thrift.protocol.TProtocol import TProtocolException
import pprint
import warn... |
import secrets
import typing
import json
from sha3 import keccak_256
from coincurve import PublicKey, PrivateKey
from jwcrypto import jwk
class Ethereum:
def __init__(self):
# Ethereum private keys are 32 bytes long.
self._private_key = keccak_256(secrets.token_bytes(32)).digest()
# Et... |
DEBUG = True
NEWS_API_KEY = 'de806c7ae3f44f99a4cbd9ce7b210ca7' |
import os
import tqdm
import torch
import datetime
import itertools
from multiprocessing import Pool
from collections import OrderedDict, defaultdict
def print_message(*s, condition=True):
s = ' '.join([str(x) for x in s])
msg = "[{}] {}".format(datetime.datetime.now().strftime("%b %d, %H:%M:%S"), s)
if... |
#!/bin/env python3
'''
This is a simple MLP script to test out the TensorBoard graph properties,
character constants, and weight matrix visualizers.
'''
import numpy as np
import tensorflow as tf
import pandas as pd
# grab data
df = pd.read_csv('../dat/mushroom_one_hot.csv')
dat = df.as_matrix()
df = pd.read_csv('..... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import codecs
from setuptools import setup
setup(name='django-mathfilters',
version='0.4.0',
description='A set of simple math filters for Django',
long_description=codecs.open('README.rst', encoding='utf-8').read(),
author='Danilo ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.