content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import imageio
import pandas as pd
import matplotlib.pyplot as plt
import trackviz.static
tracks = pd.read_csv('sample_data/ant_tracking_res.csv').rename(columns={'frame': 't'})
fig, ax = trackviz.static.trajectory_3d(tracks, color='t', line_kws=dict(linewidths=0.5))
fig.savefig('output/static_3d_color_frame.png')
# ... | python |
from typing import Any
from typing import Optional
import aiohttp
from ...box import box
from ...command import argument
from ...command import option
from ...event import Message
from ...utils import json
box.assert_config_required('NAVER_CLIENT_ID', str)
box.assert_config_required('NAVER_CLIENT_SECRET', str)
LANG... | python |
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
Original C++ source file: image_ops.cc
"""
import collections as _collections
from tensorflow.python.eager import execute as _execute
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import core... | python |
"""
Copyright 2018 Ederson Bilhante
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 ... | python |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from einops import rearrange
from torch import Tensor
device = "cuda" if torch.cuda.is_available() else "cpu"
DEVICE = device
class PositionalEncoding(nn.Module):
def __init__(self, d_model: int, dro... | python |
# teste = list()
# teste.append('Henrique')
# teste.append(15)
#
# galera = list()
# galera.append(teste[:])
#
# teste[0] = 'Maria'
# teste[1] = 22
#
# galera.append(teste[:])
# print(galera)
galera = [['Joรฃo', 19], ['Alana', 16], ['Maria', 33], ['Pedro', 25]]
for p in galera:
print(f'Nome: {p[0]} \nIdade: {p[1]}... | python |
from django.db import IntegrityError
from django.db.models import Q
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from cajas.boxes.services.box_daily_square_manager import BoxDailySquareManager
from cajas.users.models.employee import Employee
... | python |
#!/usr/bin/env python3
# Copyright (C) 2018 Adrian Herrera
#
# 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, modi... | python |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.12.8)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\xb4\xdf\
\xff\
\xd8\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x00\x00\x01\x00\
\x01\x00\x00\x... | python |
class RunnerTemplate:
def exec(self, data):
pass
| python |
import asyncio
import logging
import re
from io import BytesIO
import discord
from redbot.core import checks, commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import box, inline
from tsutils.emoji import char_to_emoji, fix_emojis_for_server, replace_emoji_names_with_code
logger = loggin... | python |
# Lint as: python3
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | python |
# LIBRARIES
from django.db import models
from django.db.utils import IntegrityError
from django.contrib.contenttypes.models import ContentType
# DJANGAE
from djangae.db import transaction
from djangae.fields import (
ComputedCharField,
GenericRelationField,
ListField,
RelatedSetField,
RelatedListFi... | python |
class DocumentOCRViewTestMixin(object):
def _request_document_content_view(self):
return self.get(
viewname='ocr:document_ocr_content', kwargs={
'document_id': self.test_document.pk
}
)
def _request_document_content_delete_view(self):
return self... | python |
import attr
import aiohttp
import asyncio
from typing import Any, Optional
# Not frozen, since that doesn't work in PyPy
@attr.s(slots=True, auto_exc=True, auto_attribs=True)
class FacebookError(Exception):
"""Base class for all custom exceptions raised by ``fbchat``.
All exceptions in the module inherit thi... | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | python |
"""Lambda pocket-to-kindle create_epub."""
from datetime import datetime
from os import environ as env
from os import stat
from shlex import join
from subprocess import (run, CalledProcessError, TimeoutExpired)
from tempfile import NamedTemporaryFile
from uuid import uuid4
import utils
import utils.aws as aws
import u... | python |
# default_settings.py
#
# Author(s):
# Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph>
#
# Licensed under MIT
# Version 1.0.0
import os
#========================================================
# [Flask-specific configuration] ::start
#========================================================
DEBUG = False
CACH... | python |
from __future__ import annotations
import typing
if typing.TYPE_CHECKING:
from src.typehints import AnyCallableT
__all__: tuple[str, ...] = ("is_classvar",)
def is_classvar(fn: AnyCallableT) -> bool:
return hasattr(fn, "__classvar__")
| python |
#!/usr/bin/python
from urllib2 import urlopen
import json, re
from json import loads
def print_json(j):
j = json.dumps(j, sort_keys=True, indent=2)
# j = re.sub(j, r'\n', '\\n')
print j
def my_urlopen(url):
print "\nurlopen:", url
return urlopen(url)
print "\nget all projects"
req = urlopen('ht... | python |
"""Tests for the Update integration init."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from typing import Any
from unittest.mock import Mock, patch
from aiohttp import ClientWebSocketResponse
import pytest
from homeassistant.components.update import (
DOMAI... | python |
class Events:
def __getattr__(self, name):
if hasattr(self.__class__, '__events__'):
assert name in self.__class__.__events__, \
"Event '%s' is not declared" % name
self.__dict__[name] = ev = _EventSlot(name)
return ev
def __repr__(self):
retu... | python |
"""
Code modified from PyTorch DCGAN examples: https://github.com/pytorch/examples/tree/master/dcgan
"""
import argparse
import os
import random
import torch
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.utils.data
def get_parsers():
parser = argparse.ArgumentParser()
parser.add_... | python |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class FunctionRepresentation(nn.Module):
"""Function to represent a single datapoint. For example this could be a
function that takes pixel coordinates as input and returns RGB values, i.e.
f(x, y) = (r, g, b).
Args:
... | python |
import random
import os
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
plt.ion()
PROJECT_FOLDER = os.path.dirname(__file__)
DATASET_FOLDER = PROJECT_FOLDER + '/data/columbia-prcg-datasets'
PHOTO_FOLDER = DATASET_FOLDER + '/google_images/'
CG_FOLDER = DATASET_FOLDER + '/prcg_images/'
NUM_IMA... | python |
import os
import tempfile
from ..spectrify import load_data, spectrify_audios
import numpy as np
def test_spectrify():
out_bins = 80
samplerate = 44100
frame_len = 0.1
input_fnames = [os.path.dirname(__file__)+"/test.mp3"]
spec_datas = [load_data(filename,samplerate) for filename in input_fnames]
... | python |
from ..grammar import Grammar
from typing import Deque
from ..tokenizer import Token
class FinalToken:
def __init__(self):
self.name = '$'
self.lexeme = '$'
class Parser:
def __init__(self, grammar: Grammar, action, go_to):
self.grammar = grammar
self.action = action
... | python |
def processChange(job):
service = job.service
args = job.model.args
if args.pop('changeCategory') != 'dataschema':
return
if 'url' in args:
service.model.data.url = args['url']
if 'eventtypes' in args:
service.model.data.eventtypes = args['eventtypes']
service.saveAll... | python |
"""Fire animation, by Uck!"""
import dcfurs
import random
# Colors, from top to bottom of the fire.
colors = [0, 0x1f0f0f, 0x3f0000, 0xff0000, 0xff7f00, 0xffff00, 0x1f007f,
0x0000ff, 0xffffff]
# Bitmask values copied from emote.boop().
boop_mask = [
0x0e48e,
0x12b52,
0x12b52,
0x0eb4e,
0... | python |
from agents.common import PLAYER1, PLAYER2, initialize_game_state, apply_player_action, \
evaluate_rows, is_player_blocking_opponent, is_player_winning
def test_evaluate_rows_True_Player1_is_player_blocking_opponent():
game = initialize_game_state()
num_rows = game.shape[0]
num_cols = game.shape[1]
... | python |
# project/server/tests/base.py
from flask_testing import TestCase
from price_picker import db, create_app
from price_picker.common.create_sample_data import create_sample_data
app = create_app()
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object("config.TestingConfig")
... | python |
from resotolib.baseresources import BaseResource
import resotolib.logger
import socket
import multiprocessing
import resotolib.proc
from concurrent import futures
from resotolib.baseplugin import BaseCollectorPlugin
from argparse import Namespace
from resotolib.args import ArgumentParser
from resotolib.config import Co... | python |
from enum import Enum
__NAMESPACE__ = "http://www.opengis.net/gml"
class KnotTypesType(Enum):
"""
This enumeration type specifies values for the knotsโ type (see ISO
19107:2003, 6.4.25).
"""
UNIFORM = "uniform"
QUASI_UNIFORM = "quasiUniform"
PIECEWISE_BEZIER = "piecewiseBezier"
| python |
#!/usr/bin/env python3
"""Bumps the detect-secrets version,
in both `detect_secrets/__init__.py` and `README.md`.
Then commits.
"""
import argparse
import pathlib
import subprocess
import sys
PROJECT_ROOT = pathlib.Path(__file__).absolute().parent.parent
INIT_FILE_PATH = PROJECT_ROOT.joinpath('detect_secrets/__init_... | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from models.archs.dcn.deform_conv import ModulatedDeformConvPack as DCN_sep
class PCD_Align(nn.Module):
''' Alignment module using Pyramid, Cascading and Deformable convolution
with 3 pyramid levels.
'''
def... | python |
import os
os.chdir("../..")
print(os.getcwd())
import sys
sys.path.append('')
from envs.aslaug_v1_cont import AslaugEnv
env = None
def setup():
global env, obs
env = AslaugEnv(gui=True)
os.chdir("baselines/mpc-acado")
obs = env.reset()
def get_obs():
global obs
return obs.tolist()
def step(inp)... | python |
import re
import sqlite3
import util
import db
def main():
con = db.connect_db()
tbl = "art_of_worldly_wisdom"
db.purge_table(con, tbl)
db.init_table(con, tbl)
cur = con.cursor()
sql = f"INSERT INTO {tbl} (_id, _body) VALUES (?, ?)"
body_lines = []
is_last_line_page_break = False
... | python |
# 5_pennyBoard.py
# A program that assigns each square on a checkerboard to a set number of pennies getting exponentially bigger
# Date: 9/22/2020
# Name: Ben Goldstone
square = 1
numberOfPennies = 0.01
#Constants
ONEPENNYTOGRAMS = 2.5
ONEPOUNDTOGRAMS = 453.6
ONEPOUNDOFCOPPERTODOLLARS = 3.15
#counters
totalAmountOfMon... | python |
"""attendanceManagement URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='ho... | python |
"""Tests for the to_cnf transformation."""
import unittest
from tt.errors import InvalidArgumentTypeError
from tt.expressions import BooleanExpression
from tt.transformations import to_cnf
class TestExpressionToCnf(unittest.TestCase):
def assert_to_cnf_transformation(self, original, expected):
"""Helpe... | python |
initialized = True
class TestFrozenUtf8_1:
"""\u00b6"""
class TestFrozenUtf8_2:
"""\u03c0"""
class TestFrozenUtf8_4:
"""\U0001f600"""
def main():
print("Hello world!")
if __name__ == '__main__':
main()
| python |
from __future__ import print_function, division, absolute_import
from datetime import timedelta
import errno
import logging
import socket
import struct
import sys
from tornado import gen
from tornado.iostream import IOStream, StreamClosedError
from tornado.tcpclient import TCPClient
from tornado.tcpserver import TCPS... | python |
from output.models.nist_data.atomic.integer.schema_instance.nistschema_sv_iv_atomic_integer_max_inclusive_3_xsd.nistschema_sv_iv_atomic_integer_max_inclusive_3 import NistschemaSvIvAtomicIntegerMaxInclusive3
__all__ = [
"NistschemaSvIvAtomicIntegerMaxInclusive3",
]
| python |
import pygame
import copy
from vector import Vec2, Vec4
from pixel import Pixel
from colors import *
from mymath import clamp, get_line_pixels
class Canvas:
def __init__(self, x, y, width, height, zoom=1.00):
self.pos = Vec2(x, y)
self.size = Vec2(width, height)
self.zoom = zoom
se... | python |
from __future__ import annotations
from threading import Thread
from typing import Callable, Optional
from .interfaces import ITimeoutSendService
from ..clock import IClock
from ..service import IService, IServiceManager
from ..send import ISendService
from ..util.Atomic import Atomic
from ..util.InterruptableSleep imp... | python |
"""
IOEcho device, receive GPIO, send them thought TCP to target
"""
__all__ = ['IOEcho']
__version__ = '0.1'
from .deviceBase import DeviceBase
from time import sleep
from lib.common import PrintColor
import requests
import json
from socket import *
try:
import RPi.GPIO as GPIO
is_running_on_pi = True
except Run... | python |
import os
import sys
import numpy as np
import csv
import matplotlib.pyplot as plt
from src import readFiles as rf
from os import listdir
import re
def getDirectoriesAtPath(path):
return [name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name))]
# Function to read the execution time an applic... | python |
class NoSuchOmekaClassicItemException(Exception):
pass
| python |
'''
1) Add an item to your cart
2) Proceed to checkout
3) Quit
$ 1
Enter item description: Red Bull
Enter item quantity: 48
Price per unit: $2.00
$ 2
48 - Red Bull @ $2.00 ea
Subtotal: $96.00
Tax (4.712%): $4.52
Total: $100.52
age = raw_input("How old is you? ")
height ... | python |
from django.template.defaulttags import register
@register.filter
def index(sequence, position):
return sequence[position] | python |
# Noysim -- Noise simulation tools for Aimsun.
# Copyright (c) 2010-2011 by Bert De Coensel, Ghent University & Griffith University.
#
# Run the viewer as a windows program
import noysim.viewer
app = noysim.viewer.wx.PySimpleApp()
app.frame = noysim.viewer.ViewerFrame()
app.frame.Show()
app.MainLoop()
| python |
__all__ = ('reduce',)
from asyncio import create_task
from ._create_channel import create_channel
async def _reduce(out, fn, ch, init):
"""Reduce items from channel."""
acc = init
async for x in ch:
acc = fn(acc, x)
await out.put(acc)
out.close()
def reduce(fn, ch, init=None, *,
... | python |
class WizardPlayer:
def __init__(self, player_id, np_random):
''' Initilize a player.
Args:
player_id (int): The id of the player
'''
self.np_random = np_random
self.player_id = player_id
self.hand = []
self.stack = [] # might need to be changed... | python |
"""
ะะฐ ัะตะณะธะพะฝะฐะปัะฝะพะผ ััะฐะฟะต ะัะตัะพััะธะนัะบะพะน ะพะปะธะผะฟะธะฐะดั ัะบะพะปัะฝะธะบะพะฒ ะฟะพ ะธะฝัะพัะผะฐัะธะบะต ะฒ 2009 ะณะพะดั ะฟัะตะดะปะฐะณะฐะปะฐัั ัะปะตะดัััะฐั ะทะฐะดะฐัะฐ.
ะัะตะผ ะธะทะฒะตััะฝะพ, ััะพ ัะพ ะฒัะตะผะตะฝะตะผ ะบะปะฐะฒะธะฐัััะฐ ะธะทะฝะฐัะธะฒะฐะตััั, ะธ ะบะปะฐะฒะธัะธ ะฝะฐ ะฝะตะน ะฝะฐัะธะฝะฐัั ะทะฐะปะธะฟะฐัั. ะะพะฝะตัะฝะพ, ะฝะตะบะพัะพัะพะต ะฒัะตะผั
ัะฐะบัั ะบะปะฐะฒะธะฐัััั ะตัะต ะผะพะถะฝะพ ะธัะฟะพะปัะทะพะฒะฐัั, ะฝะพ ะดะปั ะฝะฐะถะฐัะธะน ะบะปะฐะฒะธั ะฟัะธั
ะพะดะธัััั ะธัะฟะพะปัะทะพ... | python |
import logging
import docker
from docker.models.containers import Container
from factioncli.processing.cli import log
from factioncli.processing.cli.printing import error_out
client = docker.from_env()
class container_status:
name = ""
status = ""
ip_address = ""
message = ""
created = ""
def ... | python |
"""
The ``zen.nx`` module provides functions for converting graph objects to and from the `NetworkX <http://networkx.lanl.gov/>`_ library.
.. autofunction:: to_networkx(G)
.. autofunction:: from_networkx(G)
"""
from graph import Graph
from digraph import DiGraph
import networkx
__all__ = ['to_networkx','from_netwo... | python |
# encoding: utf-8
#
from flask.sessions import SessionInterface as FlaskSessionInterface
from mo_dots import Data, wrap, exists, is_data
from mo_future import first
from mo_json import json2value, value2json
from mo_kwargs import override
from mo_logs import Log
from mo_math import bytes2base64URL, crypto
from mo_thr... | python |
#!/usr/bin/env pypy
from random import *
from sys import *
n, q = map(int, argv[1:])
print n
L = range(0, n)
shuffle(L)
print ' '.join(map(str, L))
print ' '.join(map(str, (randint(1, i - 1) for i in xrange(2, n + 1))))
print q * 2
for i in xrange(q):
print 1, randint(1, n), randint(1, n)
print 2
| python |
job = 'source $HOME/.bashrc ; source activate threshold-devel ; python experiment.py --method {} --thresh {} --max-iters {} --num-burn {} --num-samples {} --num-steps-hyper {} --partial-momentum {} --check-prob 0.01 {} {} 2>/dev/null'
with open('joblist.txt', 'w') as f:
for nb in [10000]:
for ns in [100000... | python |
import base64
import cattle
import os
import pytest
import random
import time
import inspect
from datetime import datetime, timedelta
import requests
import fcntl
import logging
@pytest.fixture(scope='session', autouse=os.environ.get('DEBUG'))
def log():
logging.basicConfig(level=logging.DEBUG)
@pytest.fixture(... | python |
import sys
def is_triangle(a,b,c):
if a + b > c:
if a + c > b:
if b + c > a:
print("True")
else:
print("False")
else:
print("False")
else:
print("False")
def read_nonnegative(word):
num = float(input(word))
if n... | python |
import os
import easypost
from dotenv import load_dotenv
load_dotenv()
easypost.api_key = os.getenv('EASYPOST_TEST_API_KEY')
try:
shipment = easypost.Shipment.retrieve('shp_123...')
smartrates = shipment.get_smartrates()
print(smartrates)
except Exception as error:
print(error)
| python |
from django.template import Library, Node, TemplateSyntaxError
from django.utils.encoding import force_unicode
from convert.base import MediaFile, EmptyMediaFile, convert_solo
from convert.conf import settings
register = Library()
class ConvertBaseNode(Node):
def error(self, context):
if sett... | python |
import examples.PEs.alu_basic as alu_basic
import examples.PEs.PE_lut as PE_lut
from hwtypes import BitVector as BV
from peak import family
from metamapper import CoreIRContext
def test_alu():
CoreIRContext(reset=True)
width = 8
ALU_fc = alu_basic.gen_ALU(width)
isa_fc = alu_basic.gen_isa(width)
is... | python |
"""
This module contains the WPS inputs and outputs that are reused across multiple WPS processes.
"""
from dataclasses import fields
from pywps import (
FORMATS,
ComplexInput,
ComplexOutput,
Format,
LiteralInput,
LiteralOutput,
)
from pywps.app.Common import Metadata
from ravenpy.config.rvs... | python |
import os
from deepartransit.utils import data_generator
from deepartransit.utils.config import process_config
config_path = os.path.join('tests', 'deepar_config_test.yml')
def test_data():
config = process_config(config_path)
data = data_generator.DataGenerator(config)
batch_Z, batch_X = next(data.nex... | python |
''' Helper functions to select and combine data '''
from __future__ import division
import logging
import re
import os
from collections import Iterable
import numpy as np
import tables as tb
import numexpr as ne
from tqdm import tqdm
from beam_telescope_analysis.telescope.telescope import Telescope
from beam_telesc... | python |
# coding: utf-8
"""
Gate API v4
Welcome to Gate.io API APIv4 provides spot, margin and futures trading operations. There are public APIs to retrieve the real-time market statistics, and private APIs which needs authentication to trade on user's behalf. # noqa: E501
Contact: support@mail.gate.io
Gen... | python |
import pathlib
import numpy as np
import matplotlib.pyplot as plt
from os import listdir
from tqdm import tqdm
from visionutils import flow2mag
# workaround for bug https://github.com/tqdm/tqdm/issues/481
tqdm.monitor_interval = 0
font = {'family' : 'DejaVu Sans',
'weight' : 'bold',
'size' : 50}
pl... | python |
#Declare and initialize the variables
monthlyPayment = 0
loanAmount = 0
interestRate = 0
numberOfPayments = 0
loanDurationInYears = 0
#Ask the user for the values needed to calculate the monthly payments
strLoanAmount = input("How much money will you borrow? ")
strInterestRate = input("What is the interest rate on th... | python |
from difflib import SequenceMatcher
from six import iteritems
from datadog_checks.base.stubs.common import MetricStub, ServiceCheckStub
'''
Build similar message for better test assertion failure message.
'''
MAX_SIMILAR_TO_DISPLAY = 15
def build_similar_elements_msg(expected, submitted_elements):
"""
Ret... | python |
from database.mysql import MySQLDatabase
from settings import db_config
"""
Retrieve the settings from the
'db_config' dictionary to connect to
our database so we can instantiate our
MySQLDatabase object
"""
db = MySQLDatabase(db_config.get('db_name'),
db_config.get('user'),
db_c... | python |
# -*- coding: utf-8 -*-
# ======================================================================================================================
# Copyright (ยฉ) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie,
# Caen, France. =
# CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See ... | python |
t1 = [[1], [1], [1], [1], [1]]
t2 = [[1], [1, [1, 1]], [1]]
t3 = [[1], [1, [1, [1], 1]], [1]]
| python |
# --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
# code starts here
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include = 'object')
print(categorical_var)
numerical_var = bank.select_dtypes(include = 'number')
print(numerical_var)
# code end... | python |
# -----------------------------------------------------------------------------
# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens & Font Bureau
# www.pagebot.io
#
# P A G E B O T
#
# Free to use. Licensed under MIT conditions
# Made for usage in DrawBot, www.drawbot.com
# -----------------... | python |
#entrada
while True:
n = int(input())
if n == 0:
break
tempos = str(input()).split()
#processamento
tempoTotal = 10
for i in range(1, len(tempos)):
if (int(tempos[i]) - int(tempos[i - 1])) < 10:
tempoTotal += int(tempos[i]) - int(tempos[i - 1])
else:
... | python |
#!/usr/bin/env python
# Copyright (c) 2011 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.
"""A class to help start/stop a local apache http server."""
from __future__ import print_function
import logging
import optparse... | python |
import sys
a = sys.stdin.readline().split()
def main():
a.sort(reverse=True)
a.insert(2, '+')
return eval(''.join(a))
if __name__ == '__main__':
ans = main()
print(ans)
| python |
from config.config import success, header, proxy_ip_type
from proxyip import proxy_ip
def get_rest_list(sort: int):
'''
:param sort: 0ๆๆฐ๏ผ1ๆไฝไปทๆ ผ
:return:
'''
api = "https://api-app.ibox.art/nft-mall-web/v1.2/nft/product/getResellList?origin=0&page=1&pageSize=20&sort=%s&type=0" % sort
while True:... | python |
"""
This file contains the necessary to reconstruct the intermediary featuress from
a save of the models an inputs
Author Hugues
"""
import torch
from pathlib import Path
if __name__ == '__main__':
import sys
sys.path.append("..")
from param import data_path
file_location = Path(data_path) / Path('models')
... | python |
from discord import DMChannel, User
from discord import Message
import stummtaube.data.rounds as rounds_management
from stummtaube import main
from stummtaube.commands import START, JOIN, END
from stummtaube.data.game import players
from stummtaube.data.round import Round
async def handle_message(message: Message) -... | python |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.ops.range import Range
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.graph.graph import Node
class RangeFrontExtractor(FrontExtractorOp):
op = 'Range'
enabled = Tru... | python |
from .bslcp import bslcp
from .phoenix14 import phoenix14
__all__ = (
"bslcp",
"phoenix14",
)
| python |
from __future__ import division, print_function
import numpy as np
from mlfromscratch.unsupervised_learning import Apriori
def main():
# Demo transaction set
# Example 2: https://en.wikipedia.org/wiki/Apriori_algorithm
transactions = np.array([[1, 2, 3, 4], [1, 2, 4], [1, 2], [2, 3, 4], [2, 3], [3, 4], [... | python |
from aiogram import types
from ..bot import bot, dispatcher
@dispatcher.message_handler(commands=["start"])
async def start_handler(message: types.Message):
await message.answer(bot.phrases.start_message)
| python |
from itertools import chain
from euclidean.R2.cartesian import P2, V2, cross2
from euclidean.R2.line import LineSegment
from .hull import convex_hull
from .line_sweep import shamos_hoey
class Polygon:
"""
"""
@classmethod
def ConvexHull(cls, points):
return cls(convex_hull(points), is_conv... | python |
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("auth", "0006_require_contenttypes_0002"),
]
operations = [
migrations.CreateModel(
... | python |
import requests
import time
class PickCourse(object):
def __init__(self):
"""
ๅคๅถ็ฒ่ดด่ฏทๆฑๅคด
ๅฐไธ้ขๅผไธไธๆ ท็ๆขๆๅณๅฏ
"""
self.headers = {
'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'content-typ... | python |
import contextlib
from Qt import QtCore
def _iter_model_rows(
model, column, include_root=False
):
"""Iterate over all row indices in a model"""
indices = [QtCore.QModelIndex()] # start iteration at root
for index in indices:
# Add children to the iterations
child_rows = model.rowCou... | python |
#!/usr/bin/env python
# Programa 5.1 - Estrutura de repetiรงรฃo while
x = 1
while x <= 3:
print(x)
x = x + 1
print (' FIM ') | python |
# 2019-11-24 20:59:47(JST)
import sys
def main():
n = int(sys.stdin.readline().rstrip())
m = map(int, sys.stdin.read().split())
ab = list(zip(m, m))
graph = [[] for _ in range(n + 1)]
for a, b in ab:
graph[a].append(b)
graph[b].append(a)
root = 1
parent = [... | python |
# Copyright (c) 2017 The Johns Hopkins University/Applied Physics Laboratory
# 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/LICEN... | python |
import asyncio
import nertivia
import nertivia.bot
from nertivia import http
URL = "https://nertivia.net/api/messages/channels/"
URL_MSG = "https://nertivia.net/api/messages/"
URL_STA = "https://nertivia.net/api/settings/status"
class Message:
# __slots__ = ('id', 'content', 'author')
def __init__(self, me... | python |
from TestHelperSuperClass import testHelperSuperClass
from unittest.mock import patch
import passwordmanpro_cli
import datetime
from python_Testing_Utilities import assertMultiLineStringsEqual
from samplePayloadsAndEnvs import envNoKey, envUrlWithSlash, envAPIKEYFILE, env, resourseResponse, resourseResponseRAW, resour... | python |
#!/usr/bin/env python3
import utils, os, random, time, open_color, arcade
utils.check_version((3,7))
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Sprites Example"
class MyGame(arcade.Window):
def __init__(self):
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
file_path = ... | python |
#!/usr/bin/python3
import sys
import os
from tqdm import tqdm
from binascii import b2a_hex
import pandas as pd
import pickle
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPa... | python |
# ___________________________________________________________________________
#
# Prescient
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
# This software is ... | python |
import telegram
from telegram import *
from telegram.ext import *
import os
import responses
from dotenv import load_dotenv
load_dotenv()
TELEBOT_API_KEY = os.environ.get('TELE_BOT_API')
bot = telegram.Bot(token=TELEBOT_API_KEY)
updater = Updater(token=TELEBOT_API_KEY, use_context=True)
# Dispatcher
ud = updater.dis... | python |
#!/usr/bin/python
# coding=utf-8
class BadRequest(Exception):
def __init__(self):
self.message = "Bad request"
class DuplicationError(BadRequest):
def __init__(self, field):
self.message = "Field {wrong} already exist".format(wrong=field)
class MissingFieldError(BadRequest):
def __init... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.