content stringlengths 5 1.05M |
|---|
from typer.testing import CliRunner
from cipher_typer.typer_cli import app
runner = CliRunner()
def test_app():
result = runner.invoke(app, ["encrypt", "Meet me at 6pm", "23"])
assert result.exit_code == 0
assert "+BBQwJBwxQwsMJ" in result.stdout
def test_app_decrypt():
result = runner.invoke(app,... |
import os
import re
import requests
import datetime
import json
from joblib import Parallel, delayed
DATA_PATH = "/media/jerem/DATA/Eric/OpenScience/unpaywall_test/"
UNPAYWALL_SNAPSHOT_BASE_URL = \
"https://s3-us-west-2.amazonaws.com/unpaywall-data-snapshots/"
UNPAYWALL_SNAPSHOT_FILE = \
"unpaywall_sna... |
x1 = int(input("Enter x1 value bellow: "))
x2 = int(input("Enter x2 value bellow: "))
y1 = int(input("Enter y1 value bellow: "))
y2 = int(input("Enter y2 value bellow: "))
def computeDistance(x1, x2, y1, y2):
#return math.sqrt((math.pow((x2 - x1), 2)) + (math.pow((y2 - y1), 2)))
return ((x2 - x1)**2 + (y2 -... |
import h5py
import numpy
import glob
import cinemasci.cdb
import os.path
class ascent():
def __init__(self):
self.outcdb = None
self.basename = None
self.dirname = None
self.cycles = []
self.minmax = {}
self.variables = []
#
# convert an asc... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistribution... |
import asyncio
from nats.aio.client import Client as NATS
from nats.aio.errors import ErrTimeout, ErrNoServers
class Handler:
__instance = None
def __init__(self, servers, loop):
self.nc = NATS()
self.loop = loop
self.servers = servers
self.queue = asyncio.Queue()
if servers is None:
se... |
import argparse
import os
from itertools import chain
from datasets import load_dataset
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from tokenizers.pre_tokenizers import Whitespace
from tokenizers.processors import TemplateProcessing
from tokenizers.trainers import WordLevelTrainer
from p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from itertools import permutations
import six
import numpy as np
import tensorflow as tf
from zhusuan.model.utils import *
from zhusuan.model.utils import Context... |
# This is a automatically generated installer script for FontLab
# Generated on %(timeStamp)s
# scriptVersion: %(scriptVersion)s
p = "%(appLogPath)s"
log(p,"-" * 50)
log(p,"hello, this is application: %(appName)s")
log(p,"Running script version: %(scriptVersion)s")
log(p,"Platform:"+platform.platform())
resultData = [... |
__author__ = 'guorongxu'
import os
import re
## Parsing the go term file and return GO ID list with descriptions.
def parse_correlation_file(input_file):
node_hash = {}
if os.path.exists(input_file):
with open(input_file) as fp:
lines = fp.readlines()
for line in lines:
... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
"""CNN-based text classification on SageMaker with TensorFlow and Keras"""
# Python Built-Ins:
import argparse
import os
# External Dependencies:
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Conv1D, Dense, Dropout, Embedding, Flatten, MaxPooling1D
from tensorflow.keras.models import ... |
"""
We have a collection of stones, each stone has a positive integer weight.
Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y
with x <= y. The result of this smash is:
If x == y, both stones are totally destroyed;
If x != y, the stone of weight x ... |
"""
Aula - 20
- Interactive Help
- docstrings
- Argumentos/ Parametros opcionais
- Escopo de variáveis
- Retorno de resultados
"""
# Interactive Help
# help(print)
# help(int)
# print(input.__doc__)
######################################################
# Docstrings
def contador(i, f, p):
"""
-> Faz uma c... |
from setuptools import setup, find_packages
import pyTGA
if __name__ == "__main__":
setup(
name="pyTGA",
version=pyTGA.VERSION,
description='A pure Python module to manage TGA images',
long_description='A pure Python module to manage TGA images',
# Author details
... |
"""Class to extract metadata from a Data Table"""
import getpass
import psycopg2
import psycopg2.extras
from psycopg2 import sql
from . import settings
from . import extract_metadata_helper
class ExtractMetadata():
"""Class to extract metadata from a Data Table."""
def __init__(self, data_table_id):
... |
# Module to test Variables
#-------------------------------------------------------------------------------
import pytest
import math
import numpy as np
import scipy.stats
import sympy
import probayes as pb
from probayes import NEARLY_POSITIVE_INF as inf
from probayes import NEARLY_POSITIVE_ZERO as zero
#------------... |
#!/usr/bin/env python
import unittest
import os
import json
from lib.plan import plan_index, plan_filepath
from test.lib.corrigible_test import CorrigibleTest
import lib.plan
script_dirpath = os.path.join(os.path.dirname(lib.plan.__file__), '..', 'test')
system_config_dirpath = os.path.join(script_dirpath,'resourc... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from . import imagedata_pb2 as imagedata__pb2
class PredictorStub(object):
"""python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. imagedata.proto
"""
def __init__(self, channel):
"""Constructor.
Args:
... |
from asyncio import Future
import pytest
from pytest_mock import MockerFixture
from conftest import FooCommand
from protostar.cli.argument_parser_facade import ArgumentParserFacade
from protostar.cli.cli_app import CLIApp
from protostar.cli.command import Command
@pytest.mark.asyncio
async def test_command_run_meth... |
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from concurrent.futures.thread import ThreadPoolExecutor
from typing import Generator
from dazl import testing
import pytest
DEFAULT_SDK_VERSION = "1.17.0"
@pytest.fixture(sc... |
import numpy as np
import pyqtgraph as pg
from acconeer.exptool import configs, utils
from acconeer.exptool.clients import SocketClient, SPIClient, UARTClient
from acconeer.exptool.pg_process import PGProccessDiedException, PGProcess
def main():
args = utils.ExampleArgumentParser(num_sens=1).parse_args()
uti... |
# Provides a web interface for ipcampy
# Andrea Masi 2014 eraclitux@gmail.com
import datetime
from flask import Flask, render_template, send_from_directory, redirect, session, request, url_for
from utils import list_snapshots_days, list_snapshots_hours, list_snapshots_for_a_minute
app = Flask("ipcamweb")
USERNAME = "... |
#!/usr/bin/env python
"""
This runs a command and compares output to a known file over
a given line range.
"""
from __future__ import print_function
import subprocess
import argparse
import os
#pylint: disable=invalid-name
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--c... |
import pandas as pd
import os
import matplotlib.pyplot as plt
import numpy as np
def extract_single_network_edgelist(network_path):
print(network_path)
ep_network = pd.read_csv(network_path)
ep_network.columns.values[0] = "Plant"
ep_network_edgelist = ep_network.melt(id_vars=["Plant"],
... |
import numpy as np
from osgeo import gdal
import matplotlib.pyplot as plt
import os
dpath = os.path.dirname(__file__)
class BiInterpolator:
'''Bilinear interpolation in 2D. The code is modified from mpl_toolkits.basemap.interp and scipy.interpolate'''
def __init__(self, xin, yin, datain):
'''Setting up... |
#! /usr/bin/python2.2
# Copyright (C) 2002 by Martin Pool <mbp@samba.org>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version
# 2 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be ... |
from fjell.app import Application
app = Application(__name__, debug=True)
app.config.update(
{
"db": "sqlite:////tmp/db.sqlite3",
}
)
app.add_plugin("fjell.plugins.sqla")
app.add_plugin("fjell.plugins.jinja2")
app.add_routes(
[
("GET", "/", "example.views.index"),
("GET", "/templa... |
# https://leetcode.com/problems/text-justification/
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
return self.combineWords(self.groupWords(words, maxWidth), maxWidth)
def groupWords(self, words: List[str], maxWidth: int) -> List[str]:
groups = []
... |
__version__ = "1.0.0"
from protocol_lib.collection import ICollection
from protocol_lib.container import IContainer
from protocol_lib.hashable import IHashable
from protocol_lib.iterable import IIterable, IIterator, IReversible
from protocol_lib.mapping import IMapping
from protocol_lib.sequence import IMutableSequenc... |
# https://oj.leetcode.com/problems/jump-game/
class Solution:
# @param A, a list of integers
# @return a boolean
def canJump(self, A):
if len(A) == 0:
return False
table = [False] * len(A)
# stand on the first piece
table[0] = True
for i in xrange(0, len(A)-1):
if not table[i]:
... |
###########################################
# A structure for storing finch comfiguration
###########################################
from Finch_constants import Finch_constants as FS
class Finch_config:
# How should we define the states?
# As integers assigned to constant names in an enum?
# Initializes... |
#!/usr/bin/env python
import os
import time
import cv2
import numpy as np
import pybullet as p
import matplotlib.pyplot as plt
import tensorflow as tf; tf.compat.v1.enable_eager_execution()
from ravens.models import Attention, Regression
from ravens import cameras
from ravens import utils
class RegressionAgent:
... |
import pickle
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.models import load_model
import random
plt.switch_backend('agg')
f=open("./id_to_data","rb+")
data=pickle.load(f)
f=open("./id_to_box","rb+")
box=pickle.load(f)
f=open("./id_to_size","rb+")
size=pickle.load(f)
index=[i for i ... |
from django.urls import path
from .views import (
list_hackathons,
create_hackathon,
update_hackathon,
delete_hackathon,
enroll_toggle,
judging,
check_projects_scores,
view_hackathon,
update_hackathon_status,
change_awards,
judge_teams,
assign_mentors,
view_hackathon_... |
import json
import sys
import mso
import urllib3
import json
import pprint
try:
from credentials import MSO_IP, MSO_ADMIN, MSO_PASSWORD
except ImportError:
sys.exit("Error: please verify credentials file format.")
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
rc = mso.RestClient(MSO_IP, ... |
# https://matplotlib.org/api/_as_gen/matplotlib.gridspec.GridSpec.html#matplotlib.gridspec.GridSpec
import os
import matplotlib.pyplot as plt
import numpy as np
from fears.utils import results_manager, plotter
data_folder = 'results_07202021_0000'
exp_info_file = 'experiment_info_07202021_0000.p'
fig,ax = plt.subplot... |
from pydantic import BaseModel
class UtilsNotificationsLinksResponse(BaseModel):
notifications: bool
class UtilsNotificationsLinks(BaseModel):
response: UtilsNotificationsLinksResponse
|
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2015, ARM Limited and contributors.
#
# 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
#
# ... |
import socket
import sys
from threading import Thread, Lock
from PyQt5.QtWidgets import *
class MySocket(Thread):
def __init__(self, output, sock=None):
Thread.__init__(self)
self.interface = output
self.thread_active = True
if sock is None:
self.sock = sock... |
# -*- coding: utf-8 -*-
from girderformindlogger.api import access
from girderformindlogger.api.describe import Description, autoDescribeRoute
from girderformindlogger.api.rest import Resource
from girderformindlogger.models.collection import Collection
from girderformindlogger.models.folder import Folder
from girderfo... |
"""
Simple script which runs SNPE-A with one fixed observation.
"""
import numpy as np
import torch as to
from copy import deepcopy
from sbi import utils
import pyrado
from pyrado.algorithms.meta.bayessim import BayesSim
from pyrado.sampling.sbi_embeddings import BayesSimEmbedding
from pyrado.sampling.sbi_rollout_sam... |
class ProfitBl(object):
pass
|
import cv2
import time
import numpy
import init_hand_tracking_module #initial file
import mediapipe
import math
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
|
# Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom.
# Copyright (c) 2021, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium.
import itertools
class chain(object):
def __init__(self, *args):
self.args = args
... |
import pytest
from ..dtype_helpers import EqualityMapping
def test_raises_on_distinct_eq_key():
with pytest.raises(ValueError):
EqualityMapping([(float("nan"), "value")])
def test_raises_on_indistinct_eq_keys():
class AlwaysEq:
def __init__(self, hash):
self._hash = hash
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thuesday June 1 12:45:05 2021
@author: cbadenes
"""
import worker as workers
import pysolr
import html
import time
import sys
import os
from datetime import datetime
if __name__ == '__main__':
# Create a client instance. The timeout and authentication... |
#!/usr/bin/env/python
#-*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import csv
import argparse
import sys
#Esto va a permitir que se agregue inputs desde la terminal (justo cuando se ejecuta python3 remover_puntos.py argv[0]....)
try:
parser=argparse.ArgumentParser();
parser.add_argument(... |
#!/usr/bin/python
# Example using a character LCD connected to a Raspberry Pi
from lcd import LCD
import time
lcd = LCD(16, 19, 25, 11, 23, 22)
lcd.set_text('Hello!')
time.sleep(2)
lcd.set_text("World!", clean=False)
time.sleep(2)
lcd.set_text("Center!", center=True)
time.sleep(2)
lcd.cursor_visible(True)
lcd.c... |
import pkgutil
from threading import Event, Thread
from typing import Callable, List
from PyQt5.QtCore import pyqtSignal
from qtpy import QtCore, QtWidgets
class classproperty(object):
def __init__(self, fget):
self.fget = fget
def __get__(self, owner_self, owner_cls):
return self.fget(owne... |
# coding: utf-8
import os
print(os.name)
# print(getattr(os, 'uname'))
print(hasattr(os, 'uname'))
print(os.environ)
print(os.environ.get('path'))
print(os.path.realpath('.'))
print(os.path.join('/a/b', 'c'))
# print(os.mkdir(os.path.realpath(os.path.join(__file__,os.pardir, 'test_path'))))
# print(os.rmdir(os.path.... |
"""Tools for manipulation of rational expressions. """
from __future__ import print_function, division
from sympy.core import Basic, Add, sympify
from sympy.core.compatibility import iterable
from sympy.core.exprtools import gcd_terms
from sympy.utilities import public
@public
def together(expr, deep=False):
"""... |
class TestInflux:
params = {
'test_create': [{
'data': [{
'name': 'mongo',
'type': 'mongo',
'config': {
'configBean.mongoConfig.connectionString': 'mongodb://mongo:27017',
'configBean.mongoConfig.username': '... |
from .api_definition import api_list
from .project_definition import definition
|
from django.core.exceptions import PermissionDenied
from permissions import PermissionsRegistry
from permissions.exc import NoSuchPermissionError, PermissionsError
from .base import AnonymousUser, Model, TestCase, User, View
class TestRegistry(TestCase):
def test_register(self):
@self.registry.registe... |
def foo():
pass
class Model(object):
pass
|
# XY Nonlinear Kinematic MPC Module.
import time
import casadi
from controller import Controller
class KinMPCPathFollower(Controller):
def __init__(self,
N = 10, # timesteps in MPC Horizon
DT = 0.2, # discretization time between timesteps (s)
L_F = 1.... |
# -*- coding: utf-8 -*-
import models
import wizard
import controllers
import tests.test_mail_model
|
#-*- coding:utf-8 -*-
from django.shortcuts import render
from blog.models import Article, Tag, Classification,User #导入创建的模型
from django import forms
from django.shortcuts import render_to_response,get_object_or_404
from django.core.paginator import Paginator,InvalidPage,EmptyPage,PageNotAnInteger
from django.template... |
class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
total = [i for i in triangle[0]]
for i in range(1, len(triangle)):
prev = sys.maxint
for j in range(len(total)):
temp = t... |
from sqlalchemy import Column, Integer, String
from base import Base
class Qualifier(Base):
__tablename__ = 'Qualifiers'
id = Column('QualifierID', Integer, primary_key=True)
code = Column('QualifierCode', String, nullable=False)
description = Column('QualifierDescription', String, nullable=False)
def __... |
import os
import numpy as np
from Sample import Sample
from RecordingArtifact import RecordingArtifact
from TranscriptArtifact import TranscriptArtifact
from AudioTextSample import AudioTextSample
from load_and_resample_if_necessary import load_and_resample_if_necessary
from power_split import power_split
class Record... |
import goose
from bs4 import BeautifulSoup
import random
import ctypes
import concurrent.futures
import os, sys, json
import readability
import lxml
import re
__version__ = '0.0.0'
def extract_clean_content(content):
global __version__
# I found out about goose and readability here:
# http://stackoverflow.c... |
#!/usr/bin/env python
# -*- coding: utf8
import json
from datetime import datetime
import codecs
def open_utf8(filename, *args, **kwargs):
logger.debug('open(%s, %s, %s)', filename, args, kwargs)
return codecs.open(filename, *args, encoding="utf-8-sig", **kwargs)
import os.path
import logging
logger = logging... |
# vim: sw=4:ts=4:et:cc=120
import datetime
import logging
import pytz
import saq
from saq.error import report_exception
from saq.analysis import Analysis, Observable
from saq.modules import AnalysisModule
from saq.constants import *
from saq.util import abs_path, create_timedelta
from saq.qradar import QRadarAPIClie... |
import random
from itertools import cycle
from scrapy import signals
from scrapy.exceptions import NotConfigured
class RotateUserAgentMiddleware(object):
def __init__(self, user_agents: list, min_usage: int, max_usage: int):
'''Creates a new instance of RotateUserAgentMiddleware
Keyword ... |
#!/usr/bin/env python
class Edge:
"""Edge class, to contain a directed edge of a tree or directed graph.
attributes parent and child: index of parent and child node in the graph.
"""
def __init__ (self, parent, child, length=None):
"""create a new Edge object, linking nodes
with indice... |
"""
Created on 4th July, 2018 from mapclientplugins.meshgeneratorstep.
"""
import string
from opencmiss.utils.zinc import createFiniteElementField
from opencmiss.zinc.field import Field
from opencmiss.zinc.glyph import Glyph
import opencmiss.zinc.scenecoordinatesystem as Scenecoordinatesystem
from opencmiss.zinc.gra... |
from datetime import datetime
import time
import matplotlib.pyplot as plt
import random
import io
import threading
def filter24hours(data):
now = datetime.timestamp(datetime.now())
return sorted([d for d in data if (now - d["timestamp"]) < 86400], key=lambda x: x["timestamp"])
def filter30days(data):
... |
import unittest
import asm.cms.htmlpage
class HTMLPageTests(unittest.TestCase):
def test_constructor(self):
htmlpage = asm.cms.htmlpage.HTMLPage()
self.assertEquals('', htmlpage.content)
|
import numpy as np
from source.env.systems import ai
from source.env.lib.enums import Material
class Stat:
def __init__(self, val, maxVal):
self._val = val
self._max = maxVal
def increment(self, amt=1):
self._val = min(self.max, self.val + amt)
def decrement(self, amt=1):
... |
# Project Euler Problem 0008
# Largest product in a series
# The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
# 73167176531330624919225119674426574742355349194934
# 96983520312774506326239578318016984801869478851843
# 858615607891129494954595017379583319528532... |
# This script just ensures that all the JSON files can be parsed correctly
from __future__ import print_function
import os
import glob
import json
MONTAGELIB = os.path.join('..', '..', 'MontageLib')
for json_file in glob.glob(os.path.join(MONTAGELIB, '*', '*.json')):
print("Validating {0}...".format(json_fi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Redis storage file reader."""
import unittest
import fakeredis
import redis
from plaso.containers import sessions
from plaso.containers import tasks
from plaso.storage.redis import reader
from tests.storage import test_lib
class RedisStorageReaderTes... |
from diot import Diot
from bioprocs.utils import funcargs
from bioprocs.utils.tsvio2 import TsvWriter, TsvRecord
from gff import Gff
infile = {{i.infile | quote}}
outfile = {{o.outfile | quote}}
bedcols = {{args.bedcols | repr}}
keepattrs = {{args.keepattrs | repr}}
outhead = {{args.outhead | repr}}
bedcols.... |
from flask.ext.wtf import Form
from wtforms import StringField, TextAreaField, BooleanField, SelectField,\
SubmitField, FileField, SelectMultipleField, widgets
from wtforms.validators import Required, Length, Email, Regexp
from wtforms import ValidationError
from flask.ext.pagedown.fields import PageDownField
from ... |
'''analyze WORKING/samples-train.csv
INVOCATION: python samples-train-analysis.py ARGS
INPUT FILES:
WORKING/samples-train.csv
OUTPUT FILES:
WORKING/ME/0log.txt log file containing what is printed
WORKING/ME/transactions.csv with columns apn | date | sequence | actual_price
'''
import argparse
import coll... |
class Move:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
def is_valid(self):
return 1 <= self._value <= 9
def get_row(self):
if self._value in (1, 2, 3):
return 0
elif self._value in (4, 5, 6):
... |
from environments.base_environment import BaseEnvironment
import numpy as np
def _pos(i, j):
return 7 * i + j
rows = [
[_pos(line, col_start+k) for k in range(4)]
for line in range(6)
for col_start in range(4)
]
columns = [
[_pos(line_start+k, col) for k in range(4)]
for line_start in range(... |
import sys, time
import logging
proxy = "sal146-us"
domain = ".netnut.io"
port = "33128"
USR = "netnut username"
PSWD = "netnut password"
global LOGF
global INFOF
TIME = time.strftime("%H%M%S",time.localtime())
LOGF = "log.txt"
INFOF = TIME+"-Info.txt"
class LOGGING:
LogFile ... |
#!/usr/bin/env python
#########################################################################################
#
# Perform mathematical operations on images
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2015 Polytechnique Montreal <www.neuro.polymtl.ca>
# A... |
from bidict import bidict
from editor.utils.common_functions import (
get_lowest_byte_value,
round_down,
)
from editor.attributes.player.player_attribute import (
PlayerAttribute,
PlayerAttributeTypes,
)
from editor.attributes.player.player_attribute_option import (
PlayerAttributeOption,
)
from... |
# Copyright (c) OpenMMLab. All rights reserved.
import time
import uuid
import warnings
from typing import Dict, List, Optional
import numpy as np
class Message():
"""Message base class.
All message class should inherit this class. The basic use of a Message
instance is to carray a piece of text message... |
# -*- coding: utf-8 -*-
"""
Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario lo introduzca muestre
por pantalla la cadena ¡Hola <nombre>!, donde <nombre> es el nombre que el usuario haya introducido.
"""
nombre = input("Introduce tu nombre: ")
print("¡Hola " + nombre... |
from user_page.views.MyPage import *
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('helios_auth', '0001_initial'),
]
... |
# import queue
from typing import List
class Solution:
"""
https://leetcode-cn.com/problems/zui-xiao-tiao-yue-ci-shu/submissions/
动态规划:
1. 首先要有一个确定的边界数字,例如开始 或者 结束
2. 再者又一个状态转移的 循环 正序 or 倒序
3. 每一个状态的改变都有可能引起两种变化,对于已知的DP的修改 和 对于 未知DP的修改
4. 最简单的情况就是对于未知的修改,
5. 本题,难点在于对... |
# Generated by Django 2.2.5 on 2019-10-09 02:52
from dateutil import tz
from django.db import migrations, models
from django.utils import timezone
def migrate_data_forward(Series):
tzinfo = tz.gettz("America/New_York")
for series in Series.objects.all().iterator():
series.datecounted = series.datetim... |
import math
import numpy as np
from torch.utils.data import Sampler
from pidepipe.dl.utils.experiment import set_global_seed
def get_num_after_point(x: float) -> int:
balance_int = str(x)
if not '.' in balance_int:
return 0
return len(balance_int) - balance_int.index('.') - 1
def gcd(arr: [int... |
import requests
import time
import hashlib
import json
import time
class Github():
def __init__(self, config, avoid_rate_limiting=True):
self.config = config
self.avoid_rate_limiting = avoid_rate_limiting
def __query_github(self, query):
url = self.config.get('github', 'url') + query
... |
#!/usr/bin/env python3
# coding = utf8
import unittest as ut
from mykit.core._control import tags_mapping, parse_to_tagdict, check_valid_map
class test_control_map(ut.TestCase):
_mapDict = {
"abc": {"l":"abc", "C": "Abc", "U": "ABC"},
"def": {"l":"def", "C": "Def", "U": "DEF"},
"ghi": {"... |
from brian2 import *
# ###########################################
# Defining network model parameters
# ###########################################
simtime = 0.5*second # Simulation time
number = { 'CA3':100, 'I':10, 'CA1':1 }
epsilon = { 'CA3_CA1':0.1,'CA3_I':1.0,'I_CA1':1.0 } # Sparseness of synaptic connections
... |
'''Tests for the Artist class
Note: these tests are not exhaustive and could always be improved. Since the
Spotify REST api is mocked, if it's functionality ever changes these tests may
become obsolete.
Last updated: May 25, 2020
'''
# These 2 statements are fine to include in your test file
#pylint: disable=missing-... |
import timm
import torch
import torch.nn as nn
from nnAudio import Spectrogram
from scalers import standard_scaler
class GeM(nn.Module):
"""
Code modified from the 2d code in
https://amaarora.github.io/2020/08/30/gempool.html
"""
def __init__(self, kernel_size=8, p=3, eps=1e-6):
super(Ge... |
import os
import dotenv
dotenv.load_dotenv()
APP_PORT = int(os.environ.get('APP_PORT', '8000'))
DEV = bool(int(os.environ.get('DEV')))
TESTNET = bool(int(os.environ.get('TESTNET')))
LOCAL = bool(int(os.environ.get('LOCAL')))
GOOGLE_CLIENT_KEY_FILENAME = 'gclient-keys.json'
MSCAN_APIKEY = os.environ.get('MSCAN_APIKE... |
"""
Shim for NumPy's suppress_warnings
"""
try:
from numpy.testing import suppress_warnings
except ImportError:
# The following two classes are copied from python 2.6 warnings module
# (context manager)
class WarningMessage(object):
"""
Holds the result of a single showwarning() call... |
"""
A simple coroutine in a module that imports the tornado package.
"""
import tornado
@tornado.gen.coroutine
def call_api():
response = yield fetch()
if response.status != 200:
raise BadStatusError()
if response.status == 204:
raise tornado.gen.Return
raise tornado.gen.Return(respons... |
"""General Gaussian filters based on approximating intractable quantities with numerical
quadrature.
Examples include the unscented Kalman filter / RTS smoother which is
based on a third degree fully symmetric rule.
"""
import typing
import numpy as np
import probnum.statespace as pnss
import probnum.type as pntype... |
import scipy.io
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
import utils.utils
from utils.tof import *
import importlib
class AmplitudeMask(nn.Module):
def __init__(self, args, device):
super(AmplitudeMask, self).__init__()
if args.... |
import numpy as np
import pandas as pd
def createAdjMatrixFile(fileName):
dirName = "datasetTSP/%s/%s_xy.txt" % (fileName, fileName)
data = pd.read_csv(dirName,header = None, delimiter=r"\s+").as_matrix()
newMatrix = np.zeros((len(data),len(data)))
for i in range(len(data)):
for j in range(len(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.