content stringlengths 5 1.05M |
|---|
def function(x, y, food="spam"):
print(food)
function(1, 2)
# The argument '1' is passed in to parameter x, the argument '2' is passed in
# to y, no argument is passed in to the parameter food (so the default is
# used).
function(3, 4, "egg")
# "egg" passed in to parameter food
"""
In case the argument is passed ... |
import json
from datetime import datetime
from flask import request, Response, Blueprint, jsonify
from flask_login import current_user
from c3bottles import app, db
from c3bottles.model.drop_point import DropPoint
from c3bottles.model.report import Report
from c3bottles.model.visit import Visit
bp = Blueprint("api"... |
import argparse
import numpy as np
from hdf5zarr import HDF5Zarr
import h5py
import time
parser = argparse.ArgumentParser()
parser.add_argument('--selection', type=lambda s : eval('np.index_exp['+s+']'), default=':')
parser.add_argument('--dsetname', type=str, default='')
parser.add_argument('--url', type=str, defaul... |
from benchmarks.moo_bb_func import get_bb_func
from entmoot_moo.optimizer import Optimizer
# iterate through different problem names to
for bb_name in ['Battery','Windfarm']:
bb_func = get_bb_func(bb_name)
# we consider 25 different rnd states in this example
for itr in range(25):
seed = 101 + itr... |
"""
Script to generate random user data in RWTHOnline .csv format
Author: L. Lamm (lamm@ifam.rwth-aachen.de)
"""
from miraculix.participant import Participant
from miraculix.utils import write_csv
"""Generate list of participants"""
participant_list = Participant.generate_random_participant_list(50)
"""Arrange Data ... |
# -*- coding: utf-8 -*-
MOCK_TEXT_1 = (
"The seething sea ceaseth and thus the seething sea sufficeth us.")
MOCK_TEXT_2 = (
"She sells sea shells on the sea shore. "
"The shells she sells are sea shells, I'm sure. "
"For if she sells sea shells on the sea shore "
"Then I'm sure she sells sea shore s... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017-2020 Richard Hull and contributors
# See LICENSE.rst for details.
"""
Test helpers.
"""
import platform
from pathlib import Path
import pytest
from PIL import ImageChops, ImageFont
from unittest.mock import mock_open
rpi_gpio_missing = f'RPi.GPIO is not supported on thi... |
import collections
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
d = collections.defaultdict(list)
for i in strs:
d["".join(sorted(i))].append(i)
return list(d.values())
if __name__ == "__... |
from DataBases.DataBaseClass import Database
from datetime import datetime
class UserInfoDatabase(Database):
"""Stores information on users including currency, user ids, and items"""
def __init__(self, tablename='UserInformation'):
super().__init__(filename='UserInfo.db')
self.tablenam... |
# encoding=UTF-8
from __future__ import unicode_literals
from django.apps import AppConfig
class FoodConfig(AppConfig):
name = 'food'
verbose_name = '食物'
|
import json, os, sys
from pprint import pprint as print
from datetime import datetime
from datetime import date, timedelta
from collections import Counter
from collections import OrderedDict
import openpyxl
from openpyxl.worksheet.dimensions import ColumnDimension, DimensionHolder
from openpyxl.utils import get_column... |
"""Document fields."""
import abc
import re
from datetime import datetime
from decimal import Decimal
import bson.errors
from bson import ObjectId, Decimal128
from aioodm.errors import ValidationError, StopValidation
from aioodm.utils import _Empty, import_class
__all__ = ['AnyField', 'StrField', 'EmailField', 'In... |
# Players management module
#
import hashlib
import stores
from matchupsv2 import now
salt = 'superhero'
def userhash(name):
hash = hashlib.sha256()
hash.update(salt + name)
return hash.hexdigest()
def pswhash(name, psw):
hash = hashlib.sha256()
hash.update(salt + name + psw)
return hash.he... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
import numpy as np
import pytest
from astropy import units as u
from astropy.coordinates import SkyCoord, ICRS, Galactic, FK4, FK5, Longitude
asdf = pytest.importorskip('asdf')
from asdf.tests.helpers import assert_roundtrip_tre... |
"""
This program takes in the a url to an index.m3u8 file
and it will return a modified version of that file
that vlc media player can use
"""
import sys
import requests
def outputBuffer(buffer, outputFile):
buffer = buffer + '\n'
outputFile.write(buffer)
buffer = ""
return bu... |
import time
import random
def timeit(func, *args):
t1 = time.time()
ret = func(*args)
cost_time = (time.time() - t1) * 1000
print("cost time: %sms" % cost_time)
try:
randint_wrap = random.randint
except:
# micropython
def randint_wrap(a, b):
return a + random.getrandbits(32) % (b-a)
def rand_int... |
# Sneek peek on the results.
# Importing sentiment_mod module and then testing on some feeds and statements.
import sentiment_mod as senti
print(senti.sentiment("He is an incapable person. His projects are totally senseless."))
print(senti.sentiment("This movie was awesome! The acting was great, plot was wonderful !"... |
from typing import Optional
import streamlit as st
import requests
import json
import spacy_streamlit
from spacy_streamlit.util import get_svg
from spacy import displacy
spacy_model = "en_core_web_sm"
def main():
# Applying styles to the buttons
st.markdown("""<style>
.st-eb {
... |
from filelist import filelist
def functionlist(file_path):
with open(file_path) as fp:
file_lines = fp.read().splitlines()
return [(line, index) for index,line in enumerate(file_lines) if line.split(' ', 1)[0] == 'function']
def list_functionlist(list_file_path):
return [(file_path, functionlist... |
import argparse
import os
import json
import numpy
import PIL.Image
from . import pidfile, tally, nethook, zdataset
from . import upsample, imgviz, imgsave, proggan, segmenter
def main():
parser = argparse.ArgumentParser(description='quickdissect')
parser.add_argument('--outdir', type=str, default='results')
... |
from PyQt5 import uic, QtWidgets
from datetime import date
import win32com.client as win32
from openpyxl import Workbook
import pandas as pd
class SistemaGeral:
### INICIO
def __init__(self):
### SETUP LAYOUT APP
# Chamando sistema Layout
app = QtWidgets.QApplication([])
# Lay... |
import tkinter as tk
class WelcomePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
font13 = "-family {Tw Cen MT} -size... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''abcat.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Apr 2018
License: MIT - see the LICENSE file for the full text.
This contains functions to interface with astrobase checkplots, lcproc object
catalogs and generate useful files and database tables for use with the... |
# --------------
# import the libraries
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
import warnings
warnings.filterwarnings('ignore')
# Code starts here
df = pd.read_csv(path)
print(df.head())
X = df.drop(['insuranceclaim'],1)
y = df['insuranceclai... |
from enum import Enum
class Months(Enum):
janeiro = "Janeiro"
fevereiro = "Fevereiro"
marco = "Março"
abril = "Abril"
maio = "Maio"
junho = "Junho"
julho = "Julho"
agosto = "Agosto"
setembro = "Setembro"
outubro = "Outubro"
novembro = "Novembro"
dezembro = "Dezembro"
|
__all__ = ["LightningModelAdapter"]
import pytorch_lightning as pl
from icevision.imports import *
from icevision.metrics import *
class LightningModelAdapter(pl.LightningModule, ABC):
def __init__(self, metrics: List[Metric] = None):
super().__init__()
self.metrics = metrics or []
def accum... |
import os
import socket
import struct
import sys
import threading
import time
class Driver(object):
def __init__(self, topo):
"""
constructor
"""
self.topo = topo
self.host = '192.168.10.100' # driver ip address
self.port = 4747 # port number must match the one in router.py
self.hosts = self.populate... |
print(42 if False == False else 777)
|
import numpy as np
from cereal import log, messaging
from common.filter_simple import FirstOrderFilter
from common.numpy_fast import interp, clip, mean
from common.realtime import DT_MDL
from selfdrive.hardware import EON, TICI
from selfdrive.swaglog import cloudlog
from common.params import Params
from decimal import ... |
"""
File utilities
"""
import sys
import os
from os.path import join
import stat
from glob import glob
from pprint import pprint
import shutil
import distutils
import pathlib
from pathlib import Path
import json
import csv
import pickle
import threading
from queue import Queue
import time
import logging
import itertoo... |
# from downscale import utils
# from downscale.downscale import * |
from clearbit.resource import Resource
from clearbit.error import (ParamsInvalidError)
class NameToDomain(Resource):
endpoint = 'https://company.clearbit.com/v1/domains'
@classmethod
def find(cls, **options):
return cls.get('/find', **options)
|
""""Unit tests for the outbox."""
import unittest
from unittest.mock import patch
from models.metric_notification_data import MetricNotificationData
from models.notification import Notification
from outbox import Outbox
class OutboxTestCase(unittest.TestCase):
"""Unit tests for the outbox."""
def setUp(sel... |
# %-*- coding: utf-8 -*-
"""
=============================================================================
Title : Compressive sensing framework
Project : Simulation environment for BckTrk app
File : CSNN_Framework.py
-----------------------------------------------------------------------------
... |
from brownie import reverts
def test_constructor(SwapStrategy, vault, gov, keeper):
strategy = gov.deploy(SwapStrategy, vault, 2400, 1200, 500, 600, keeper)
assert strategy.vault() == vault
assert strategy.pool() == vault.pool()
assert strategy.baseThreshold() == 2400
assert strategy.limitThreshol... |
import sys
import process_sequence_fasta as pro_seq_fasta
import sequence2vector as s2v_tools
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from keras.layers import LSTM, Dense
from keras.models import Sequential
from keras.layers import Embedding
from keras.preprocessing import ... |
# recursive approach to find the number of set
# bits in binary representation of positive integer n
def count_set_bits(n):
if (n == 0):
return 0
else:
return (n & 1) + count_set_bits(n >> 1)
# Get value from user
n = 41
# Function calling
print(count_set_bits(n... |
import numpy as np
from keras import backend as K
from keras.models import Model
from keras.layers import Input, Lambda
def euclidean_distance(vects):
x, y = vects
sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)
return K.sqrt(K.maximum(sum_square, K.epsilon()))
def contrastive_los... |
from argparse import ArgumentParser
from enum import Enum
from more_itertools import sliced
from pathlib import Path
from robber_baron import Bot
class Difficulty(Enum):
EASY = "easy"
MEDIUM = "medium"
DIFFICULT = "difficult"
INSANE = "insane"
def __str__(self) -> str:
return self.value
... |
from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, EqualTo, Length
# Set your classes here.
class RegisterForm(Form):
name = TextField(
'User Name', validators=[DataRequired(), Length(min=6, max=25)]
)
email = TextField(
'E... |
from iap2022.utils.coordinate_transformer import CoordinateTransformer
from iap2022.utils.coordinate_transformer import InternalCoordinate, InternalCoordinateAndOrientation
from iap2022.utils.functional import get_bonded_atoms
|
from django.conf.urls import patterns, url
urlpatterns = patterns(
'',
url(r'^admin/inspect/browse/$', 'upy.contrib.inspect.views.browse', name='inspect_browse'),
)
|
import tensorflow as tf
import numpy as np
import gym
class Config(object):
input_size = None
output_size = None
num_layer = 2
num_hidden = 128
dtype = tf.float32
epsilon = 0.2
c1 = 0.5
c2 = 0.01
gamma = 0.99
normalize_advantages = True
learning_rate = 3e-4
epoch = 10
... |
'''
Created on Jan 3, 2022
@author: immanueltrummer
'''
import argparse
import codexdb.catalog
import codexdb.code
import codexdb.engine
import contextlib
import json
import os
import openai
import pandas as pd
import time
def extract_samples(catalog, path_to_results):
""" Extracts completion examples from prior ... |
import setuptools
# -$ python setup.py sdist bdist_wheel
# -$ twine upload dist/* -u VicWang -p PYPI******
setuptools.setup(
name="leaptask",
version="2020.4.2.14",
author="Vic Wang",
author_email="305880887@qq.com",
description='leap task',
long_description="leap tasks",
long_description_... |
import sys
import os.path
sys.path.insert(1,
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir,)))
from graph.arango_utils import aql_query, connect_to_mim_database
from graphviz import Digraph
def main():
db = connect_to_mim_database()
# query = f'''
# FOR m IN Members
#... |
#from django.urls import path
from django.conf.urls import url, include
from django.conf.urls import url
from . import views
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers
urlpatterns = [
url('', views.homePageView, name='home')
]
'''
router = routers.... |
# Copyright 2020, 2021 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... |
"""Module for server."""
import logging
import os
from typing import Any
from aiohttp import web
from aiohttp_middlewares import cors_middleware, error_middleware
from dotenv import load_dotenv
from .routes import (
delete_ontology,
get_ontology,
get_ontology_type,
get_slash,
ping,
put_ontolog... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import functools
import numpy as np
import dask.array as da
import xarray as xr
import skimage as ski
from scipy.ndimage.filters import convolve
#import bottlenack as bn
def view(offset_y, offset_x, size_y, size_x, step=1):
"""
Calculates views for windowes operations... |
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
apptrace_URL_PATTERNS = ['top50']
apptrace_TRACE_MODULES = ['models.py', 'app.py', 'views.py']
def webapp_add_wsgi_middleware(app):
from google.appe... |
"""Python setup.py for project_name package"""
import io
import os
from setuptools import find_packages, setup
def read(*paths, **kwargs):
"""Read the contents of a text file safely.
>>> read("project_name", "VERSION")
'0.1.0'
>>> read("README.md")
...
"""
content = ""
with io.open(
... |
#!/usr/bin/python3
import os
import time
from lsb import Lsb
from util import cmd_parser
def main():
args = cmd_parser()
coding = args.coding
secret_message = args.message
source_file = args.source_file
result_file = args.result_file
secret_file = args.secret_file
# Input check
if ... |
import argparse
parser = argparse.ArgumentParser();
parser.add_argument("--first", default="Admin", help='First Name')
parser.add_argument("--last", default="Admin", help='Last Name')
parser.add_argument("-p", "--pay", default=1000, dest='EPAY', metavar='PAY', type=int, help='Payment')
parser.add_argument("... |
import os
import htmlPy
from PyQt4 import QtGui
#initial configuration
#we get the absolute path of the initialization script to manage all the assets and backend
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
#GUI initialization
app = htmlPy.AppGUI(title=u"PepperPresenter Application")
app.maximized = True
#... |
"""
The Quantum Graph Recurrent Neural Network
===========================================
.. meta::
:property="og:description": Using a quantum graph recurrent neural network to learn quantum dynamics.
:property="og:image": https://pennylane.ai/qml/_images/qgrnn_thumbnail.png
*Author: Jack Ceroni*
"""
####... |
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
__all__ = ['login_required', 'staff_required']
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
"""
Decorator for views that checks that the user is logge... |
import numpy
import math
from matplotlib import pyplot
img0 = pyplot.imread('./data/Teddy/frame10.png')
img1 = pyplot.imread('./data/Teddy/frame11.png')
M, N = img0.shape
print(img0.shape)
W = 25
def lucas_kanade(img0, img1, W):
It = img1 - img0
Ix, Iy = numpy.gradient(img0)
pyplot.imshow(img0, cmap = 'g... |
import time
noe = time.time()
print(time.ctime(now))
|
from django.apps import AppConfig
class CeleryApiConfig(AppConfig):
name = 'celery_api'
def ready(self):
from . import signal_handler
|
# -*- coding: utf-8 -*-
from contextlib import nested
import json
import mock
import testify as T
from urlparse import urlunsplit
from py_razor_client.razor_client import RazorClient
class RazorClientTestCase(T.TestCase):
@T.setup_teardown
def create_razor_client(self):
self.hostname = "some_host"
... |
import discord
from discord.ext import commands
import time
class Management:
def __init__(self, client):
self.client = client
@commands.is_owner()
@commands.command()
async def shutdown (self, ctx):
"""Shuts the bot down."""
await ctx.send("Bot is shutting down...")
aw... |
'''
module for calculating
x to the power y (x ** y)
efficiently
'''
def big_power(x: int, y: int, MOD = None):
'''
For calculating powers where
x and y are large numbers
'''
result = 1
if MOD is None:
while (y > 0):
if (y & 1):
result *= x
x ... |
from typing import Dict, Optional
from asyncpraw import Reddit
from asyncpraw.models import Submission
from asyncprawcore.exceptions import OAuthException
from app.core.config import RedditConfig, settings
async def get_reddit_connection(config: RedditConfig) -> Reddit:
"""Function for connecting to reddit with... |
# Models
from hrm_api.community.models import Reaction
# Utils
import factory
from factory.django import DjangoModelFactory
from hrm_api.community.models.reaction import ReactionTypes
# Factories
from hrm_api.users.factories import ProfileFactory
from hrm_api.community.factories import FeedFactory, CommentFactory
... |
import math
import cv2
import numpy as np
from time import time
import mediapipe as mp
import matplotlib.pyplot as plt
# Initializing mediapipe pose class.
mp_pose = mp.solutions.pose
# Setting up the Pose function.
pose = mp_pose.Pose(static_image_mode=True, min_detection_confidence=0.3, model_complexity=2)
# Init... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
INSTALLED_APPS = ["testapp"]
BASEDIR = os.path.dirname(__file__)
SECRET_KEY = "supersikret"
ROOT_URLCONF = "testapp.urls"
ALLOWED_HOSTS = ["*"]
|
# -*- coding: utf-8 -*-
from flask import url_for
from . import db, BaseNameMixin, MarkdownColumn
from .user import User
from .commentvote import VoteSpace, CommentSpace, SPACETYPE
__all__ = ['SPACESTATUS', 'ProposalSpace']
# --- Constants ---------------------------------------------------------------
class SPACE... |
#python=3.6
# -*- coding: utf-8 -*-
"""
Synopsis:
Created: Created on Sun Feb 14 18:59:11 2021
Sources:
Author: John Telfeyan
john <dot> telfeyan <at> gmail <dot> com
Distribution: MIT Opens Source Copyright; Full permisions here:
https://gist.github.com/john-telfeyan/2565b2904355410c1e75f27524aeea... |
import itertools as it
import string
import unicodedata
from unicode_math_symbols import *
JSON_SNIPPET_TEMPLATE = """\
"{0}": {{
"prefix": "{0}",
"body": ["{1}"],
"description": "{2}"
}},
"""
def json_escape(char):
codepoint = ord(char)
if codepoint <= 0xFFFF:
return "... |
from Jumpscale import j
from base_test import BaseTest
from parameterized import parameterized
import random, requests, uuid, unittest
from requests import ConnectionError
SKIPPED_INSTALLATION = {
"capacity": "https://github.com/threefoldtech/jumpscaleX_core/issues/94",
"sanic": "https://github.com/threefoldte... |
from collections import UserDict, OrderedDict
from collections.abc import Iterable
from _collections_abc import (
dict_keys,
dict_values,
dict_items,
) # https://github.com/python/typeshed/pull/6888
from .helpers import _is_iterable_but_not_string, _convert_slice_to_list
class kdict(UserDict):
"""
... |
import tensorflow as tf
from tensorflow.keras.callbacks import Callback
from matplotlib import pyplot as plt
class GANMonitor(Callback):
def __init__(self, num_img, latent_dim, vis_path, model_path):
self.num_img = num_img
self.latent_dim = latent_dim
self.vis_path = vis_path
s... |
# -*- coding: UTF-8 -*-
import json
import uuid
from datetime import datetime
from flask import current_app
from flask.ext.login import UserMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from werkzeug.security import generate_password_hash, check_password_hash
from app import db
from app... |
import numpy as np
import matplotlib.pylab as mp
import scipy as sp
from scipy.integrate import odeint,dblquad
import time
from colorsys import hsv_to_rgb
from mpl_toolkits.mplot3d import Axes3D
# anim
from matplotlib import pyplot as plt
from matplotlib import animation
import twod
import fourier_2d as f2d
#import ... |
from datetime import datetime, timedelta
import oembed
from urllib2 import HTTPError
from django.contrib.admin import helpers
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import Validat... |
import arcade
from .base import Base
class BaseVisible(Base):
def __init__(self):
super().__init__()
"""the property below ensures that this component can only be added to an arcade sprite (gameobjectvisible)"""
@property
def parent(self):
return self._parent
@parent.setter
... |
import fido
from typing import List
from config import IRC
from modules.access import require_permission, Levels
from modules.nexmo import add_group, send_to_group, get_group
@require_permission(level=Levels.OP, message="Permission denied!")
async def sendmessage(bot: fido, channel: str, sender: str, args: List[str]... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2 as google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2
import google.iam.v1.iam_policy_pb2 as google_dot_iam_d... |
# https://www.codechef.com/problems/CHFMOT18
import math
for _ in range(int(input())):
s,n=map(int,input().split())
print(math.ceil((s-s%2)/n)+(s%2)) |
import math
import os
import os.path
import numpy as np
import cv2 as cv
import torch
import torch.nn as nn
import torch.nn.functional as F
import imageio
from PIL import ImageFont, ImageDraw, Image
from console_progressbar import ProgressBar
import inference
from utils import ScreenSpaceShading
###################... |
"""
Main program for robot.
"""
from pybricks import hubs
from pybricks.geometry import Axis
class Robot(hubs.PrimeHub):
def __init__(self, name: str, front_side: Axis = Axis.X, top_side: Axis = Axis.Z):
super.
|
import torch
import numpy as np
import torchvision
from torchvision import datasets, models, transforms
import PIL
from PIL import Image
from PIL import ImageFile
import cv2
import imageio
ImageFile.LOAD_TRUNCATED_IMAGES = True
# Inference environment params.
model = torch.load("SurfaceDamageDetectionModel")
classes =... |
#Project euler problem 10
#Problem link https://projecteuler.net/problem=10
def sumPrimes(n):
sum, sieve = 0, [True] * n
for p in range(2, n):
if sieve[p]:
sum += p
for i in range(p * p, n, p):
sieve[i] = False
return sum
print(sumPrimes(2000000)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: x.huang
# @date:28/05/19
import abc
import hashlib
import random
from enum import Enum
import requests
from pypay import err
from pypay.interfaces.GatewayApplicationInterface import GatewayApplicationInterface
from pypay.util import xml_et_cdatasection as ET
... |
"""
Computes a TANGENT pulse shape with defined Start and End
Supply d, b, and sp to silence Interaction
W.T. Franks FMP Berlin
Arguments:
-sp:shaped pulse name
-d : delta (+/- d%)
-b : beta (curvature)
-p : number of points (default 1000) ""
-np: number of points
-sc: number of points
-name : specify name
"""
impor... |
phone = input("Enter Phone number:)"
digits_mapping = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine",
"0": "Zero"
}
output = ""
for ch in phone:
output += digits_mapping.get(ch, " ! ") + " "
print(output)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-12 15:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('titles', '0004_auto_20171210_1512'),
]
operations = [
migrations.CreateMode... |
""" LINATE module: Compute (Latent) Ideological Embedding """
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import StandardScaler
import os.path
import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix, issparse
# the user can specify the ideological embeddi... |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import pins
from esphome.const import (
CONF_CLOCK_PIN,
CONF_DATA_PIN,
CONF_ID,
CONF_NUM_CHANNELS,
CONF_NUM_CHIPS,
)
AUTO_LOAD = ["output"]
sm16716_ns = cg.esphome_ns.namespace("sm16716")
SM16716 = sm16716_ns.class_("S... |
"""Dicionário
Escreva uma list comprehension que crie um dicionário em que cada chave
corresponde a um outro dicionário, contendo nome e a nota do aluno.
NOTA: O nome e a nota podem ter valor None.
"""
d = { 'student_' + str(i): {'name': None, 'score': None} for i in range(3) }
print(d)
|
"""Odata library."""
from .odata import (
Blueprint,
Odata,
OdataMixin,
OdataSchema,
)
__all__ = [
"Blueprint",
"Odata",
"OdataMixin",
"OdataSchema",
]
|
import argparse
import time
import yaml
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from utils.profile import count_params
from utils.data_a... |
# Generated by Django 2.1.13 on 2020-01-14 19:54
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nablaforum', '0005_auto_20200104_1336'),
]
operations = [
migrations.AlterField(
model_name='c... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
""" Initial migrations """
dependencies = [
]
operations = [
migrations.CreateModel(
name='AccessAttempt',
fields=[
... |
#!/usr/bin/env python
# DON'T USE THIS. IMPORT OMNI OMNI.OMNI_TO_SWMF.
import datetime as dt
import numpy as np
from spacepy.pybats import ImfInput
raise Exception("DON'T USE THIS YOU IDIOT.")
def fix(arr, flag):
'''
For data vector 'arr', interpolate (linearly) over all regions where
the the bad data... |
from fttcrypt import FTTCryptor
key = "SecretKeyGoesHere"
text="Secured to to be encrypted"
# Encrypt a plain Text to Cipher
cipherText = FTTCryptor.encryptText(text, key)
print(cipherText)
# Decrypt Cipher to Plain Text
decryptedText = FTTCryptor.decryptText(cipherText, key)
print(decryptedText)
# Encrypt a file... |
import click
from ocrd.decorators import ocrd_cli_options, ocrd_cli_wrap_processor
from .processor import OlaHdClientProcessor
@click.command()
@ocrd_cli_options
def cli(*args, **kwargs):
return ocrd_cli_wrap_processor(OlaHdClientProcessor, *args, **kwargs)
|
from django.core.files.uploadedfile import SimpleUploadedFile
from rest_framework.test import APIClient
from testing.testcases import TestCase
from tweets.models import Tweet, TweetPhoto
from utils.paginations import EndlessPagination
# 注意要加 '/' 结尾,要不然会产生 301 redirect
TWEET_LIST_API = '/api/tweets/'
TWEET_CREATE_API ... |
from django.apps import AppConfig
class EnergySaverConfig(AppConfig):
name = 'energy_saver'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.