content stringlengths 5 1.05M |
|---|
from time import sleep
from random import randint
print('\n\33[1;32m{:+^40}\33[m'.format(' JOKENPÔ '))
print('\nVamos jogar?')
itens = ('Pedra', 'Papel', 'Tesoura')
comp = randint(0, 2)
print('''Suas opções:
[ 0 ] Pedra
[ 1 ] Papel
[ 2 ] Tesoura''')
jog = int(input('Qual a sua jogada? '))
print('\n JO')
sleep(1)
print... |
""".oof"""
from telethon import events
import asyncio
@borg.on(events.NewMessage(pattern=r"\.(.*)", outgoing=True))
async def _(event):
if event.fwd_from:
return
animation_interval = 1
animation_ttl = range(0, 103)
input_str = event.pattern_match.group(1)
if input_str == "... |
import sendgrid
import os
from sendgrid.helpers.mail import *
# TODO: change from address and names
from_address = "no-reply@marchingbytes.com"
from_name = "MarchingBytes Automated"
def send_email(to, subject, body):
api_key = os.environ.get("SENDGRID_API_KEY")
if api_key is None:
print("Sendgrid not... |
import numpy as np
from astropy import wcs
from matplotlib import pyplot
import h5py
import binFuncs
from scipy.interpolate import interp1d
import os
from matplotlib.patches import Ellipse
from Mapping import Mapper
from MappingAzEl import MapperAzEl
from MappingSun import MapperSun
from tqdm import tqdm
import clic... |
import matplotlib.pyplot as plot
import matplotlib.animation as animation
import numpy as np
import seaborn as sns
def calculateLoss(X, Y, weight, bias = 0):
predictedLine = X * weight + bias
return np.average((predictedLine - Y) ** 2)
def trainWithBias1(X, Y):
weight = 0
bias = 0
learningRate = 5... |
#!/usr/bin/env python2.7
import os
import argparse
import git
import sys
from datetime import datetime
import re
def GetVersion(backupFile, label=''):
"""As getLongVersion(), but only return the leading *.*.* value."""
raw = GetLongVersion(backupFile, label)
# Just return the first 3 parts of the ver... |
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
import scipy.sparse as sp
from sklearn.metrics import mean_squared_error
from math import sqrt
import itertools
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import random
def novelty(predicted,... |
#from nlplingo.tasks.sequence.run import find_token_indices_of_markers, remove_tokens_at_indices
from nlplingo.tasks.sequence.utils import find_token_indices_of_markers, remove_tokens_at_indices
from nlplingo.oregon.event_models.uoregon.tools.xlmr import xlmr_tokenizer
from nlplingo.oregon.event_models.uoregon.tools.u... |
# Autogenerated from KST: please remove this line if doing any edits by hand!
import unittest
from params_pass_array_str import _schema
class TestParamsPassArrayStr(unittest.TestCase):
def test_params_pass_array_str(self):
r = _schema.parse_file('src/term_strz.bin')
self.assertEqual(len(r.pass_s... |
# The MIT License
#
# Copyright (c) 2008 James Piechota
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy,... |
"""Utils and fixtures to facilitate operation on metadata row in file browser in oneprovider web GUI.
"""
from selenium.common.exceptions import NoSuchElementException
from tests.gui.utils.core.common import PageObject
from tests.gui.utils.core.web_elements import InputWebElement, TextLabelWebElement, WebItem, WebItem... |
#!/usr/bin/env python
# Copyright 2017 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import itertools
import json
import os
import sys
from sdk_common import Atom, detect_category_violations, detect_colli... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Ui_SendFileDialog.ui',
# licensing of 'Ui_SendFileDialog.ui' applies.
#
# Created: Fri Jan 10 21:11:54 2020
# by: pyside2-uic running on PySide2 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PySide2 im... |
########################################
########################################
####### Author : Abhinandan Dubey (alivcor)
####### Stony Brook University
# perfect essays : 37, 118, 147,
import csv
import sys
import nltk
import numpy
import sklearn
from sklearn.feature_extraction.text import TfidfVectorizer
from sk... |
# -*- coding: utf-8 -*-
"""
Mouse and keyboard listener, logs events to database.
--quiet prints out nothing
@author Erki Suurjaak
@created 06.04.2015
@modified 10.02.2021
"""
from __future__ import print_function
import datetime
import math
import Queue
import sys
import threading
im... |
"""Commands module."""
|
from __future__ import absolute_import, division, print_function
import unittest
import os.path
from GenomicConsensus.options import Constants
from pbcore.io import ContigSet
import pbcommand.testkit
import pbtestdata
DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")
assert os.path.isdir(D... |
# -*- coding: utf-8 -*-
"""
An alphabetical list of Finnish municipalities for use as `choices` in a
formfield.
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
MUNICIPALITY_CHOICES = (
('akaa', u"Akaa"),
('alajarvi', u"Alajärvi"),
('alavieska', u"Alav... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('labour', '0014_auto_20151108_1906'),
]
operations = [
migrations.CreateModel(
name='Shift',
fields=[
('id', models.AutoField(verbose_name='ID', seria... |
import pandas as pd
from flask import Flask, render_template, request
from recommendation.recommender import item_based_recom, rename_columns, item_and_genre_based_recom, categories
app = Flask(__name__)
app.recommender = pd.read_parquet('models/recommender_df.parquet.gzip')
app.movies = pd.read_parquet('models/movies... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from setuptools import find_packages, setup
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
__import__("adminlte")
setup(
name='django-adminlte... |
from pypbbot import app, run_server, BaseDriver
from pypbbot.utils import sendBackClipsToAndWait, SingletonType
class SingletonDriver(BaseDriver, metaclass=SingletonType):
def onPrivateMessage(self, event):
message = event.raw_message
if message.startswith('#repr'):
sendBackClipsToAndW... |
__doc__ = """Deprecated.
"""
__author__ = "Rui Campos"
from scipy.interpolate import CubicSpline, RectBivariateSpline, BarycentricInterpolator, interp1d
from numpy import *
from numpy.random import rand
from scipy.integrate import *
class UnivariateDistribution:
def __init__(self, xAxis = [], yAxis = []):
... |
"""Urls mappings for both UI views and REST api calls."""
from django.conf.urls import patterns, url
import django.contrib.auth.views
from spudblog import views
urlpatterns = patterns(
'',
# UI view urls
url(r'^$', django.contrib.auth.views.login,
{'template_name': 'spudblog/login.html'}, name='l... |
query = """
DROP TABLE IF EXISTS evidences;
CREATE TABLE IF NOT EXISTS evidences (
id serial PRIMARY KEY,
incident_id VARCHAR,
link VARCHAR,
FOREIGN KEY (incident_id) REFERENCES incidents (id)
);
"""
|
import json
import matplotlib.pyplot as plt
with open('new_cases.json', 'r+') as f:
new_cases = json.load(f)
COUNTRIES = ['India', 'Italy', 'Spain', 'South Korea']
growth_rate = {}
for country in COUNTRIES:
growth_rate[country] = []
report_no = 0
for country in COUNTRIES:
for report in range(len(new_cas... |
import datetime
from tests import BaseTestCase
from redash import models
from factories import dashboard_factory, query_factory, data_source_factory, query_result_factory
from redash.utils import gen_query_hash
class DashboardTest(BaseTestCase):
def test_appends_suffix_to_slug_when_duplicate(self):
d1 = d... |
import colors as c
from types import SimpleNamespace as ns
from animation import Animation as anim
from hex_tile import hex_to_pixel
from gui import draw_box, draw_hex, draw_text
directions = ns(**{
"TOP":0,
"LEFT":1,
"BOTTOM":3,
"RIGHT":4
})
def white_hex_blink(selected, loop=2, ms=200):
def step(percent,... |
import csv
import itertools
import re
import hashlib
from androidcrypto import constants
import base64
import random
import logging
import json
import numpy as np
import pandas as pd
import copy
from collections.abc import Iterable
def decolorize_source_code(src_code):
reaesc = re.compile(r'\x1b[^m]*m')
retur... |
#!"F:\\Python\\pythonw.exe"
print("Content-Type: text/html")
print()
import cgi
form = cgi.FieldStorage()
ac=form.getvalue('account')
#ac="655580033"
def main():
import pyodbc
conn=pyodbc.connect('Driver={SQL Server};''Server=suresh-pc;''Database=bank')
amount=int(form.getvalue('withdraw'))
... |
#!python3
# Mark Bykerk KauffmanO.
# Parses command line args and uses VideoLinkCreator to create a link to a URL for a video.
# Sample Use: python create_link.py --learnfqdn "kauffman380011.ddns.net" --key "1237d7ee-80ab-123c-afc5-123ddd7c31bc" --secret "kL1239NnNk0s1234UUm0muL19Xmt1234" --course_id "uuid:fc005cb3865a... |
# Contiguous Array
# Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
# Example 1:
# Input: [0,1]
# Output: 2
# Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
# Example 2:
# Input: [0,1,0]
# Output: 2
# Explanation: [0, 1] (or [... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#Display whether the current year is a leap year
year = 2020
if year % 400 == 0:
print('2020 is a leap year')
elif year % 4 == 0 and year % 100 != 0:
print('2020 is a leap year')
else:
print('2020 is not a leap year')
# In[ ]:
|
# %%
#caesar cipher
class his_cip:
def __init__(self):
self.alf = "abcdefghijklmnopqrstuvwxyz"
self.alf2 = self.alf*2
self.len_ = len(self.alf)
def caesar_enc(self,plaintext,key):
ciphertext = ""
alpha = self.alf*2
#replace dots and getting all in lower ... |
from typing import Dict
from pyspark.sql import SparkSession, Column, DataFrame
# noinspection PyUnresolvedReferences
from pyspark.sql.functions import col, regexp_replace, substring
from pyspark.sql.functions import coalesce, lit, to_date
from spark_auto_mapper.automappers.automapper import AutoMapper
from spark_aut... |
from database import session
from models.ratingsModel import Rating
from models.newsModel import News
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
class GraphController(object):
def getRatingsGraph(self, nid: int):
ratings = session.query(Rating.rating).where(Rating.n... |
import asyncio
from typing import Callable
from typing import Dict
from typing import List
class HandlersHolder:
def __init__(self):
self._on_event_update: Dict[str, List[Callable]] = {
'RAW_UPDATE_HANDLER': [],
'STREAM_END_HANDLER': [],
'INVITE_HANDLER': [],
... |
# -*- mode:python; coding:utf-8 -*-
# Copyright (c) 2021 IBM Corp. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
#... |
import torch
import torch.nn as nn
import torch_tensorrt.fx.tracer.acc_tracer.acc_ops as acc_ops
from parameterized import parameterized
from torch.testing._internal.common_fx2trt import AccTestCase
from torch.testing._internal.common_utils import run_tests
class TestConverter(AccTestCase):
@parameterized.expand(... |
#! /usr/bin/python
"""Module for Matches.
This module builds the Match base class with validation
for its fields. When validation is stronger than simple type
validation, the Mark class is used in replace of traditional str or int classes to
track accuracy.
Example:
>>>match = CollegeMatch(**kwargs)
"""
from d... |
from typing import List
from pydantic import BaseModel
class Butaca(BaseModel):
idButaca: int
idSala: int
Sala: str
Cantidad: int
class Config:
orm_mode = True
|
def progress_level_percentage(percentage):
""" Progess percentage util.
- 0-33 red
- 34-66 yellow
- 67-100 green
"""
_percentage = int(percentage)
if 0 < _percentage <= 33:
level = 'danger'
elif 34 <= _percentage <= 66:
level = 'warning'
elif _percentage >= 67:
... |
import logging
from dbnd._core.constants import ApacheBeamClusterType, CloudType, EnvLabel
from dbnd._core.errors import friendly_error
from dbnd._core.parameter.parameter_builder import parameter
from dbnd._core.parameter.parameter_definition import ParameterScope
from dbnd._core.task.config import Config
from target... |
# !/usr/bin/env python
# -*-coding:utf-8 -*-
# Warning :The Hard Way Is Easier
import random
import string
"""
1.如何随机获取26个字母大小写?如果给定不同字母不同的权重值,如果实现根据不同权重获取字母?
英文字母的ASCII标码 97-123
"""
print(string.ascii_letters) # 获取大小写字符串
print(string.ascii_lowercase) # 只获取小写字符串
print(string.ascii_uppercase) # 只获取大写字符串
# chr(i... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib, math
# Create subplot
fig, ax = plt.subplots(1)
# Create circle
theta = np.linspace(0, 2*np.pi, 100)
r = 250.0
x1 = r*np.cos(theta)
x2 = r*np.sin(theta)
# Print circle
ax.plot(x1, x2)
ax.set_aspect(1)
# Configure grid
plt.xlim(-300.00,300.00)
plt... |
# Generated by Django 3.1.2 on 2020-10-27 20:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pokemonfans', '0013_pokemon_type_1'),
]
operations = [
migrations.AddField(
model_name='pokemon',
name='description'... |
import mysql.connector
from mysql.connector import Error
#Open database connection with a dictionary
conDict = {'host':'localhost',
'database':'game_records',
'user':'root',
'password':''}
db = mysql.connector.connect(**conDict)
#preparing cursor
cursor = db.cursor()
#ex... |
"""
Connection manager for DynamoDB
"""
import boto3
from botocore.exceptions import ClientError
import logging.config
import os
import constants
import settings
LOGGING_CONFIG = os.path.join(settings.ROOT_DIR, 'logging.conf')
logging.config.fileConfig(LOGGING_CONFIG)
log = logging.getLogger()
class DynamoDBConn():
... |
from pathlib import Path
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from confluence_client import ConfluenceClient
class ConfluenceContent:
def __init__(self, html):
self.html_soup = BeautifulSoup(html, 'lxml')
def process_images(self, page_html_path: Path, confluen... |
"""
@author: Justin Pusztay
"""
# In this file we will only worry about 'NN' simulations
# In this file we only start from empty with the states.
"""
Average is multiplying states of two nodes and dividing by number of timesteps
"""
import Cayley as cy
import Cayley.research as cr
import numpy as np
import matplotli... |
'''
Make a Python program, which can validate if the input string is a valid Finnish id number.
You must calculate that the checksum is correct. Also output the birthdate of the person in format day.month.year
and tell the gender (male/female) See https://fi.wikipedia.org/wiki/Henkil%C3%B6tunnus
'''
import re
check_... |
"""
test for the psurl module.
"""
import unittest
from base_test import PschedTestBase
from pscheduler.psurl import *
class TestPsurl(PschedTestBase):
"""
URL tests.
"""
def test_url_bad(self):
"""IP addr tests"""
# Missing scheme
no_scheme = "no-scheme"
(status,... |
# -*- coding: utf-8 -*-
import sys
from concurrent.futures import as_completed
from concurrent.futures.thread import ThreadPoolExecutor
from multiprocessing import cpu_count, get_context
from typing import Any, Callable, Dict, List
from django.conf import settings
def batch_call(
func: Callable,
params_list:... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
def home(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse("operations:operation_list"))
# test si authentifié, si oui, rediriger vers convention/index...
... |
import logging
from time import sleep
from r7insight import R7InsightHandler
# add your token from insightops here
# token = ''
region = 'EU'
log = logging.getLogger('r7insight')
log.setLevel(logging.INFO)
test = R7InsightHandler(token, region)
log.addHandler(test)
log.warn("Warning message")
log.info("Info message... |
import datetime
import string
import random
import json
import boto3
from prettytable import PrettyTable # imported from Lambda layer
# PrettyTable
TABLE = PrettyTable(['Region', 'MonthlySpendLimit ($)', 'SMSMonthToDateSpentUSD'])
START_TIME = datetime.datetime.utcnow() - datetime.timedelta(hours=1)
END_TIME = date... |
import pytest
def pytest_runtest_setup(item):
r"""Our tests will often run in headless virtual environments. For this
reason, we enforce the use of matplotlib's robust Agg backend, because it
does not require a graphical display.
This avoids errors such as:
c:\hostedtoolcache\windows\python\3... |
from bideox.settings.base import *
DEBUG = False
ALLOWED_HOSTS = ['*']
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-30 23:11
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('flexible_reports', '0005_column_attrs'),
]
operati... |
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import array
from PIL import Image, ImageChops, ImageFilter
texture = [9.962654113769531 for i in range(255)]
trans_4_firefox = [6.102943420410156, 1.7255783081054688, 4.796600341796875, 3.0786514282226562, 3.874969482421875, 4.560279... |
#Exercícios Numpy-01
#*******************
import numpy as np
|
v = float(input('Qual é a quantidade de metros? '))
cm = v * 100
mm = v * 1000
print('A quantidade de metros em cm é {} e em mm é {}.'.format(cm, mm))
|
import string
from math import inf
from tempfile import TemporaryDirectory
from os.path import join
BLOCK_FILE_NAME = 'block_{}.dat'
class ExternalSort:
"""External sort of a file with integer numbers (separated by spaces).
"""
def __init__(self, input_file_name, block_size, output_file_name):
i... |
import unittest
from fsap.sepr import section_property as sp
class SectionPropertyTest(unittest.TestCase):
def setUp(self):
self.points1 = [(0.0,0.0),(1.0,0.0),(1.0,1.0),(0.0,1.0)]
self.points2 = [(0.0,0.0),(1.0,1.0),(1.0,0.0),(0.0,1.0)]
def test_centroid(self):
sp1 = sp.SectionProper... |
# -*- coding: utf-8 -*-
"""unittest
"""
import unittest
import numpy as np
from numpy.testing import assert_almost_equal
from fastsst.util.linear_algebra import *
class TestLinearAlgebra(unittest.TestCase):
def setUp(self):
np.random.seed(1234)
self.A = np.random.rand(10,10)
self.x0 = np.ra... |
from django.core.management import BaseCommand
from django.core.paginator import Paginator
from guardian.shortcuts import assign_perm
from grandchallenge.reader_studies.models import Answer
class Command(BaseCommand):
def handle(self, *args, **options):
answers = Answer.objects.all().select_related("crea... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from ... import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .alert_policy import *
from .get_alert_... |
from config import general
def printProgressBar(
iteration,
total,
decimals=0,
length=10,
fill="#",
printEnd="\n",
):
"""
Calls in a loop to create terminal progress bar.
Args:
iteration (int): Current iteration
total (int): Total iterations (Int)
prefix (... |
#!/usr/bin/env python3
# This software is Copyright (c) 2018, Dhiru Kholia <dhiru at openwall.com> and
# it is hereby released to the general public under the following terms:
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted.
#
# Special thanks goes to https://github... |
import torch
import math
import torch.nn.init
import torch.nn as nn
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import numpy as np
import torch.nn.functional as F
from Utils import L2Norm
def getPoolingKernel(kernel_size = 25):
step = 1. / float(np.floor( kernel_size / 2.))
x_coef ... |
import numpy as np
import copy
class Maze(object):
def __init__(self):
super(Maze, self).__init__()
self.n_action = 2
self.len_state = 2
self.x = 0.1
self.y = 0.1
def reset(self):
self.x = 0.1
self.y = 0.1
return self.get_state()
def set_state(self,x,y):
self.x = np.cl... |
from random import randint
from collections import OrderedDict
# never let the children number get below zero
def nozero(inteiro):
if inteiro > 0:
return inteiro
else:
return 0
lista = []
def main(num_ploxys,num_foods,min_lifespan,max_lifespan):
stringui = str(num_ploxys) + "," + str(num... |
# 3rd party
import lxml.etree # type: ignore
import lxml.objectify # type: ignore
# this package
from mh_utils.xml import XMLFileMixin
from tests.test_worklist_parser.test_integration import worklist_file
class MixinSubclass(XMLFileMixin):
@classmethod
def from_xml(cls, element: lxml.objectify.ObjectifiedElemen... |
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import sys
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.module_utils.six.moves import builtins
from ansible.module_utils._... |
"""Create database models to represent tables."""
from events_app import db
from sqlalchemy.orm import backref
import enum
class Guest(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
email = db.Column(db.String)
phone = db.Column(db.String)
events_attending = db... |
from tests.check import check_result
def test_01():
source = """
def foo(s):
if isinstance(s, unicode):
return s.encode("utf-8")
"""
expected = """
from future.utils import text_type
def foo(s):
if isinstance(s, text_type):
return s.encode("utf-8")
"""
check_result(source, expect... |
#!/usr/bin/env python
import datetime
print(datetime.datetime.now())
import argparse,logging
<<<<<<< HEAD
import torch,time
from ptflops import get_model_complexity_info
=======
import torch,time,datetime
from ptflops import get_model_complexity_info
import numpy as np
>>>>>>> a2f58d0afe8cfc0fc3d7bc3a3c6f7f55da08b5fb
l... |
#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
"""Baby Names exercise
Define the extract_names() function below and c... |
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^treewidget/', include('treewidget.urls')),
]
from django.conf import settings
from django.conf.urls import include, url
if settings.DEBUG:
import debug_toolbar
urlpatte... |
# Copyright (C) 2018 Verizon. 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 ... |
def valid_cross_sale_offer_with_charge():
return {
"charge": {
"amount": 1000,
"currency": "EUR",
},
"title": "Test Title",
"description": "Test Description",
"termsAndConditionsUrl": "https://github.com/securionpay",
"template": "text_only",
... |
from constants.nodetype import TYPE_GATEWAY, TYPE_NODE
from meshnet.heartbeat import Heartbeat
from meshnet.routing import Routing, RoutingEntry
from util.debug import dbg, routing_dbg
from util.nodetype import NodeType
# Initialize Routing
routing = Routing()
routing.add(RoutingEntry(b'\x01\x01\x03', NodeType(TYPE_NO... |
import pyodbc
import time
from datetime import timezone
import datetime
import sys
import glob
import boto3
from botocore.errorfactory import ClientError
import pandas as pd
import csv
import s3fs
import os
## Fetch the arguments
#server = sys.argv[1]
DBName = sys.argv[1]
LSBucket=sys.argv[2]
##... |
# Generated by Django 2.2.1 on 2019-05-31 07:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('read_only_site', '0004_auto_20190531_0700'),
]
operations = [
migrations.AlterField(
model_name='match',
name='match... |
__version__ = '0.1.5'
from .convert import (
adjac_to_nested, set_attr, get_subtree, adjac_to_nested_with_attr)
from .extract import (
remove_node_ids, extract_subtrees, trunc_leaves, drop_nodes, replace_attr)
from .encode import (
to_hash, unique_trees)
from .shingleset import shingleset
|
# The Hazard Library
# Copyright (C) 2012-2016 GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#... |
import random
from typing import List, Optional, Union
import jira
import logging
from jira import JIRAError
from time import sleep
from .ticket import Ticket
from .utils import ObliviousCookieJar
from ...common.enum import to_enumable
DEV_STATUS_API_PATH = "{server}/rest/dev-status/latest/{path}"
JIRA_SERVER_ERROR... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# this is wait We... |
import sys
w, h = map(int, sys.stdin.readline().split())
def main():
if w / h == 16 / 9:
return "16:9"
return "4:3"
if __name__ == "__main__":
ans = main()
print(ans)
|
from app import db
from datetime import datetime, timedelta
"""
the fine for each extra day after the due date
"""
EXTRA_PER_DAY_FINE = 2
class Transaction(db.Model):
__tablename__ = 'transaction'
id = db.Column(db.Integer, primary_key=True)
returned = db.Column(db.Boolean)
issue_date = db.Colum... |
import os
import shutil
from matplotlib import projections
from transformers import LayoutLMTokenizer
import tweepy
import config
import time
import datetime
import plotly.express as px
import undetected_chromedriver as uc
import pandas as pd
import plotly.graph_objects as go
from geopy.geocoders import Nominatim
fro... |
from typing import (
Any,
Iterable,
)
from eth_utils import (
is_bytes,
to_tuple,
)
import rlp
from rlp.codec import _apply_rlp_cache, consume_item
from rlp.exceptions import DecodingError
from rlp.sedes.lists import is_sequence
@to_tuple
def decode_all(rlp: bytes,
sedes: rlp.Serializa... |
import collections
from thegame.abilities import Ability
Vector = collections.namedtuple('Vector', ('x', 'y'))
Vector.__doc__ = '''
A 2D vector.
Used to represent a point and velocity in thegame
'''
class _EntityAttribute:
def __init__(self, doc=None):
self.__doc__ = doc
def __set_name__(self, kla... |
# -*- coding: utf-8 -*-
import json
from plivo.base import (ListResponseObject)
from plivo.exceptions import ValidationError
from plivo.resources import MultiPartyCall, MultiPartyCallParticipant
from plivo.utils.signature_v3 import construct_get_url
from tests.base import PlivoResourceTestCase
from tests.decorators im... |
# pacman imports
from pacman.model.partitionable_graph.abstract_partitionable_vertex import \
AbstractPartitionableVertex
from pacman.model.abstract_classes.virtual_partitioned_vertex import \
VirtualPartitionedVertex
# general imports
from abc import ABCMeta
from six import add_metaclass
from abc import abst... |
import numpy as np
class Datasets():
def create_np_ones_file(row,col,fn="data/nparray.txt"):
np.ones((row,col)).tofile(fn,sep=",")
def create_test_file(bytes_size,fn="data/test_data.dat"):
with open(fn, "wb") as o:
o.write(np.random.bytes(bytes_size))
#https://docs.i... |
import unittest
from stratuslab_usecases.cli.TestUtils import sshConnectionOrTimeout
import BasicVmLifecycleTestBase
class testVmIsAccessibleViaSsh(BasicVmLifecycleTestBase.BasicVmTestBase):
vmName = 'ttylinux'
def test_usecase(self):
sshConnectionOrTimeout(self.ip_addresses[0])
def suite():
... |
while True:
tot = 0
quantcopias = int(input("Digite a quantidade de copias normais: "))
quantcopiasverso = int(input("Digite a quantidade de copias com versos: "))
print("-=" * 30)
if quantcopias > 0:
print("{} copias normais são {} MT".format(quantcopias, quantcopias * 1.5))
to... |
KEYDOWN = 'KEYDOWN'
KEYUP = 'KEYUP'
DIRDOWN = 'DIRDOWN'
DIRUP = 'DIRUP'
LEFTTEAM = 'LEFTTEAM'
RIGHTTEAM = 'RIGHTTEAM'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.