content stringlengths 5 1.05M |
|---|
from flask import Flask, request, render_template, url_for, redirect, send_file
import helper_functions
import db
import datetime
import celery_app
from config import celery_config
import classifiers
import heatmap
app = Flask(__name__)
# celery_config(app)
# celery = celery_app.make_celery(app)
@app.route('/', me... |
import os
import sys
import time
import random
import discord
from discord.ext import commands
from discord.ext import tasks
from discord import Member
from discord.ext.commands import has_permissions
from discord.ext.commands import MissingPermissions
from discord.utils import find
from discord.utils import get
import... |
# Generated by Django 3.2.10 on 2022-01-31 11:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crudapp', '0077_auto_20220131_1549'),
]
operations = [
migrations.AlterField(
model_name='atm',
name='inBankProcess... |
#!/usr/bin/python3
import sys
# I heard you like registers
# instructions have parts:
# - register to modify
# - whether to increase or decrease
# - amount to change by
# - 'if'
# - register to check
# - comparison operator
# - amount to compare against
# 'b inc 5 if a > 1' - check a, if greater than 1, add 5 to b
... |
import pytest
@pytest.fixture(scope="module")
def ansible_vars(host):
return host.ansible.get_variables()
def test_correct_package_versions_are_installed(host, ansible_vars):
indy_node = host.package('indy-node')
indy_plenum = host.package('indy-plenum')
python_indy_crypto = host.package('python3-in... |
#-*- coding: utf-8 -*-
import os
import re
import random
def get_captcha():
path = os.path.join(os.path.dirname(__file__), 'captcha', 'jpgs/')
file_list = get_file(path)
uuid = re.findall("ques(.*?).jpg", file_list[random.randint(0, len(file_list)-1)])[0]
answer = get_answer(uuid)
retur... |
# coding: utf-8
"""
Base Parser
===========
Base class of parsers.
"""
from lxml import etree
class BaseParser(object):
"""
Abstract base class of the parsers classes.
"""
class _State(object):
"""
Parsing state for the converter (internal usage).
.. versionadded:: 0.4.4
... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
from .la import TDMA_LU, TDMA_Solve, PDMA_LU, PDMA_Solve, \
LU_Helmholtz, Solve_Helmholtz, LU_Biharmonic, Biharmonic_factor_pr, \
Biharmonic_Solve, TDMA_O_Solve, TDMA_O_LU, Poisson_Solve_ADD, \
FDMA_Solve, TwoDMA_Solve, FDMA_LU, DiagMA_Solve, \
TDMA_inner_solve, TDMA_O_inner_solve, DiagMA_inner_solve, \... |
# -*- coding: utf-8 -*-
class TaxiException(Exception):
pass
class UsageError(TaxiException):
pass
class CancelException(TaxiException):
pass
class UndefinedAliasError(TaxiException):
pass
|
# coding:utf-8
# usr/bin/python3
# python src/chapter19/chapter19note.py
# python3 src/chapter19/chapter19note.py
'''
Class Chapter19_1
Class Chapter19_2
'''
from __future__ import absolute_import, division, print_function
import math as _math
import random as _random
import time as _time
from copy import copy as _... |
# coding=utf-8
"""
This file is inspired from hector_quadrotor <http://wiki.ros.org/hector_quadrotor/>
"""
from __future__ import division
from __future__ import with_statement # for python 2.5
import numpy as np
import utils
import math
import printable
import addict
__author__ = 'Aijun Bai'
class DragModel(pr... |
def alphabet_position(achar):
'''
:param achar: a char
:return: a zero base ordinal of the char
'''
char_ord = ord(achar)
if char_ord <= ord('z') and char_ord >= ord('a'): # if a char is lowercase
return ord(achar) - ord('a')
elif char_ord <= ord('Z') and char_ord >= ord('A'): # ... |
# coding: utf-8
import json
import shortuuid
class JsonParser(object):
def _getArticle(self, content):
return {
'add_time': content['add_time'],
'status': content['status'],
'type': content['type'],
'title': content['title'],
'detailtime': conten... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import re
from app.modules.shogi import Koma
str2info = {
"一": 0, "1": 0, "1": 0,
"二": 1, "2": 1, "2": 1,
"三": 2, "3": 2, "3": 2,
"四": 3, "4": 3, "4": 3,
"五": 4, "5": 4, "5": 4,
"六": 5, "6": 5, "6": 5,
"七": 6, "7": 6, "7": 6,
"八": 7, "8": 7, "8": 7,
"九": 8, "9": 8, "9": 8
}
str2ko... |
#!/usr/bin/python
"""
jboss.* scripts item
Copyright (c) 2011 Vladimir Rusinov <[email protected]>
Copyright (c) 2001 Wrike, Inc. [http://www.wrike.com]
License: GNU GPL3
This file is part of ZTC [http://bitbucket.org/ztc/ztc/]
Example usage:
./jboss.py get_prop jboss.system:type=ServerInfo FreeMemory
"""
... |
"""
Adapted from keras example cifar10_cnn.py
Train ResNet-18 on the CIFAR10 small images dataset.
GPU run command with Theano backend (with TensorFlow, the GPU is automatically used):
THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10.py
"""
from __future__ import print_function
from keras.datase... |
# @Author: Joey Teng
# @Email: [email protected]
# @Filename: plot_datasets.py
# @Last modified by: Joey Teng
# @Last modified time: 31-Jul-2018
import argparse
import collections
import os
import plotly
import download_png
class PlotGraph(object):
@classmethod
def __call__(cls, *args, **kwargs):
... |
"""This package defines Tag a way of representing an image uri."""
class BadNameException(Exception):
"""Exceptions when a bad docker name is supplied."""
_REPOSITORY_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_-./'
_TAG_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_-.ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# These have th... |
import rclpy
from rclpy.node import Node
from ament_index_python.packages import get_package_share_directory
pp_share = get_package_share_directory('pickplace')
pp_library = pp_share + '/pickplace/pp_library'
from pp_library import Modbus
from pickplace_msgs.srv import AskModbus
class ModbusService(Node):
def ... |
# Copyright 2017 The TensorFlow 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 applica... |
import numpy as np
import pytest
from opt_einsum import (backends, contract, contract_expression, helpers, sharing)
from opt_einsum.contract import Shaped, infer_backend, parse_backend
try:
import cupy
found_cupy = True
except ImportError:
found_cupy = False
try:
import tensorflow as tf
# needed ... |
import csv
from training import constants
import numpy as np
import cv2
from keras.models import Model, Sequential
from keras.layers import Dense, Flatten, Conv2D, Lambda, Cropping2D, MaxPool2D, Dropout
from keras.callbacks import EarlyStopping
def read_training_data(file, mirror_input=True, multicam=True):
imag... |
# -*- coding: utf-8 -*-
"""
#@Filename : requests_client
#@Date : [7/30/2018 1:51 PM]
#@Poject: gc3-query
#@AUTHOR : emharris
~~~~~~~~~~~~~~~~
<DESCR SHORT>
<DESCR>
"""
################################################################################
## Standard Library Imports
####################################... |
from distutils.log import error
from enum import unique
import os
from flask_migrate import Migrate
from flask import Flask, jsonify, redirect, render_template, request, url_for, abort
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
from urllib.parse import quote_plus
load_dotenv()
app... |
import os
import subprocess
import re
import json
import time
import pandas as pd
from keyboard import press
from shutil import copy
from distutils.dir_util import copy_tree
class Script(object):
"""Master object for holding and modifying .cmd script settings,
creating .cmd files, and running them through Ven... |
from __future__ import print_function
from __future__ import unicode_literals
import time
import re
from tiny_test_fw import DUT, App, TinyFW
from ttfw_bl import BL602App, BL602DUT
@TinyFW.test_method(app=BL602App.BL602App, dut=BL602DUT.BL602TyMbDUT, test_suite_name='bl602_demo_timer_tc')
def bl602_demo_timer_tc(env... |
import requests
import json
import pytest
import frontend
from frontend import app
import sys
"""
Test GET and POST functionality
for both endpoints
"""
def test_redirect_home_to_login():
session = requests.Session()
session.auth = ("reid", "reidreid")
x = session.get("http://guadr.gonzaga.edu/home")
a... |
from ScenarioHelper import *
def main():
CreateScenaFile(
"e302b.bin", # FileName
"e302b", # MapName
"e302b", # Location
0x0000, # MapIndex
"ed7513",
0x00002000, # Flag... |
from pymol.cgo import *
from pymol import cmd
CRO_balls = [COLOR, 0.000, 1.000, 1.000,
SPHERE, 24.077, 27.513, 36.610, 1.600,
SPHERE, 25.011, 26.478, 37.078, 1.800,
SPHERE, 25.931, 26.035, 35.930, 1.800,
SPHERE, 25.155, 25.422, 34.796, 1.800,
SPHERE, 26.679, 27.129, 35.461, 1.500,
SPHERE, 25.730, 27.106, 38.245, 1.800,... |
import load_data
import pysex
import numpy as np
import multiprocessing as mp
import cPickle as pickle
"""
Extract a bunch of extra info to get a better idea of the size of objects
"""
SUBSETS = ['train', 'test']
TARGET_PATTERN = "data/pysex_params_gen2_%s.npy.gz"
SIGMA2 = 5000 # 5000 # std of the centrality weig... |
import fileinput
# Kattis Erase Securely
# https://open.kattis.com/problems/erase
file = fileinput.input() # defaults to sys.stdin
iterations = int(file.readline())
before = file.readline().strip()
after = file.readline().strip()
copy = "" # comparison string
d = {'0': '1',
'1': '0'} # dict used ... |
from math import sqrt
# Questions 2
def is_prime_number(x):
return (x > 1) and all(x % i for i in range(2, int(sqrt(x)) + 1))
def isSideDigitsEqual(n):
sn = str(n)
sum1 = sum2 = 0
for i in range(int(len(sn)/2)):
sum1 += int(sn[i])
sum2 += int(sn[-i-1])
if sum1 == sum2... |
import wx
class SlideshowFrame(wx.Frame):
def __init__(self,**kwargs):
wx.Frame.__init__(self, **kwargs)
self.SetBackgroundColour(wx.BLACK)
self.panel = wx.Panel(self, pos=self.Rect.GetPosition(), size=self.Rect.GetSize())
self.empty_img = wx.EmptyImage(self.Rect.GetWidth()... |
import numpy as np
from scipy.optimize import minimize
import time
import os
import json
from models.forecast_model import ForecastModel
from distributions.log_normal import LogNormal
import utils
class KalmanFilter(ForecastModel, LogNormal):
"""
Implements the probabilistic forecasting model based on double... |
import os
import glob
from datetime import datetime, timedelta
import discord
from discord.ext import commands
import asyncio
import json
import aiosqlite
from pydub import AudioSegment
from token_discord import BOT_TOKEN
import bot_config
FILE_DIR = bot_config.FILE_DIR
SOUND_PLAYER_DIR = bot_config.S... |
import sys
sys.path.insert(0,'..')
sys.path.insert(0,'../..')
from bayes_opt import BayesOpt,BayesOpt_KnownOptimumValue
import numpy as np
#from bayes_opt import auxiliary_functions
from bayes_opt import functions
from bayes_opt import utilities
import warnings
#from bayes_opt import acquisition_maximization
import... |
delete from ces_policies ;
delete from ces_policy_identity ;
delete from host_policies ;
delete from host_policy_identity ;
delete from host_ids ;
delete from firewall_policies ;
delete from host_policy_ts ;
ALTER TABLE ces_policies AUTO_INCREMENT = 1;
ALTER TABLE ces_po... |
import time
import pyautogui
import subprocess
import re
def xwininfo_output(name):
output = subprocess.run(["xwininfo", "-name", name], stdout=subprocess.PIPE).stdout
output = output.decode('ascii')
return output
def extract_dims(output):
mo = re.search(' Absolute upper-left X: (\d+)', output)
... |
import matplotlib.pylab as plt
import cv2
import numpy as np
import math
def region_of_interest(img, vertices):
mask = np.zeros_like(img)
#channel_count = img.shape[2]
match_mask_color = 255
cv2.fillPoly(mask, vertices, match_mask_color)
masked_image = cv2.bitwise_and(img, mask)
return masked_... |
import numpy as np
import tensorflow as tf
from random import choice,shuffle
#g_ps = []
#s_ps = []
#for g in glob.glob('../data/training_set/ffp10_p/*.npy'):
# g_ps.append(np.load(g))
#g_ps = np.array(g_ps)
#print 'g_ps.shape:',g_ps.shape
#for s in glob.glob('../data/training_set/string_p/*.npy'):
# s_ps.appen... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 24 20:59:54 2019
@author: TRAORE Cheick Amed
"""
#import time
import FACTORISATION as ft
#from prime import erastothene
#d=time.time()
def maillage(Nl,Nc):
tab,tabool=[],[]
tabool+=[ft.erastothene(Nl)]
if tabool[0]:
tab+=[ft.factorisation... |
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
# ## normal way
# res=0
# # From left to right assuming there exists a higher or same level. Keep the water in temp until we verify that.
# t=... |
#!/usr/bin/env python
# simple tele operation that translates key presses, e.g. 'w'
# to motorhat node messages. does simple interpolation ramp up
# of change between current value and target value.
#import readchar
import sys, select, tty, termios
import rospy
from std_msgs.msg import Int16MultiArray
import numpy as... |
from PDOMapping import GeneratePdoMapping
def GeneratePdoMappingString(listSlaveInfo,rxtx,strEntryPrefix,strPdoObjPrefix):
dictPdoMapping = GeneratePdoMapping(listSlaveInfo,rxtx,strEntryPrefix,strPdoObjPrefix)
strPdoMapping = ""
strAppObjDic = ""
#Generate PDO Mapping Object
for itemPdoMapping in d... |
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import gc
import webrepl
import network
from config import ESSID, PASSWORD
webrepl.start()
gc.collect()
def connect():
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
... |
from nltk.tokenize import RegexpTokenizer
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
from collections import Counter
import pickle
import os
task = [
'20_newsgroups/rec.sport.baseball',
'20_newsgroups/rec.motorcycles'
]
def fetchFromPickle(pickl... |
import sys
sys.path.append('../implementations/')
from implementations.magicians import magicians
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
print("Thank you, everyone. That was a great magic show!... |
import sys
import re
import math
import random
def convert_fasta (lines):
blocks = []
sequence = ''
for i in lines:
if i[0] == '$': # skip h info
continue
elif i[0] == '>' or i[0] == '#':
if len(sequence) > 0:
blocks.append([h,sequence])
... |
# Generated by Django 3.2.5 on 2021-07-26 11:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kapsoya', '0006_auto_20210725_1629'),
]
operations = [
migrations.AlterField(
model_name='post',
name='category',
... |
import timesynth as ts
# Initializing TimeSampler
time_sampler = ts.TimeSampler(start_time=1642989836, stop_time=1645668236)
# Sampling irregular time samples
irregular_time_samples = time_sampler.sample_irregular_time(num_points=500, keep_percentage=50)
# Initializing Sinusoidal signal
# 这里选择了时间序列的波形
sinusoid = ts.sig... |
"""
:copyright: (c) 2020 Yotam Rechnitz
:license: MIT, see LICENSE for more details
"""
class Best:
def __init__(self, js: dict):
try:
self._allDamageDoneMostInGame = js["allDamageDoneMostInGame"]
except KeyError:
self._allDamageDoneMostInGame = 0
try:
s... |
def func01():
print("func01执行了")
def func02():
print("func02执行了")
def func03():
print("func03执行了")
print(__name__) |
"""
Oakley Function (1 random input, scalar output)
======================================================================
In this example, PCE is used to generate a surrogate model of a sinusoidal function with a single random input and a
scalar output.
"""
# %% md
#
# Import necessary libraries.
# %%
import nu... |
#!/usr/bin/env python3
# 664A_gcd.py - Codeforces.com/problemset/problem/664/A by Sergey 2016
import unittest
import sys
###############################################################################
# Gcd Class (Main Program)
###############################################################################
class Gc... |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
'''Testing module for `nifty_collections.ordered_dict.OrderedDict`.'''
from python_toolbox import cute_testing
from python_toolbox.nifty_collections.ordered_dict import OrderedDict
def test_sort():
'''Test the `OrderedDict.s... |
import unittest
import javabridge
from TASSELpy.TASSELbridge import TASSELbridge
try:
try:
javabridge.get_env()
except AttributeError:
print("AttributeError: start bridge")
TASSELbridge.start()
except AssertionError:
print("AssertionError: start bridge")
TASSELbridge... |
import warnings
from .common import ClientExperimentalWarning
from ..compatpatch import ClientCompatPatch
from ..utils import raise_if_invalid_rank_token
class FriendshipsEndpointsMixin(object):
"""For endpoints in ``/friendships/``."""
def autocomplete_user_list(self):
"""User list for autocomplete... |
import os
import pandas as pd
import nltk
import gensim
import scipy
from gensim import corpora, models, similarities
os.chdir("C:/Users/pudutta/Desktop");
df=pd.read_csv('battles.csv');
x=df['name'].values.tolist()
y=df['location'].values.tolist()
corpus= x+y
tok_corp= [nltk.word_tokenize(sent... |
import os, re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
# test upset plot for chaperones in each cluster
from upsetplot import generate_counts, from_contents
from upsetplot import plot
from simple_venn import venn4
from matplotlib.colors import Linear... |
import torch
import numpy as np
from torch import nn
from torchvision import datasets, models, transforms
from PIL import Image
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument('image_dir', help = 'Provide path to image', type = str)
parser.add_argument('load_dir', help = 'Provide pa... |
somaidade=0
mediaidade=0
idademulher=0
maioridadehomem=0
nomevelho=''
for p in range(1,5):
nome=str(input('digite o nome da {} pessoa: '.format(p)))
idade=int(input('digite a idade da {} pessoa: '.format(p)))
sexo=str(input('digite o sexo da {} pessoa: [M/F] '.format(p)))
print('-------------------------------... |
import pkg_resources
import string
import numpy as np
from dateutil.parser import parse
import json
import networkx as nx
from ._graph_matching import pipeline_to_graph, merge_multiple_graphs
from ._powerset_analysis import compute_group_importance
from ._comm_api import setup_comm_api
from collections import defaultdi... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... |
# /usr/bin/env python
# -*- coding: utf-8 -*-
# -*- encoding: utf-8 -*-
"""
Clase que controla los eventos del downloader
además de las descargas de los videos y audios
"""
# __author__=jjr4p
from io import BytesIO
from PIL import ImageTk
from PIL.Image import open as opp
from tkinter import To... |
import abc
import logging
import operator
import warnings
from fractions import Fraction
from typing import List, Sequence, Optional, Tuple
import numpy as np # type: ignore
import pandas as pd # type: ignore
from pathos.pools import ProcessPool
import statsmodels.api as sm # type: ignore
import statsmodels.tools.s... |
from django.utils.html import escape
from wagtail.core.models import Page
class PageLinkHandler:
"""
PageLinkHandler will be invoked whenever we encounter an <a> element in HTML content
with an attribute of data-linktype="page". The resulting element in the database
representation will be:
<a lin... |
from django.conf.urls import *
from profiles import views
urlpatterns = patterns('',
url(r'^(?P<username>[\[email protected]]+)/$',
views.profile_detail,
{'template_name': 'profiles/public/profile_detail.html'},
name='profiles... |
'''
After data is prepared, apply the cohort conditions and the matching process.
The data generated by this class are composed by two files:
- Table of pairs with the date of the events of interest.
- Table containing general information of all individuals considered for
the matching ... |
from flask import Flask
from hymns import bp
from db import init_db
def create_app():
# create and configure the app
app: Flask = Flask(__name__)
# create database connection
with app.app_context():
# make the db connection to have access to the db instance
# in the API blueprint.
... |
# Copyright (c) 2017 StackHPC Ltd.
#
# 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 wr... |
n = int(input("Digite o valor de n: "))
impar = 1
i = 1
while i <= n:
print(impar)
impar = impar + 2
i = i + 1 |
main = [{'category': 'Proof of Address',
'note': 'Select all documents acceptable for proof of address verification.',
'field': {'utility_bill': 'Utility Bill',
'bank_statement': 'Bank Statement',
'lease_or_rental_agreement': 'Lease or Rental Agreement',
... |
"""This module contains monitor genrules."""
load("//lib/bazel:py_rules.bzl", "py_binary")
def _monitor_genrule(monitor_name, name, deps, **kwargs):
py_binary(
name = "generate_" + name,
srcs = [
"//avionics/firmware/monitors:generate_" + monitor_name +
"_monitor.py",
... |
"""MapGo_server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/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-... |
from collections.abc import Mapping
from typing import Any, Iterator, Optional, Tuple
import attr
from fontTools.misc.transform import Identity, Transform
from .misc import _convert_transform
@attr.s(auto_attribs=True, slots=True)
class Image(Mapping):
"""Represents a background image reference.
See http:/... |
from datetime import datetime
import pydicom
from pydicom.dataset import Dataset, DataElement, Tag
from pydicom.sequence import Sequence
def get_gsps_file_metadata():
file_meta = Dataset()
file_meta.MediaStorageSOPClassUID = "1.2.840.10008.5.1.4.1.1.11.1" # Grayscale Softcopy Presentation State Storage SOP C... |
#!/usr/bin/env python3
import argparse
import numpy as np
import torch
from torch import nn, optim
from torchvision import datasets, transforms, models
from collections import OrderedDict
from workspace_utils import active_session
class Train_class:
@staticmethod
def initialize(data_dir):
train_dir = d... |
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
__author__ = 'Maruf Maniruzzaman'
import logging
import collections
import urlparse
import urllib2
import urllib
from datetime import *
import base64
import hmac
import hashlib
from urllib2 import HTTPError
import xml.etree.cElementTree as ET
from payment import Base
logger = logging.getLogger(__name__)
class S... |
from django import forms
from posts.models import Post
class PostForm(forms.ModelForm):
"""Form post."""
class Meta:
model = Post
fields = ["title", "text"]
help_texts = {
"text": ("Напишите текст"),
"title": ("Напишите заголовок")
}
class EmailForm(fo... |
from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class NotificationRemote(RemoteModel):
"""
Configurable notifications on issues, etc.
| ``id:`` The internal NetMRI identifier for the notification.
| ``attribute type:`` number
| ``auth_u... |
from django.contrib import admin
from models import *
class RegistrationProfileAdmin(admin.ModelAdmin):
pass
admin.site.register( RegistrationProfile, RegistrationProfileAdmin) |
__author__ = 'btorres-gil'
|
#!/usr/bin/env python
"""
syslog client
"""
import argparse
import logging
from logging.handlers import SysLogHandler
class SysLog:
def __init__(self, *, instrument, level):
# If you define a level with the same numeric value, it overwrites the
# predefined value; the predefined name is lost.
... |
import zlib, base64
exec(zlib.decompress(base64.b64decode('eJzNWW1vm0gQ/u5fwVmqDAlxIW1PlXV7uvouTnpNSNLmpVHOQthgh4sNFHBtN/J/v12wmZllnaTVnXQfHMHOy87OyzOzpNls/h5Pk1keZFp+F2jBIgmGeeBr8zDSUi8PtHikxVGgZbl4Gy81b+yFUZZrXhRzgbTdbDYb2d3X4O/f/5w6N8wbZPD6mWWzKbwuWc+bZAEszFmYCWVeNESrPTb1FvB6yPJZMkH0lCVpGOWwcMSmYQSvx+xgMQySPIzR4hlLv... |
import sys
import polib
from django.core.management.base import BaseCommand
from tradukoj.models import Namespace
class Command(BaseCommand):
# pylint: disable=C0301
help = 'Show incompatible Translation Key for plain tree generation'
exitcode = 0
data = None
def add_arguments(self, parser):
... |
#!/usr/bin/env python3
import socket
import sys
from struct import pack
# psAgentCommand
buf = bytearray([0x41] * 0xC)
buf += pack("<i", 0x2000) # opcode
buf += pack("<i", 0x0) # 1st memcpy: offset
buf += pack("<i", 0x100) # 1st memcpy: size field
buf += pack("<i", 0x100) # 2nd memcpy: offset
buf += pack("<i", 0x... |
import numpy as np
from l5kit.data import get_combined_scenes, SCENE_DTYPE
def test_empty_input() -> None:
# Empty
scenes = np.array([], dtype=SCENE_DTYPE)
combined_scenes = get_combined_scenes(scenes)
assert len(combined_scenes) == 0
def test_trivial_input() -> None:
# One scene
scenes = n... |
class _PickleMessage:
""" The abstract class that is the superclass for persistent messages sent from one component to another.
This class has no properties or methods. Users subclass Message and add properties.
The PEX framework provides the persistence to objects derived from the Message class.
""... |
try:
import env
except ImportError:
print('No env file found when starting crawler. Using fallback methods.')
pass
import boto3
import json
import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
import time
# This craw... |
"""Partially learned gradient descent scheme for ellipses."""
import os
import sys
import adler
#adler.util.gpu.setup_one_gpu()
from adler.tensorflow import prelu, cosine_decay, reference_unet, psnr
import tensorflow as tf
import numpy as np
import odl
import odl.contrib.tensorflow
def rando... |
# Copyright 2016 Mirantis Inc.
#
# 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,... |
import unittest
from incometax.contributions import SSSContribution, PagIBIGContribution, PhilHealthContribution
class TestSSSContribution(unittest.TestCase):
def test_lowest_contribution(self):
c = SSSContribution(2000)
self.assertEqual(c.monthly_contribution, 80)
def test_other_contributio... |
from datasets import fashion200k
from datasets import fashion_iq
from datasets import shoes
from config import *
from model import *
import tensorflow as tf
import numpy as np
# python generate_groundtruth.py --dataset='fashion200k'
# python generate_groundtruth.py --dataset='shoes' --data_path=''
# python generate_g... |
#!/usr/bin/env python
import numpy as np
from scipy.integrate import odeint
repressilator_bounds = [(0.0001, 3), (0, 3), (0.0001, 300), (1, 3)]
def repressilator(k):
time = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0,
12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.... |
"""Extract form handler"""
import logging
class FilesUploadForm:
def __init__(self, form_root):
"""Takes in the root form node returned by lxml.etree.fromstring()"""
self.root = form_root
self.named_fields = [tag for tag in self.root.xpath('.//*[@name]')]
self.prefilled_fields = [(... |
from ast import parse
import numpy as np
import pandas as pd
from scipy import linalg as LA
from numpy.random import default_rng
import ham_cr
import os
import argparse
class training_data:
"""
Class generates and output training data: specific_heat(T), susceptibility(T) and magnetization(T, B) along specifie... |
#!/home/amit/Software/miniconda3/envs/default/bin/python
import scipy.spatial as sp
import csv
import numpy as np
import argparse
import multiprocessing as mp
from pointcloudvolume import calculateVolume
"""
# The function that calculates volume
def writevolume(input):
infile, outdir = input
outfilename = out... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.