content stringlengths 5 1.05M |
|---|
from rest_framework import serializers
class IndexSerializer(serializers.Serializer):
content = serializers.StringRelatedField()
class Meta:
fields = ['content']
|
# Generated by Django 3.2.7 on 2021-10-23 13:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('social', '0004_alter_recipe_prep_time_units'),
]
operations = [
migrations.AlterField(
model_name='recipe',
name='co... |
def print_rel_notes(name, org, repo, version, outs=None, setup_file="",
deps_method="", toolchains_method=""):
tarball_name = ":%s-%s.tar.gz" % (repo, version)
cmd = [
"$(location @rules_pkg//releasing:print_rel_notes)",
"--org=%s" % org,
"--repo=%s" % repo,
"... |
#-*- coding: ISO-8859-1 -*-
def _():
import sys
if sys.platform == 'cli':
import clr
clr.AddReference('IronPython.Wpf')
_()
del _
from _wpf import *
|
# !/Users/xxpang/anaconda3/bin/python3
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(level=logging.INFO)
import asyncio
import os
import json
import time
from datetime import datetime
from aiohttp import web
def index(request):
return web.Response(body=b'<html><title>127.0.0.1</title><h1>Awesome</h1... |
#!/usr/bin/env python3
"""
Advent of Code 2017: Day #
"""
import os
from shared.readdayinput import readdayinput
def first_half(dayinput):
"""
first half solver:
"""
lines = dayinput.split('\n')
programs = {}
for line in lines:
key, val = line.split(' <-> ')
val = [int(x) for x... |
import pygame
import lib
import lib.constants as const
import lib.common as common
import ai.neat.neat as neat
from ai.neatinterface.smartcar import SmartCar
pygame.init()
# game specific neat interface
# this straps on to the original Core class
# by inheriting it and overriding necessary methods
# and adding exte... |
from django.contrib import admin
from .models import Container
from .actions import start_containers, stop_containers, restart_containers
class ContainerAdmin(admin.ModelAdmin):
list_display = ['container_id', 'name', '_image','_networks', '_ip', 'status', 'active']
actions = [start_containers, stop_contain... |
from uliweb.orm import *
import datetime
from uliweb.i18n import ugettext_lazy as _
from uliweb import functions
from . import encrypt_password, check_password
from uliweb.utils.common import get_var
class User(Model):
username = Field(str, verbose_name=_('Username'), max_length=30, unique=True, index=True, nulla... |
import random
class DiffieHellman:
def __init__(self, generator, prime_divider):
if prime_divider <= 2:
raise ValueError('prime_divider must be gross than 2')
self.__prime_divider = prime_divider
self.__private_key = random.randint(2, prime_divider - 1)
self.__public_ke... |
import sys
import bisect
def fib(n):
a, b = 0, 1
while b < n:
yield b
a, b = b, a + b
fibArray = list(fib(100000005))
sys.stdin = open('input.txt')
numTest = int(input())
for itertest in range(numTest):
N = int(input())
print '%d =' % N,
idx = bisect.bisect_right(fibArray, N)
r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This code is from https://github.com/DaikiShimada/masalachai
"""
import numpy as np
import six
from six.moves.urllib import request
import tarfile
fname = 'cifar-10-python.tar.gz'
batches = 5
batchsize = 10000
category_names = ['airplane', 'automobile', 'bird', 'ca... |
from PyQt6.QtWidgets import QApplication, QMainWindow, QSpinBox
from PyQt6.QtCore import Qt, QSize
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Moja aplikacja")
self.widget = QSpinBox()
self.widget.setMinimum(-20)
sel... |
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.validators import UnicodeUsernameValidator
from django.db import models
class CustomUserManager(BaseUserManager):
def create_user(self, email, username, first_name,
... |
from bs4 import BeautifulSoup
class GoogleExtractionModule(object):
def find_queries(html):
""" Finds queries and extracts them from Google SQL documentation on
cloud.google.com.
Code blocks are in <code> tags with parent <pre> tags.
Args:
html: HTML response which co... |
class BufferedGraphicsManager(object):
""" Provides access to the main buffered graphics context object for the application domain. """
Current = None
|
#!/usr/bin/env python3
"""
USAGE:
yb_sysprocs_bulk_xfer.py [options]
PURPOSE:
Transformed subset active bulk transfers (ybload & ybunload) from sys.load and sys.unload.
OPTIONS:
See the command line help message for all options.
(yb_sysprocs_bulk_xfer.py --help)
Output:
The report as a ... |
#!/usr/bin/env python
# coding: utf-8
#
# Author: Kazuto Nakashima
# URL: http://kazuto1011.github.io
# Created: 2017-10-11
from __future__ import print_function
import argparse
import torch
import torchvision
from smooth_grad import SmoothGrad
from torchvision import transforms
def main(args):
# Loa... |
from PuzzleLib.Models.Nets.Inception import loadInceptionBN, loadInceptionV3
from PuzzleLib.Models.Nets.LeNet import loadLeNet
from PuzzleLib.Models.Nets.MiniYolo import loadMiniYolo
from PuzzleLib.Models.Nets.NiN import loadNiNImageNet
from PuzzleLib.Models.Nets.OpenPoseCOCO import loadCOCO
from PuzzleLib.Models.Nets.... |
i=20
j=2
i/j
print(i)
|
from pathlib import Path
import fire
from composo import ioc
from appdirs import user_config_dir
def main():
ioc.App.config.from_yaml(Path(user_config_dir("composo")) / "config.yaml")
app = ioc.App.app()
fire.Fire(app)
def run():
app = ioc.App.app()
app.new("test", lang="shell")
if __name__ ... |
from .Visualizer import visualize_binary_tree |
# from app import db
import pymongo
from pprint import pprint
import dns
import pprint
from bson.json_util import dumps, _json_convert
from bson.objectid import ObjectId
con = pymongo.MongoClient('mongodb+srv://root-condor:[email protected]/CondorMarket?retryWrites=true')
db = con.CondorMarke... |
def setup_package():
pass
def teardown_package():
pass
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^victim', views.index, name='index'),
url(r'^form', views.form, name='form'),
]
|
def ready_operations(bot):
print("Logged in as")
print(bot.user.name)
print(bot.user.id)
print('------')
github = "See my GitHub for help and other information. " \
"https://github.com/ElectricNinja315/harvest-bot"
meme_music = "billy bragg the internationale"
champions = [
"Aatrox",
... |
import gpbasics.global_parameters as global_param
global_param.ensure_init()
from sklearn.cluster import DBSCAN
from typing import List
import numpy as np
import gpbasics.KernelBasics.PartitioningModel as pm
import gpbasics.DataHandling.DataInput as di
import gpbasics.Metrics.Metrics as met
import time
import logging... |
import re
my_str = '''Write a regular expression that
can find all amounts of money in a text. Your
expression should be able to deal with different formats
and currencies, for example £50,000 and £117.83m as well as 300p,
500m euro, 338bn euros, $150bn and $92.88. Make sure that
you can at least detect ... |
import os
import yaml
import pprint
import traceback
import src.libs.gen_utils as gen_utils
from src.classes.software import Software
from src.definitions import BACKUP_FOLDER, TEMPLATES_FOLDER
from getpass import getuser
from jinja2 import Template
class Themer():
def __init__(self, config_file, **kwargs):
... |
import pathlib
from setuptools import setup, find_packages
from fcrawler import __version__
here = pathlib.Path(__file__).parent.resolve()
long_description = (here / 'README.md').read_text(encoding='utf-8')
setup(
name="fcrawler",
version=__version__,
description="Python application that can be used to ... |
# coding: utf-8
import tensorflow as tf
import numpy as np
import os
from settings import DIR2SAVE_CARD_NO_RECORDS, \
CARDNO_IMG_HEIGHT, CARDNO_IMG_CHANNELS, DIR2SAVE_CARDNO_EVAL_RECORDS, \
encode_map, decode_map
import threading
dir2save_train_records = DIR2SAVE_CARD_NO_RECORDS
dir2save_eval_rec... |
from unittest import TestCase, TestSuite, TextTestRunner, main
from sample_problem import sample_problem
class SampleBeginnerTestCase(TestCase):
def test_sample_problem(self):
self.assertEqual(sample_problem('test1'), 'test1')
self.assertEqual(sample_problem('test2'), 'test2')
print("\n.Pa... |
import os
import pathlib
from setuptools import setup
HERE = pathlib.Path(os.path.abspath(os.path.dirname(__file__)))
VERSION = "VERSION-NOT-FOUND"
for line in (HERE / "snails.py").read_text().split("\n"):
if line.startswith("__version__"):
VERSION = eval(line.split("=")[-1])
README = (HERE / "README.rst")... |
#
#
#
# DEPRECATED - put POST handler functions in handler classes
#
#
#
#
#
#
#!/usr/bin/env python
#
# Copyright 2012 Andy Gimma
#
# 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... |
import asyncio, config, discord, random, aiohttp
import logging
from .utils import instance_tools
log = logging.getLogger()
statuses = ["OwO whats n!help", "🤔🤔🤔", "👀", "(╯°□°)╯︵ ┻━┻",
"¯\_(ツ)_/¯", "┬─┬ノ(ಠ_ಠノ)", "><(((('>", "_/\__/\__0>", "ô¿ô", "°º¤ø,¸¸,ø¤º°`°º¤ø,", "=^..^=",
"龴ↀ◡ↀ龴", "^⨀ᴥ⨀^"... |
env_dataset = "mnist_full" |
# Exercício Python 026: Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra "A", e
# em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.
phrase = str(input('Enter a phrase: ')).upper().strip()
count_letter = phrase.count('A')
first_letter = phrase.fi... |
"""
lec3
"""
my_list = [1,2,3,4,5]
print(my_list)
my_nested_list = [1,2,3,[1,2,3,4,5]]
print(my_nested_list)
my_list[0]=6
print(my_list)
print(my_list[0])
print(my_list[1])
print(my_list[-1])
print(my_list)
print(my_list[1:3])
print(my_list[:])
|
#!/usr/bin/python
# Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""This module provides maps and sets that report unused elements."""
_monitored_values ... |
import keen
import subprocess
import copy
from collections import defaultdict
keen.project_id = "594bd6a50935ce9ceaaaaf63"
keen.read_key = '7856E5E161A29A43701E1F65BCCB6FDD1C0DF3B3624A5212C9946D8419C98A6E8F32D0BEA5616B60E92C4567571E23B32EAF7438458814654F7DE37F885E59D15F434D19C386D975F907B890F9F546D1CE2D3DA2F400C437557... |
#!/usr/bin/env python3
"""Play a MIDI file.
This uses the "mido" module for handling MIDI: https://mido.readthedocs.io/
Pass the MIDI file name as first command line argument.
If a MIDI port name is passed as second argument, a connection is made.
"""
import sys
import threading
import jack
from mido import MidiFi... |
import sys
import os
import logging
import sentry_sdk
from sentry_sdk.integrations.logging import LoggingIntegration
__author__ = "Noah Hummel"
loggers = dict()
_sentry_dsn = os.environ.get("SENTRY_DSN")
if _sentry_dsn:
sentry_logging = LoggingIntegration(
level=logging.DEBUG,
event_level=logg... |
"""Tests for CMS app API functionality"""
import pytest
from django.contrib.contenttypes.models import ContentType
from wagtail.core.models import Page
from cms.api import ensure_home_page_and_site
from cms.models import HomePage
@pytest.mark.django_db
def test_ensure_home_page_and_site():
"""
ensure_home_pa... |
# 1.a
class ejr1a:
def __init__(self):
while True:
tabla = input("Escriba los elementos de su tabla separados por espacios: ")
tabla = tabla.split()
try:
for i in range(len(tabla)):
tabla[i] = int(tabla[i])
print("Los or... |
# coding: utf-8
from src.unit import PAWN
PASSANT_RIGHT = "pr"
PASSANT_LEFT = "pl"
def calculatePawnMoves(unit, player, game):
position = game.getPositionOfUnit(unit)
x = position[0]
y = position[1]
if player == game.white:
calculateWhitePawnMoves(unit, game, x, y)
elif player == game.bla... |
from dearpygui.dearpygui import *
from tkinter import Tk, filedialog
import requests
import socket
import json
ButtonEditor_id = generate_uuid()
category_combo = generate_uuid()
system_combo = generate_uuid()
obs_combo = generate_uuid()
system_selectapp_button = generate_uuid()
system_websiteurl_input = generate_uu... |
"""
Recreate Figures 7 and 8 from the paper
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
from pathlib import Path
from bad_seeds.plot.gen_figs import plot_all_ideal, plot_all_timelimit
def main():
figsize = (8.5 / 2.54, (8.5 / 2.54) / 1.6)
batch_sizes = (1, 8, 16, 32, 64, 128, 256, 512)
ti... |
# -*- coding: utf-8 -*-
"""
Defines a synthetic seismogram.
:copyright: 2016 Agile Geoscience
:license: Apache 2.0
"""
import numpy as np
import matplotlib.pyplot as plt
from .curve import Curve
class Synthetic(np.ndarray):
"""
Synthetic seismograms.
"""
def __new__(cls, data, basis=None, params=No... |
"""
Tests for day 1 of 2020's Advent of Code
"""
import pytest
from aoc_cqkh42.year_2020 import day_01
@pytest.fixture
def data() -> str:
"""
Test data for day_01.
Returns
-------
data: str
"""
return '1721\n979\n366\n299\n675\n1456'
def test__find_subset_with_sum(data) -> None:
n... |
from __future__ import absolute_import, division, print_function, unicode_literals
from . import BaseSignal
class Signal(BaseSignal):
""" Ranking signal based on the domain presence in DMOZ
"""
def get_value(self, document, url_metadata):
return float(bool(url_metadata["domain"].dmoz_title))
|
import random
import csv
indian_first_names = [
'Vaishnavi',
'Sunthari',
'Shruti',
'Sangem',
'Ramalingam',
'Amarnath',
'Vallath',
'Suranjan',
'Shukla',
'Sanjna... |
# Generated by Django 3.2.7 on 2021-09-21 18:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('catalog', '0002_alter_book_options'),
]
operations = [
migrations.AlterModelOptions(
name='book',
options={'ordering': ['tit... |
from chocs import HttpStatus
def test_http_status_str() -> None:
status = HttpStatus.OK
assert "200 OK" == str(status)
assert 200 == int(status)
def test_http_status_from_int() -> None:
status = HttpStatus.from_int(200)
assert "200 OK" == str(status)
assert 200 == int(status)
|
# Generated by Django 3.0.6 on 2020-05-29 15:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('Profile', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='R... |
def busca_binaria(lista, chave):
primeiro = 0
ultimo = len(lista)-1
while primeiro <= ultimo:
meio = int((primeiro+ultimo)/2)
if lista[meio] == chave:
return meio
if lista[meio] > chave:
ultimo = meio - 1
else:
primeiro = meio +1
return None
def exibe_lista(lista):
print(li... |
import math
from typing import List, Tuple
class Rectangle:
"""
A class used to represent a Rectangle, using only five sine qua non parameters.
Attributes
----------
x_center : float
center of the rectangle on x axis
y_center : float
center of the rectangle on y axis
radi... |
import argparse
import os
import time
import matplotlib.pyplot as plt
import torch
from torch.optim import SGD
from torchvision import utils
from utils import create_dataloader, YOLOv2Loss, parse_cfg, build_model
# from torchviz import make_dot
parser = argparse.ArgumentParser(description='YOLOv2-pytorch')
parser.a... |
import string
import pytest
from hypothesis import assume, given
from hypothesis import strategies as st
from pybitcoin.mnemonic_code_words import MNEMONIC_CODE_WORDS
from pybitcoin.tests.wallet.fixtures import BIP_32_TEST_VECTORS
from pybitcoin.wallet import KeyStore, hmac_sha512, validate_mnemonic
@st.composite
d... |
import os
import shutil
import unittest
import mdl
class TestDownloader(unittest.TestCase):
def test_aria2(self):
self.assertIs(
mdl.downloader.downloaders['aria2'],
mdl.downloader.aria2.aria2c
)
class TestBiliVideo(unittest.TestCase):
def assertion(self, vid, vide... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-12-20 13:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photologue', '0010_auto_20160105_1307'),
]
operations = [
migrations.Alter... |
## This file is the celeryconfig for the Periodic Task Handler on scanmaster.
import sys
sys.path.append('.')
import djcelery
djcelery.setup_loader()
from scaggr.settings import *
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
CELERY_IMPORTS = ('virusscan.tasks',)
from virusscan.tasks import get_per... |
"""Functional tests using the API with a fake Apple TV."""
import pyatv
import ipaddress
import asynctest
from pyatv.conf import AppleTV
from tests import zeroconf_stub
HOMESHARING_SERVICE_1 = zeroconf_stub.homesharing_service(
'AAAA', b'Apple TV 1', '10.0.0.1', b'aaaa')
HOMESHARING_SERVICE_2 = zeroconf_stub.ho... |
import os
import json
import requests
from base64 import b64encode, b64decode
from collections import OrderedDict
from Crypto.PublicKey import RSA
from Crypto.Util import number
from datetime import datetime
from jwt import JWT, jwk_from_dict
from OpenSSL import crypto
from suds.client import Client
from xml.dom impor... |
from typing import Any, Literal, Sequence, Union, TypedDict
class BeginEvent(TypedDict):
event: Literal["begin"]
xid: int
class ChangeEvent(TypedDict):
event: Literal["change"]
xid: int
timestamp: str
schema: str
table: str
class InsertEvent(ChangeEvent):
kind: Literal["insert"]
... |
from pywps import Service
from pywps.tests import assert_response_success
from .common import client_for
from c3s_magic_wps.processes import processes
def test_wps_caps():
client = client_for(Service(processes=processes))
resp = client.get(service='wps', request='getcapabilities', version='1.0.0')
names ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function
import requests
import sys
import json
import os
import codecs
import logging
import logging.handlers
# Some constants
BASEURL = None
# Format the logger output
class CustomFormatter(logging.Formatter):
... |
import keccak_hash
from binascii import unhexlify, hexlify
import unittest
import sys
# smartcash block #1
# rc125@ubuntu:~/.smartcash$ smartcashd getblockhash 1
# 00000009c4e61bee0e8d6236f847bb1dd23f4c61ca5240b74852184c9bf98c30
# rc125@ubuntu:~/.smartcash$ smartcashd getblock 00000009c4e61bee0e8d6236f847bb1dd23f4c61... |
"""
LINK: https://leetcode.com/problems/pascals-triangle-ii/
Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle.
Notice that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Follow up:
Could you optimize your algorithm to use on... |
#!/usr/bin/env python
import roslib; roslib.load_manifest('rosprolog')
import rospy
from rosprolog_client import PrologException, Prolog
if __name__ == '__main__':
rospy.init_node('example_query_prolog_kb')
prolog = Prolog()
query = prolog.query("perishable(X), location(X,Y,_)")
for solution in query... |
# We are given a three data sets represented as arrays: A, B and C. Find algorithm that determines
# if there is a triplet a,b and c respectively from A, B and C that a + b = c.
# 1st solution:
def partition(T, l, r):
pivot = T[r]
i = l - 1
for j in range(l, r):
if T[j] <= pivot:
i +... |
import argparse
from pathlib import Path
INDENT = ' ' * 4
ELEMENTS_PER_LINE = 8
def main():
parser = argparse.ArgumentParser(
description="""
bla bla bla
""".strip(),)
parser.add_argument('filenames', type=str, help='filename help', nargs='+')
args = parser.parse_args()
... |
#Tom Mirrigton
#Exercise 6 submission
#define the function factorial
#set y to 1 or for loop will just multiply through 0
def fact(x):
y = 1
#for loop using a range of all values up to and including x
#iterating though the for loop will multiply i value by cumaltive y value
for i in range (1, x + 1):
... |
"""Class to perform under-sampling based on nearmiss methods."""
# Authors: Guillaume Lemaitre <[email protected]>
# Christos Aridas
# License: MIT
import warnings
from collections import Counter
import numpy as np
from sklearn.utils import safe_indexing
from ..base import BaseUnderSampler
from ...ut... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import html
import re
from typing import Any, Callable, Dict, List, Optional, Tuple
from urllib.parse import quote, unquote, urlencode
from mwparserfromhell.wikicode import Wikicode
from mwcomposerfromhell.magic_words import MAGIC_WORDS, MagicWord
# A parser function is a callable which takes two parameters (param ... |
"""
File name: version.py
Author: rameshpr
Date: 11/5/18
"""
__version__ = '1.1'
|
#Maze is the class that creates a matrix like field
from Maze import Maze
from Player import *
from SaveLoad import *
from ConsoleColors import set_color
from Help import *
from INFO import BUILDING
from INFO import RESEARCH
from random import randint
from time import strftime
from GetFileDir import get_file_... |
"""Stores group membership information as secrets, for faster lookups."""
import asyncio
import json
import urllib
import os
from typing import List, Optional
import aiohttp
import cpg_utils.cloud
from flask import Flask
ANALYSIS_RUNNER_PROJECT_ID = 'analysis-runner'
app = Flask(__name__)
async def _groups_lookup(... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: [email protected]
*
"""
n=int(input())
a=[*map(int,input().split())]
x=sum(a[i]==i for i in range(n))
x+=(x<n)
x+=any(i!=a[i] and i==a[a[i]] for i in range(n))
print(x) |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
import traceback
import sys
from multiprocessing import Value, Lock
from synapseclient.utils import printTransferProgress
def notifyMe(syn, messageSubje... |
"""Frequency Finder
Analyzes frequency of letters in given message compared to the most common occurring
letters to determine if message is in the English language.
Attributes:
ETAOIN (str): String containing uppercase latin letters in order from most to least common.
LETTERS (str): String containing uppercas... |
import os
import time
# noinspection PyPackageRequirements
import ffmpeg
from radikoplaylist import MasterPlaylistClient, LiveMasterPlaylistRequest, TimeFreeMasterPlaylistRequest
ENVIRONMENT_VALIABLE_KEY_AREA_ID = "RADIKO_AREA_ID"
AREA_ID_DEFAULT = "JP13"
def record(station, recording_time, outfilename):
maste... |
from dataclasses import dataclass, field
from typing import List
from enum import Enum
@dataclass
class Task:
"""
TODO: add supported_file_types
"""
name: str
supported: bool = field(default=False)
supported_metrics: List[str] = field(default_factory=list)
@dataclass
class TaskCategory:
... |
import numpy as np
def convolucion(A,B):
C1 = 0
for k in range(len(A)-1):
for j in range (len(A)-1):
N = A[k][j]*B[k][j]
C1 += N
C2 = 0
for k in range(len(A)-1):
for j in range (len(A)-1):
S = A[k][j+1]*B[k][j]
C2 += S
C3 = 0
for k... |
"""
The aws module is intended to provide an interface to aws
It tightly interfaces with boto. Indeed, many functions require a boto connection object parameter
While it exposes boto objects (espcially instances) to callees, it provides the following ease of use ability:
* Unpacking reservations into reservations
*... |
import re
from setuptools import setup
with open('wumpus/__init__.py') as f:
contents = f.read()
try:
version = re.search(
r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', contents, re.M
).group(1)
except AttributeError:
raise RuntimeError('Could not identify version') from ... |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if ... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2015
# Gmail:liuzheng712
#
from ansible import playbook, callbacks
import tornado.web
import tornado.ioloop
import tornado.websocket
import os, sys
import subprocess
import time
import StringIO
import json
import tornado.escape
class Index(tornado.web.RequestHan... |
from ..greengraph import Greengraph
from ..map import Map
|
from typing import Dict, List, Optional, Tuple
import symro.src.mat as mat
from symro.src.prob.problem import Problem, BaseProblem
import symro.src.handlers.metaentitybuilder as eb
DEFAULT_MP_SYMBOL = "Master"
DEFAULT_PRIMAL_SP_SYMBOL = "Primal"
DEFAULT_FBL_SP_SYMBOL = "Feasibility"
CUT_COUNT_PARAM_SYMBOL = "CUT_CO... |
from pyrfuniverse.envs import NailCardEnv
import numpy as np
from stable_baselines3.common.env_checker import check_env
import gym
env = NailCardEnv(
rotation_factor=0,
goal_baseline=0.02,
)
# Check environment
# check_env(env)
# exit()
env.reset()
for i in range(10):
action = np.array([0, -1, 0, 1])
... |
"""
Copyright 2020 The OneFlow 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 law or agr... |
"""
Spotify OAuth integration
"""
from base64 import b64encode
from datetime import datetime
from typing import Dict
from typing import Optional
from typing import Tuple
from urllib.parse import urlencode
from fastapi import Depends
from httpx import HTTPError
from httpx import Response
from app.extensions import htt... |
# Copyright 2019, Google LLC.
#
# 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 in writing... |
# Copyright 2020 Sebastian Ahmed
# This file, and derivatives thereof are licensed under the Apache License, Version 2.0 (the "License");
# Use of this file means you agree to the terms and conditions of the license and are in full compliance with the License.
# You may obtain a copy of the License at
#
# http://www.ap... |
import numpy as np
import tensorflow as tf
import cv2
class Waifu2x:
__MODEL_PATH__ = "./GUI//src/saved_model/Waifu2x"
def __init__(self, sess):
if sess is None:
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.2
self.sess = tf.Sess... |
"""Dummy test."""
def test_dummy():
"""Dummy."""
assert 1 + 1 == 2
|
# Initialize an instance of the following class. Use a variable to store the object and then call the info function to print out the attributes.
class Dog(object):
def __init__(self, name, height, weight, breed):
self.name = name
self.height = height
self.weight = weight
self.breed =... |
#!/usr/bin/env python
# found on <http://files.majorsilence.com/rubbish/pygtk-book/pygtk-notebook-html/pygtk-notebook-latest.html#SECTION00430000000000000000>
# simple example of a tray icon application using PyGTK
import gtk
def message(data=None):
"Function to display messages to the user."
msg=gtk.Message... |
import os
import configparser
def get_param(section, name):
"""
Возращает значение параметра "name" из секции "section"
Args:
section: имя секции
name: имя параметра
Returns:
значение параметра.
"""
path = os.path.expanduser("~/.mpython_conf")
if not os.path.exist... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.