content stringlengths 5 1.05M |
|---|
"""
This module contains utility functions that enhance Matplotlib
in one way or another.
"""
__all__ = ['wigner_cmap', 'MidpointNorm', 'complex_phase_cmap']
import numpy as np
try:
import matplotlib as mpl
from matplotlib import cm
from matplotlib.colors import (Normalize, ColorConverter)
except:
cl... |
from random import randint
from time import sleep
itens = ('Pedra', 'Papel', 'Tesoura')
computador = randint(0, 2)
print('''\033[1;97;40mSuas opções:\033[49m
\033[92;40m[ 0 ] \033[93mPEDRA\033[49m
\033[92;40m[ 1 ] \033[93mPAPEL\033[49m
\033[92;40m[ 2 ] \033[93mTESOURA\033[49m''')
jogador = -1
while jogador < 0 or jogad... |
#!/usr/bin/python3
# coding: UTF-8
"""
フォトリフレクタクラス
「電子情報通信設計製図」新潟大学工学部工学科電子情報通信プログラム
All rights revserved 2019-2020 (c) Shogo MURAMATSU
"""
import pygame
class LFPhotoReflector:
""" フォトリフレクタクラス
フォトリフレクタの応答を模擬しています。
ノイズを加えたり応答をスケールするなど、
実機のフォトリフレクタに合わせた調整は、
この部分で行うとよいでしょう。
... |
from .pyutils.version import get_version
try:
# This variable is injected in the __builtins__ by the build
# process. It used to enable importing subpackages when
# the required packages are not installed
__SETUP__ # type: ignore
except NameError:
__SETUP__ = False
VERSION = (2, 0, 0, 'alpha', ... |
# Need to import the plotting package:
import matplotlib.pyplot as plt
from pylab import *
import numpy as np
import sys
FILENAME = sys.argv[1]
# Read the file.
f2 = open(FILENAME, 'r')
# read the whole file into a single variable,
# which is a list of every row of the file.
lines = f2.readlines()
f2.close()
# in... |
# coding: utf-8
from __future__ import unicode_literals
import logging
from wxpy.utils import handle_response
from .user import User
logger = logging.getLogger(__name__)
class Friend(User):
"""
好友对象
"""
@handle_response()
def set_remark_name(self, remark_name):
"""
设置或修改好友的备注名称... |
import _thread
import socket
import ubinascii, network
from network import LoRa
from LoRaMeshLibrary.ReceiveBuffer import ReceiveBuffer
class ThreadSafeLoraSocket:
def __init__(self):
self.socketLock = _thread.allocate_lock()
self.lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868)
self.lora_so... |
"""
# !/usr/bin/env python
-*- coding: utf-8 -*-
@Time : 2022/6/4 下午4:26
@Author : Yang "Jan" Xiao
@Description :
reference:https://github.com/dominickrei/MatchboxNet
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchaudio.transforms import MFCC
from utils.utils import padding
class... |
# Back end of cypher
import collections
import string
def moduleTest(name):
print("Hello World!")
print("Hello " + name + ", how old art thu?")
def encrypt(word, rotationnum):
if word and rotationnum != "":
alphLib = collections.deque(string.ascii_lowercase)
word = word.l... |
from datetime import date
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from wtforms import (
IntegerField,
PasswordField,
RadioField,
SelectField,
StringField,
SubmitField,
)
from wtforms.fields.html5 import DateField
from wtforms.validators import (
DataRequired,
... |
from flask import Flask
from flask import request
from flask import render_template
from flask import url_for
from flask import redirect
from flask import jsonify
from flask import session
from flask import flash
import hashlib, binascii
import sqlite3
app = Flask(__name__)
conn = None
# Get the current connection
d... |
"""Main entry point to mypy annotation inference utility."""
import json
from typing import List
from typing_extensions import TypedDict
from typewriter.annotations.infer import infer_annotation
from typewriter.annotations.parse import parse_json
from typewriter.annotations.types import ARG_STAR, ARG_STARSTAR
# Sch... |
import tensorflow as tf
import tensorflow_addons as tfa
from numpy import pi
def rotate_images(ds):
"""
Rotate images by 90, 180, and 270 degrees. Quadruple size of dataset.
Args:
ds (TensorFlow dataset): image dataset on which to perform the augmentation
Returns:
ds (TensorFlow datas... |
while True:
c = input('Digite o sexo [M/F] : ').strip().lower()
if c in 'mf':
break
else:
print('Erro! Digite uma letra válida! ')
print(f'Você selecionou o sexo "{c.upper()}"')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##################################################
#
# make_fsg.py
#
# This module takes a text file, marked up with
# units (e.g. w for word, m for morpheme) and ids
# and converted to IPA, and outputs a FSG
# file for processing by PocketSphinx.
#
######################... |
import torch
if __name__ == '__main__':
generator = torch.Generator(device="cpu")
generator.manual_seed(1904)
print(torch.randint(0, 2, (10,),generator=generator))
print(torch.randint(0, 2, (10,),generator=None)) |
import socket, os, time
import cv2, numpy
banner ="""
( * ) ( (
)\ ` ) /( ( )\ )\
(((_) ( ( ( )(_)) )( ( ((_) ((_)
)\___ )\ )\ ) (_(_()) (()\ )\ _ ... |
#Ex02
dic = {} #空のディクショナリを用意
while True: #無限に繰り返す
key = input("キーを入力してください: ")
if key == "END": #入力されたのは "END" か?
break
val = input("値を入力してください: ")
dic[key] = val #ディクショナリ(dic)にキーと値の組を格納(追加)
#すべてのキーいついてキーと値の組を表示
for k,v in dic.items():
print(k,v)
|
#!/usr/bin/env python
import astropy.io.fits as pyfits
import numpy as np
import sys
import datetime
import dateutil.parser
file=open("temperatures.txt","w")
skeys=["DAY","EXPNUM","TIME","HOUR","EXPREQ","BLUTEMP","REDTEMP","NIRTEMP","PLCTEMP1","PLCTEMP2","EXPSHUT","HARTL","HARTR","BLUHUMID","REDHUMID","NIRHUMID","... |
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data.sampler import SubsetRandomSampler
from torch.optim.lr_scheduler import StepLR
from .base_agent import BaseAgent
from .expert_dataset import ExpertDataset
from ..networks import ... |
import pickle
import time
import numpy as np
import copy
import os
import random
from constants import *
# data
# user_id \t os_name \t search_record1 \t search_record2 \t ...
# search_record: time_poiid_poiloc_poiname_poitype_userloc_network
"""
step3: make the final dataset files for transfer learning process and ... |
"""
Copyright 2020 Lightbend Inc.
Licensed under the Apache License, Version 2.0.
"""
import os
import pathlib
from setuptools import find_packages, setup
# Load version in akkaserverless package.
from setuptools.command.build_py import build_py
exec(open("akkaserverless/version.py").read())
PROTOBUF_VERSION = "mas... |
# coding: utf-8
"""
Xero Payroll AU API
This is the Xero Payroll API for orgs in Australia region. # noqa: E501
Contact: [email protected]
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
from xero_python.models import BaseModel
class SuperFunds(BaseModel):
"""NOTE: This ... |
from reef import create_app
application = create_app() |
class American:
@staticmethod
def printNationality():
print('America')
American.printNationality()
American().printNationality() |
#!/usr/bin/python
import gendsession
class MySubClassExample(gendsession.GEndSessionListenerBase):
def end_session_actions(self):
print "Performing user specified logout actions"
example = MySubClassExample()
example.start()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Chery pick of fasta sequences satisfying a query string in their header/name
import argparse
from Bio import SeqIO
def Parser():
the_parser = argparse.ArgumentParser(
description='Cherry pick fasta sequences')
the_parser.add_argument('--input', action='... |
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'Python Connector for Mongrel2',
'author': 'Zed A. Shaw',
'url': 'http://pypi.python.org/pypi/mongrel2-python',
'download_url': 'http://pypi.python.org/pypi/mongrel2-python',
'a... |
from src.renderers.teams import TeamsRenderer
# have to replace above with the football equivalents
class Scoreboard:
def __init__(self, canvas, data):
self.canvas = canvas
self.data = data
def render(self):
TeamsRenderer(self.canvas, self.data).render()
# NetworkErrorRenderer(self.canvas, self.da... |
#!/usr/bin/env python
# Copyright 2012 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Runs a command with optional isolated input/output.
Despite name "run_isolated", can run a generic non-isolated command ... |
from adminapi import _api_settings
from adminapi.request import send_request
API_CALL_ENDPOINT = '/call'
class ApiError(Exception):
pass
class ExceptionManager(object):
def __init__(self):
self._cache = {}
def __getattr__(self, attr):
if attr == 'ApiError':
return ApiError
... |
# Import packages needed:
import visa
import numpy as np
import sys
import warnings
import time
import matplotlib.pyplot as plt
import multiprocessing as multi
import os
import time
import pandas as pd
# Import our classes
from sr_operators import *
from adv_op import *
import measure
import maths_op
from Setup impo... |
mse = np.zeros((max_order + 1))
for order in range(0, max_order + 1):
X_design = make_design_matrix(x, order)
# Get prediction for the polynomial regression model of this order
y_hat = X_design @ theta_hats[order]
# Compute the residuals
residuals = y - y_hat
# Compute the MSE
mse[order] = np.mean(res... |
"""With this script users can download the final HTML dataset from Internet Archive.
This is a script for downloading whole HTML dataset which is
hosted on Internet Archive. Note that the whole dataset is 7TB
compressed. If the script fails while execution, it can be
safely restarted. The internetarchive doesn't re-do... |
from flask_jwt_extended import get_jwt_identity
from datetime import datetime
from src.users.controller import ( conn, cur)
class QuestionsController:
"""Question controller interfaces with the database."""
def __init__(self):
"""Initializes the questions controller class."""
conn.create_ques... |
"""
Copyright (c) 2020 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WI... |
class ArbitrageConfig(object):
def __init__(self, options={}):
self.name = options['name']
self.base_coin = options['base_coin']
self.quote_coin = options['quote_coin']
self.symbol = f"{self.base_coin}/{self.quote_coin}"
self.one_to_two_pure_profit_limit = float(options['one_... |
__author__ = 'Bohdan Mushkevych'
from io import TextIOWrapper
from typing import Union
from grammar.sdplParser import sdplParser
from parser.abstract_lexicon import AbstractLexicon
from parser.data_store import DataStore
from parser.projection import RelationProjection, FieldProjection, ComputableField
from schema.sd... |
"""Module with utitlity functions."""
import json
import numpy as np
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if np.issubdtype(type(obj), np.integer):
return int(obj)
if np.issubdtype(type(obj)... |
import os
from pathlib import Path
from pelican import signals
# Function extracted from https://stackoverflow.com/a/19308592/7690767
# Las tres funciones que le dan toda la funcionalidad al plugin
def get_filepaths(directory, extensions=[], ignores=[]): # ignore es una lista de archivo que se deben ignorar
file_p... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
''' Copyright 2012 Smartling, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/license... |
import glob
import matplotlib.pyplot as plt
# from Gnn_Models.model import GCN
# from Gnn_Models import model
import numpy as np
import torch
import torch.nn.functional as F
from sklearn.ensemble import RandomForestRegressor
from torch_geometric.nn import GCNConv
from torch_geometric.transforms import RandomLinkSplit
... |
from fastapi import FastAPI, Depends
import fastapi_simple_security
app = FastAPI()
@app.get("/unsecured")
async def unsecured_endpoint():
return {"message": "This is an unsecured endpoint"}
@app.get("/secure", dependencies=[Depends(fastapi_simple_security.api_key_security)])
async def secure_end... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from ceasiompy.utils.moduleinterfaces import CPACSInOut, AIRCRAFT_XPATH
# ===== RCE integration =====
RCE = {
"name": "PyTornado",
"description": "Wrapper module for PyTornado",
"exec": "pwd\npython runpytornado.py",
"author": "Aaron Dettmann",
"emai... |
# -*- coding: utf-8 -*-
# create MC/MCV files from curve data
#
import femagtools
import logging
import os
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(message)s')
mcvData = [
dict(curve=[dict(
bi=[0.0, 0.09, 0.179, 0.267, 0.358,
0.45, 0.543, 0.6334, 0.727,... |
"""
Implement numerical maxabs scaler.
"""
from typing import Any, Union
import dask.dataframe as dd
class MaxAbsScaler:
"""Max Absolute Value Scaler for scaling numerical values
Attributes:
name
Name of scaler
maxabs
Max absolute value of provided data column
"""
... |
"""
This module provides versioning informations.
from SlackLogger.version import get_version
__version__ = get_version()
"""
VERSION = '2.5.0'
def get_version():
"""
Return package version value.
:return: VERSION value, obviously
:rtype: string
"""
return VERSION
|
import os
import unittest
import apiritif
from apiritif.thread import get_index
reader_1 = apiritif.CSVReaderPerThread(os.path.join(os.path.dirname(__file__), "data/source0.csv"))
def log_it(name, target, data):
log_line = "%s[%s]-%s. %s:%s:%s\n" % (get_index(), target, name, data["name"], data["pass"], data["... |
# Copyright 2020 Supun Nakandala. 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 law... |
import numpy as np
import pandas as pd
import pytest
from pandas.api.types import is_numeric_dtype
from scipy import sparse
import sklearn.datasets
import sklearn.model_selection
from sklearn.utils.multiclass import type_of_target
from autosklearn.data.target_validator import TargetValidator
# Fixtures to be use... |
#
# Copyright 2017 Pixar Animation Studios
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
... |
import RPi.GPIO as GPIO
from time import sleep
# Direction pin from controller
DIR = 10
# Step pin from controller
STEP = 8
# 0/1 used to signify clockwise or counterclockwise.
CW = 1
CCW = 0
# Setup pin layout on PI
GPIO.setmode(GPIO.BOARD)
# Establish Pins in software
GPIO.setup(DIR, GPIO.OUT)
GPIO.setup(STEP, GPI... |
import check50
import numpy as np
import requests
# random seed generated and then passed to TestBank to prevent cheating
ui32 = np.iinfo(np.uint32)
seed = np.random.randint(1, ui32.max)
params = {'seed': seed, 'solution': True}
r = requests.get('https://testbank.roualdes.us/ey0C', params=params)
sol = r.json()['solu... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Rt(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param value: {"type": "string", "description": "VPN extended community", "format": "string-rlx"}
:param DeviceProxy: The device proxy for REST operations and... |
#!/usr/bin/env python
"""
Pandoc filter to convert divs with class="theorem" to LaTeX
theorem environments in LaTeX output, and to numbered theorems
in HTML output.
"""
from pandocfilters import toJSONFilter, RawBlock, Div
theoremcount = 0
def latex(x):
return RawBlock('latex',x)
def html(x):
return RawBlock('... |
import re
from collections import defaultdict
def day19(fileName):
substitutionRegex = re.compile(r"(.+) => (.+)")
substitutions = defaultdict(list)
with open(fileName) as infile:
for inputLine in (line.strip() for line in infile):
match = substitutionRegex.match(inputLine)
... |
# -*- coding: utf-8 -*-
'''
Git Fileserver Backend
With this backend, branches and tags in a remote git repository are exposed to
salt as different environments.
To enable, add ``git`` to the :conf_master:`fileserver_backend` option in the
master config file.
As of the :strong:`Helium` release, the Git fileserver ba... |
import numpy as np
import pytest
from numpy import testing as npt
from ifg.calculator import IfgCalculator
from ifg.units_converter import convert_theta_to_temperature
COMPLICATED_MESH = (
[3.0, 5.0],
[5.0, 10.0, 15.0],
np.array(
[
[4.909741, 8.182902],
[3.092943, 5.154905]... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
class Sink:
def write(self, key, obj):
raise Exception('Virtual function is not overriden')
def flush(self):
raise Exception('Virtual function is not overriden')
class CompositeSink(Sin... |
#
# PySNMP MIB module AcPerfMediaGateway (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AcPerfMediaGateway
# Produced by pysmi-0.3.4 at Wed May 1 11:33:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
from jumpscale import j
import dns.resolver
import time
def test(geodns_install=False, dnsresolver_install=True, port=3333, tmux=True):
# start geodns instance(this is the main object to be used it is an
# abstraction of the domain object)
prefab = j.tools.prefab.local
geodns = prefab.apps.geodns
... |
from blitzcrank import Blitzcrank
b = Blitzcrank("RGAPI-this-doesnt-really-matter","euw1")
champion_id = "222"
champion_name = b.champion.by_id(champion_id)["name"]
item_id = "350"
item_name = b.item.by_id(item_id)["name"]
print(champion_name, item_name) |
class Scope:
__scope_id = 0
def __init__(self, data=None):
self.__data = data or {}
self.__data['id'] = Scope.__scope_id
Scope.__scope_id += 1
def __get__(attr): return lambda self: self.__data.get(attr)
def __set__(attr):
def _set(self, value):
if se... |
from kicker.SymbolMapper import SymbolMapper
class ConsoleView(object):
def __init__(self):
self.header = "Current user input state:"
self.pattern = "{0: <30}{1} {2} {3} {4}"
self.mapper = SymbolMapper()
def renderView(self, inputs):
mapped = self.mapper.inputs2sym... |
#$Id$
from books.model.PageContext import PageContext
class ContactList:
"""This class is used to create an object for contact list."""
def __init__(self):
""" Initialize contacts list and page context."""
self.contacts = []
self.page_context = PageContext()
def set_contacts(self,... |
from __future__ import absolute_import
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from common.utils import encapsulate
from permissions.models import Permission
from .api import get_job_list
from .permissions impo... |
from decimal import Decimal
import pytest
from tartiflette.scalar.builtins.int import ScalarInt
@pytest.mark.parametrize(
"value,should_raise_exception,expected",
[
(None, True, "Int cannot represent non-integer value: < None >."),
(True, False, 1),
(False, False, 0),
("", Tr... |
"""Test that `if` in formatted string literal won't break Pylint."""
# pylint: disable=missing-docstring, pointless-statement, using-constant-test
f'{"+" if True else "-"}'
if True:
pass
elif True:
pass
|
#*************************************************************************************************************************
#import the required Python libraries. If any of the following import commands fail check the local Python environment
#and install any missing packages.
#******************************************... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from math import ceil, sqrt
from PIL import Image
MODES = ('palette', 'grayscale')
PALETTE = [
0x000000, # 0 — black
0x000080, # 1 — maroon
0x008000, # 2 — green
0x008080, # 3 — olive
0x800000, # 4 — navy
0x800080, # 5 — pur... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2010 Doug Hellmann. All rights reserved.
#
"""Show the native byte order.
"""
#end_pymotw_header
import sys
print sys.byteorder
|
async def leaves(voice_client):
await voice_client.disconnect()
|
# Generated by Django 3.1 on 2021-10-26 22:07
from django.db import migrations, models
from django.contrib.auth.models import User
import reversion
ADMIN_USERNAME = 'biobankadmin'
def create_buffy_coat_sample_kind(apps, schema_editor):
SampleKind = apps.get_model("fms_core", "SampleKind")
admin_user = User.o... |
"""
Author : Robin Phoeng
Date : 21/06/2018
"""
class Bar:
"""
A stress bar in the Fate SRD
box indexes start at 1
"""
def __init__(self,name):
self.name = name
self.boxes = []
def add_box(self,box):
"""
Adds a new box to the bar
... |
#!/usr/bin/python
"""Script to add, update, list or remove the grid application.
Usage::
grid_admin.py [add|update|list|remove|show-xml]
* add: adds or updates the grid application
* update: updates the application (assumes it is already loaded)
* list: lists all loaded applications
* remove: removes the grid a... |
"""Special rectangles."""
__all__ = [
"ScreenRectangle",
"FullScreenRectangle",
"FullScreenFadeRectangle",
"PictureInPictureFrame",
]
from manim.utils.deprecation import deprecated
from .. import config
from ..constants import *
from ..mobject.geometry import Rectangle
from ..utils.color import BLAC... |
# Copyright 2018 MLBenchmark Group. 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... |
#! /usr/bin/env python
## include packages
import commands
import subprocess
import sys
import signal
import time
import xml.etree.cElementTree as ET ## parsing the xml file
from run_util import print_with_tag
#====================================#
## config parameters and global parameters
## default mac set
mac_... |
# ============================================================== #
# Fusnet eval #
# #
# #
# Eval fusnet with processed dataset in tfrecords fo... |
from config.main import *
from pymongo import MongoClient
import functions
import argparse
client = MongoClient(host=DATABASE['HOST'], port=DATABASE['PORT'], Connect=False)
#client.jury.authenticate(DATABASE['USER'], DATABASE['PASSWORD'])
db = client.jury
def init(parse):
from classes.initialize import Initializ... |
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import torch
from parameterized import parameterized
from tests import utils
class SimpleFloorDivideModule(torch.nn.Module):
def __init__(self, inplace=False):
super(SimpleFloorDivideModule, self).__init__... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import argparse
import facenet
import lfw
import os
import sys
import math
from sklearn import metrics
from scipy.optimize import brentq
from scipy import interpolate
... |
from pykka import ThreadingActor, Timeout
import logging
from util.message_utils import Action
class Consumer(ThreadingActor):
def __init__(self, producers, job, manager):
super(Consumer, self).__init__()
self.producers = producers
self.job = job
self.id = job.id
self.logg... |
TETRIMINO_T1 = ((0, 0, 0), \
(0, 1, 0), \
(1, 1, 1),)
TETRIMINO_T2 = ((0, 1, 0), \
(0, 1, 1), \
(0, 1, 0),)
TETRIMINO_T3 = ((0, 0, 0), \
(1, 1, 1), \
(0, 1, 0),)
TETRIMINO_T4 = ((0, 1, 0), \
... |
from flask import request
from flask import Blueprint
from flask_restful import Api, Resource
from eventapp.models import db, Event, Admin, User, EventSignup
from eventapp.routes.response import SUCCESS, FAILURE
from flask import jsonify, make_response
from eventapp.services.signature_util import generate_signature
fro... |
# send json by request and received
import requests
from flask import request, Response
r = requests.post('http://httpbin.org/post', json={"key": "value"})
r.status_code
r.json()
# receive json in flask
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
if request.is_json():
... |
# -*-coding:UTF-8-*-
from scripts.logger.lemon_logger import Logger
from scripts.tools.mutator_selection_logic import MCMC, Roulette
import argparse
import sys
import ast
import os
import numpy as np
from itertools import combinations
import redis
import pickle
from scripts.tools import utils
import shutil
import re
im... |
class gamer():
def __init__(self):
self.position=(80,80)
self.face = 'S'
self.stone_getable= []
self.stone_ungetable=[]
self.stones=[]
self.have_stones=0
self.graph=None
self.tree =[]
self.tree_ungetable =[]
self.tree_getable =[]
... |
# Pratice 41. Parsing a Data File
# Input:
# File name : parsing_a_data_file_input
# Output:
# Last First Salary
# ------------------------
# Ling Mai 55900
# Johnson Jim 56500
# Jones Aaron 46000
# Jones Chris 34500
# Swift Geoffrey 14200
# Xiong Fong 65000... |
from pathlib import Path
from autoit_ripper import AutoItVersion, extract # type: ignore
from karton.core import Karton, Resource, Task
from malduck.yara import Yara # type: ignore
from .__version__ import __version__
from .extract_drop import extract_binary
class AutoItRipperKarton(Karton):
"""
Extracts ... |
"""
Provide constants for hostdb endpoint.
"""
ALL_URL = '/hostdb/all'
ACTIVE_URL = '/hostdb/active'
HOSTS_URL = '/hostdb/hosts/'
|
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils.spectral_norm as SpectralNorm
def get_norm(norm_type, size):
if(norm_type == 'batchnorm'):
return nn.BatchNorm2d(size)
elif(norm_type == 'instancenorm'):
return nn.InstanceNorm2d(size)
class N... |
TITLE = "chip-8"
ZOOM = 10
SCREEN_WIDTH = 64
SCREEN_HEIGHT = 32
CLOCK_SPEED = 1200
TIMER_SPEED = 60
BG_COLOR = (0xa0, 0xe6, 0xfa)
FG_COLOR = (0xff, 0xff, 0xff)
|
#!/usr/bin/python3
import sys
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
def bubble(arr):
count_swap = 0
for num in range(len(arr) - 1, 0, -1):
for i in range(num):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from midgard.server.models.base_model_ import Model
from midgard.server import util
class GPUMaxClockInfo(Model):
"""NOTE: This class is auto generated by the swa... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
DESCRIPTION="""
Converts an OBJ file to the internal model file.
Examples:
1. python3 models.py Warehouse.obj Warehouse.model
2. python3 models.py Warehouse.obj Warehouse.obj --replace-ext
"""
EPILOG = """
Debugging
---------
For the debugging, please, run the sc... |
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
import shutil
import random
import string
import re
import json
import socket
"""
Time Helper
"""
def today(form='%Y-%m-%d'):
return datetime.datetime.now().strftime(form)
def days_ago(days=0, form='%Y-%m-%d'):
return (datetime.... |
# coding=utf-8
'''
Problem 52
12 September 2003
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
'''
import euler
for i in range(1, 10**6):
va... |
""" To Read pickle files from Corpus """
import nltk
import pickle
from nltk.corpus.reader.api import CorpusReader
from nltk.corpus.reader.api import CategorizedCorpusReader
doc_pattern = r'(?!\.)[a-z_\s]+/[a-f0-9]+\.json'
pkl_pattern = r'(?!\.)[a-z_\s]+/[a-f0-9]+\.pickle'
cat_pattern = r'([a-z_\s]+)/.*'
... |
import cv2
import numpy as np
from keras.optimizers import SGD
import keras.backend as K
import keras
import pylab as plt
from keras.datasets import cifar10
from densenet121 import DenseNet
# 数据的导入和预处理
(x_train,y_train),(x_test,y_test)=cifar10.load_data()
y_test=keras.utils.to_categorical(y_test,10)
# 模型已经训练好了,将训练好的... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.