content stringlengths 5 1.05M |
|---|
# 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... |
from fastapi import APIRouter,WebSocket,Request,HTTPException
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
ftemps = Jinja2Templates(directory="app/templates")
fileres=APIRouter()
@fileres.get("/addone",response_class=HTMLResponse)
async def add_one(request:Request):
... |
from dataclasses import fields
from rest_framework import serializers
from core import models
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = models.Tag
fields = ("name", "id")
read_only_fields = ("id",)
class ActorSerializer(serializers.ModelSerializer):
cl... |
from JumpScale import j
descr = """
Check on average cpu for last 15 min
"""
organization = "jumpscale"
maxperiod = 17*60 # always in sec
enable = True
roles = []
def check(watchdogevent):
pass
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
from . import *
class wElement(wComponent):
"""
Class which models an element. Every object what can be added to a page, is an element.
"""
def __init__(self):
wComponent.__init__(self)
|
""" Python 3.6+
Data import from Excel file and addition to CTVdb
Carmen Sheppard 2020-2022
"""
import argparse
import os
import sys
import pandas as pd
from Database_tools.db_functions import searchexact, session_maker
from Database_tools.sqlalchemydeclarative import Serotype, SerotypeVariants, Group, V... |
import torch
def get_torch_device():
if torch.cuda.is_available():
device_name = torch.cuda.get_device_name()
n_gpu = torch.cuda.device_count()
print(f"Found device: {device_name}, n_gpu: {n_gpu}")
device = torch.device("cuda")
else:
device = torch.device('cpu')
ret... |
# Copyright 2017 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 required by applica... |
"""empty message
Revision ID: 4f6c3b920cba
Revises: 7632c2a5255f
Create Date: 2016-02-01 01:30:18.381681
"""
# revision identifiers, used by Alembic.
revision = '4f6c3b920cba'
down_revision = '7632c2a5255f'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
# -*- coding:utf-8 -*-
from lxml import etree
import urllib
import os
import requests
urllib2=urllib.request
def getHtml(url):
html = requests.get(url).content
selector = etree.HTML(html)
return selector
def getContent(htm, xpathStr):
selector = htm
content = selector.xpath(xpathStr)
return ... |
'''
No 2. Buatlah fungsi tanpa pengembalian nilai, yaitu fungsi segitigabintang.
Misal, jika dipanggil dg segitigabintang(4), keluarannya :
*
**
***
****
'''
def segitigabintang(baris):
for i in range(baris):
print('*' * (i+1))
|
import argparse
import numpy as np
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib'))
import common
import inputparser
def write_snvs(variants, sampnames, garbage, snv_fn, normal_vaf=0.0):
sampnames = ['Normal'] + sampnames
snv_indices = {}
with open(snv_fn, 'w') a... |
import os
import teek
try:
# examples/soup.py does bs4.BeautifulSoup(html_string, 'lxml')
import bs4 # noqa
import lxml # noqa
soup_py_can_run = True
except ImportError:
soup_py_can_run = False
EXAMPLES_DIR = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
... |
font = "Josefin Sans Light"
TITLE_FONT = (font, 35)
HEADING_FONT = (font, 30)
SIDEBAR_STAT_FONT = (font, 30)
SIDEBAR_LABEL_FONT = (font, 20)
LOADING_FONT = (font, 17)
SEARCHBAR_FONT = (font, 18)
COUNTRIES_FONT = (font, 16)
COUNTRY_NOT_FOUND_FONT = (font, 20)
#LARGE_FONT = (font, 20)
#SUBTITLE_FONT = (font, 18)
#NORMAL... |
'''It is a modified version of the official implementation of
"Scale-steerable filters for the locally-scale invariant convolutional neural network"
Paper: https://arxiv.org/pdf/1906.03861.pdf
Code: https://github.com/rghosh92/SS-CNN
MIT License
Copyright (c) 2020 Ivan Sosnovik, Michał Szmaja
'''
import torch
import t... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-06-02 21:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('entrance', '0047_auto_20170515_1434'),
('enrolled_s... |
a = 1
b = 1
c = a
a = 2
b = b + 3
c = 'строка'
print(a, b, c)
|
import os
input_path = os.path.join(os.path.dirname(__file__), "input.txt")
with open(input_path) as f:
data = f.read()
lines = data.splitlines()
def solve(binary_nums: list[str]) -> int:
pos = 0
o2_gen_lst = binary_nums
while len(o2_gen_lst) > 1:
bit_count = sum(int(b_num[pos]) for b_num i... |
## ---------------------------------------------------------------------------
## DM-Sim: Density-Matrix Quantum Circuit Simulation Environement
## ---------------------------------------------------------------------------
## Ang Li, Senior Computer Scientist
## Pacific Northwest National Laboratory(PNNL), U.S.
## Ho... |
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from src.domain.user import User
from .base import RepoBase
class UserRepo(RepoBase[User]):
model = User
_session: AsyncSession
async def get_by_username(self, /, username: str) -> User | None:
return (
awa... |
######################################################################
# Author: Concepta Njolima TODO: Change this to your name
# Username: njolimac TODO: Change this to your username
#
# Assignment: A01
#
# Purpose: A program that returns your Chinese Zodiac animal given a
# birth year between 1988 and ... |
import os
import json
import requests
import logging
import ssl
from pymongo import MongoClient
logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s/%(module)s @ %(threadName)s: %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.... |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals, division, print_function
import unittest
from pymatgen.io.abinit.launcher import ScriptEditor
class ScriptEditorTest(unittest.TestCase):
def test_base(self):
... |
#!/usr/bin/env python3
#
# Copyright (c) 2020 - 2021 Cheng Zhao <zhaocheng03@gmail.com>
#
# 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... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .original_encoder import OriginalEncoder
from .paraphrase_encoder import ParaEncoder
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Encoder(nn.Module):
def __init__(self, params):
super(Encoder, self).__... |
# -*- coding: utf-8 -*-
"""
--------------------------------------
@File : model_constant.py
@Author : maixiaochai
@Email : maixiaochai@outlook.com
@Created on : 2020/5/10 15:47
--------------------------------------
"""
# 权限值
USER_COMMON = 0
USER_BLACK = 1
USER_VIP = 2
ADMIN_NONE = 0
ADMIN_COMMON = 2
... |
import web
from web import form
import socket
print("http://" + socket.gethostbyname(socket.gethostname()) + ":8080")
urls = (
'/index', 'Index',
'/','Login',
'/page_one','Page_one'
)
loginform = form.Form(
form.Textbox("USERNAME",
form.notnull,
form.Validator('... |
from tkinter import *
import random
import time
class Coords:
def init(self, x1=0, y1=0, x2=0, y2=0):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def within_x(co1, co2):
if co1.x1 > co2.x1 and co1.x1 < co2.x1:
return True
elif co1.x2 > co2.x1 and co1.x2 < co... |
from unittest import TestCase
from typing import List
from mapperr import to_dict, to_obj
class A:
a1: str
a2: int
class B:
b1: str
b2: int
b3: A
class C:
c1: str
c2: int
c3: List[B]
c4: List[int]
c5: dict
c6: list
c7: float
def test(self):
print("hi")
c... |
import sys, tty, termios
import RPi.GPIO as GPIO
from motor import Motor
import picamera
import tflearn
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.normalization import local_response_normalization
from tflearn.lay... |
"""
All test are from the webs
https://realpython.com/primer-on-python-decorators/#decorators-with-arguments
"""
import functools
import math
from typing import Callable, Any
def dec(*args: Any, **kwargs: Any):
def inner():
print("hello")
# return f
return inner
@dec
def hello_test(a):
... |
from typing import Any, Union
from boa3.builtin import CreateNewEvent, NeoMetadata, metadata, public
from boa3.builtin.interop.contract import update_contract
from boa3.builtin.interop.runtime import check_witness
from boa3.builtin.interop.storage import get, put
from boa3.builtin.type import UInt160
# --------------... |
from logging import debug, info, warning, error
from datetime import datetime, timezone
import requests
import re
from .. import AbstractPollHandler
from data.models import Poll
class PollHandler(AbstractPollHandler):
OPTION_V2_PLUS = 'Like'
OPTION_V2_MINUS = 'Dislike'
OPTIONS_V3 = ['Excellent', 'Great', 'Good', '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Trainer script for src.pl_modules.supervised_learning. Example run command: bin/train.py save_to_folder configs/cnn.gin.
"""
import gin
import logging
import os
import json
from src.data import get_dataset
from src.callbacks import get_callback
from src.utils import ... |
from .array_sum_to_one import array_sum_to_one
from .exists import exists
from .list_to_list_two_tuples import list_to_list_two_tuples
from .to_percent import to_percent
|
import hashlib
import numpy as np
import torch
from dataclasses import dataclass
from typing import List
import logging
from jiant.tasks.core import (
BaseExample,
BaseTokenizedExample,
BaseDataRow,
BatchMixin,
Task,
TaskTypes,
)
from jiant.tasks.lib.templates.shared import (
construct_sing... |
from django.views.generic import View
from highcharts.views.common import HighChartsDualAxisView
class HighChartsBarView(HighChartsDualAxisView, View):
chart_type = 'bar'
class HighChartsStackedView(HighChartsBarView):
@property
def plot_options(self):
plot_options = super(HighChartsBarView, s... |
#!/usr/bin/env python3
# coding=utf-8
'''
#-------------------------------------------------------------------------------
Project : Instagram Bot
Module : bot
Purpose : Follow users, like posts, upload photo, unfollow
Version : 0.1.2 beta
Status : Development
Modified : 2020 Jun 28
Created : 2019 Nov 03
#-... |
#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
"""Tools for automatic generation of some nt2 header files
"""
__author__ = "Lapreste Jean-thierry (lapreste@univ-bpclermont.fr)"
__version__ = "$Revision: 1.0 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyleft (c) 2010 Jean-thierry L... |
amount = int(input("Enter Amount:"))
if amount < 1000:
discount = amount * 0.05
print("Discount", discount)
elif amount<5000:
discount = amount * 0.10
print("Discount", discount)
else:
discount = amount*0.15
print("Discount", discount)
print("Net payable:", amount - discount) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 11 12:35:35 2020
@author: miyazakishinichi
設計
連続するビデオデータを入力とする
numpyバイナリへの変換, モデルによる予測, 結果の出力
ジャンプの時間帯の抽出とビデオ化
可能であれば, 判断に迷った挙句に0にしたデータ群も
出力するデータは, 周囲も含めて出力することで, その時間帯の印象を見分けられるようにする
→ハードネガティブマイニング??
"""
import pandas as pd
from tkinter import m... |
# File: elasticsearch_consts.py
#
# Copyright (c) 2016-2022 Splunk Inc.
#
# 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 ... |
from flask import Flask, render_template, request, redirect, session
from colour import Color
app = Flask(__name__)
app.secret_key = 'darksecret'
@app.route("/")
def checker_8_by_8():
return render_template("checker.html", num_rows=8, num_cols=8, colors=["salmon", "black"])
@app.route("/<x>")
def checker_x_by_8... |
#!/usr/bin/env python3
"""
Conway's game of life, bounded grid, numpy 2-dimensional array rbh 2020
"""
import numpy as np
from time import sleep
import sys
from paint import paint
PTS = '.*#'
DEAD, ALIVE, WALL = 0, 1, 2
DCH, ACH, GCH = PTS[DEAD], PTS[ALIVE], PTS[WALL]
def point(r, c, cols):
return c + r*cols
... |
import numpy as np
from kNN import kNN
from CIFAR import CIFARLoader
from CIFAR import CIFARPlotter
%matplotlib inline
########################################################################
# 2017 - Manny Grewal
# This class is the entry point for the KNN classifier.
################################################... |
# Copyright (c) 2022 PaddlePaddle 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 app... |
import ringogw
def ringo_reader(fd, sze, fname):
import struct, zlib
MAGIC_HEAD = (0x47da66b5,)
MAGIC_TAIL = (0xacc50f5d,)
def read_really(s):
t = 0
buf = ""
while t < s:
r = fd.read(s - t)
... |
"""
Application File
"""
import flask
import flask.logging
from flask import Flask, Response, request
import glob
import hmac
import logging
import os
import re
import subprocess
from subprocess import PIPE
import sys
from webapp import default_config
from webapp import webhook_status_messages
from webapp.common i... |
from tests.test_helper import *
from braintree.configuration import Configuration
class TestTransactionGateway(unittest.TestCase):
def setUp(self):
config = Configuration(
environment=Environment.Development,
merchant_id="integration_merchant_id",
public_key="integratio... |
import re
import tempfile
import unittest
from dataclasses import asdict
from pathlib import Path
from datasets.utils.metadata import (
DatasetMetadata,
metadata_dict_from_readme,
tagset_validator,
validate_metadata_type,
yaml_block_from_readme,
)
def _dedent(string: str) -> str:
indent_level... |
import numpy as np
from pandas import Series, Timedelta, DataFrame
def acf(x, lags=None, bin_method='gaussian', bin_width=None, max_gap=np.inf,
min_obs=10, output="acf"):
"""Calculate the autocorrelation function for irregular timesteps.
Parameters
----------
x: pandas.Series
Pandas S... |
try:
from kolibri.utils.pskolibri.common import LINUX # noqa: F401
from kolibri.utils.pskolibri.common import WINDOWS # noqa: F401
SUPPORTED_OS = True
except NotImplementedError:
# This module can't work on this OS
SUPPORTED_OS = False
|
# Copyright 2015 Mirantis, Inc.
#
# 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 ... |
# Authors: Edouard Oyallon, Joakim Anden, Mathieu Andreux
import torch
import torch.nn.functional as F
from collections import namedtuple
BACKEND_NAME = 'torch'
from ...backend.torch_backend import _is_complex, Modulus, concatenate, type_checks, cdgmm, real
from ...backend.base_backend import FFT
def subsample_fou... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class RouteHistory(Document):
pass
def flush_old_route_records():
"""Deletes all rout... |
import os
import subprocess
import platform
import time
import database as DB
import input_commands as IC
import pygame_camera_module as CM
class Main(object):
def __init__(self):
#Setup input events
IC.InputCommands(self.shutdown)
#Connect to firebase
self.dirname, self.filename =... |
# import pytest
from mygamefile import Game
import resources
def test_init():
game = Game()
assert game.board == resources.EMPTY_BOARD
assert game.next_board == resources.EMPTY_BOARD
def test_print_empty_board():
game = Game()
assert game.board_to_string() == resources.EMPTY_BOARD_STRING
def t... |
from __future__ import absolute_import, print_function
import os
import sys
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
# For demo purposes, we build our own tiny library.
try:
print("building libmymath.a")
assert os.system("gcc -shared -fPIC... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
from typing import (
Any, Dict, Optional,
)
from amundsen_rds.models import RDSModel
def serialize_record(record: Optional[RDSModel]) -> Dict[str, Any]:
if record is None:
return {}
record_dict = {key: value... |
"""Miscellaneous utilities."""
import functools
import sys
class Named:
"""A named object.
This class can be used to construct objects with a name that will be used
for the string representation.
"""
def __init__(self, name):
"""Construct a named object.
Arguments:
... |
from django.conf.urls import url, patterns, include
urlpatterns = patterns(
'',
url(r'^', include('site_search.urls', 'search')),
)
|
from tkinter import Frame, Label, Entry, Button, LabelFrame
from tkinter import N, W, LEFT, CENTER
from gui.selected_device_frame import SelectedDeviceFrame
from gui.creator import write_device_config, load_device_config
import adb
import re
import traceback
RUNNING = 'running'
DISCONNECTED = 'disconnected'
CONNECTED ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class KoubeiMarketingDataSmartactivityConfigResponse(AlipayResponse):
def __init__(self):
super(KoubeiMarketingDataSmartactivityConfigResponse, self).__init__()
self._activ... |
import time
import random
s1 = open("scores.txt","a")
name = open("name.txt","w")
score = 0
p1 = random.randint(1,4)
p2 = random.randint(1,4)
p3 = random.randint(1,4)
p4=random.randint(1,5)
p5=random.randint(1,4)
p11 = random.randint(1,5)*p3
rs = random.randint(9,12)
sc22 = random.randint(45,55)
while True:
yk = in... |
from django.test import TestCase
from portfolios.models import ProfessionalExperience
from portfolios.factories.professional_experience_factory import create_professional_experiences_with_factory
class ProfessionalExperienceTestCase(TestCase):
__MODEL = ProfessionalExperience
@classmethod
def setUpTestDa... |
from typing import Tuple
from utils import (multiply,
pythagorean_triplets)
numbers_sum = 1_000
def special_condition(numbers: Tuple[int, ...]) -> bool:
return sum(numbers) == numbers_sum
special_pythagorean_triplet, = filter(special_condition,
pythagor... |
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from copy import deepcopy
from functools import partial
import numpy as np
import scipy
from addict import Dict
from ....algorithms.quantization import utils as eu
from ....engines.ac_engine import ACEngine
from ....graph.model_utils i... |
"""989. Add to Array-Form of Integer
https://leetcode.com/problems/add-to-array-form-of-integer/
For a non-negative integer X, the array-form of X is an array of its digits
in left to right order. For example, if X = 1231, then the array form is [1,2,3,1].
Given the array-form A of a non-negative integer X, return t... |
#!/bin/python3
# https://www.hackerrank.com/challenges/minimum-swaps-2
import sys
if __name__ == "__main__":
n = int(input())
a = [int(s) for s in input().strip().split(' ')]
dict = {v: i for i, v in enumerate(sorted(a))}
swaps = 0
i = 0
while i < n:
j = dict[a[i]]
if j != i... |
"""This is the top level module for my raspberry pi syncing program.
It's definitely more complicated than it needs to be. In short, all it does is
provide a way to run rsync jobs using config files. These would then ideally be
scheduled via cron.
I didn't just pure bash because I want it to be easily modular and con... |
# -*- coding: utf-8; -*-
__all__ = ['Bunch']
from collections.abc import Mapping, MutableMapping, Container, Iterable, Sized
class Bunch:
"""A bunch of named values.
Can be used instead of a `dict` when `b.someattr` is more readable than
`d['somekey']`. In terms of `collections.abc`, a `MutableMapping`,... |
"""
util.py
Implements util functions
"""
__version__ = '1.0'
__author__ = 'Hugo Chauvary'
__email__ = 'chauvary.hugo@gmail.com'
import sys
import os
import functools
from random import choice
from inspect import getframeinfo, stack
import numpy as np
from module.logger import Logger
def log_item(func):
"""... |
import sys
import base64
from .exceptions import WinRMTransportError, UnauthorizedError
HAVE_KERBEROS = False
try:
import kerberos
HAVE_KERBEROS = True
except ImportError:
pass
is_py2 = sys.version[0] == '2'
if is_py2:
from urllib2 import Request, URLError, HTTPError, HTTPBasicAuthHandler, HTTPPassw... |
# Ask a user to enter a number
num1 = input('Enter a number: ')
# Ask a user to enter a second number
num2 = input('Enter a second number: ')
# Calculate the total of the two numbers added together
answer = float(num1) + float(num2)
# Print 'first number + second number = answer'
# For example if someone enters 4 and ... |
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.lost, name="lost"),
url(r'^found/', views.found, name="found"),
url(r'^lost/', views.lost, name="lost"),
url(r'^postItem/', views.postItem, name="postItem")
] |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
import pygame, random
import shared, circle
class Pow():
def __init__(self, images:dict, center:tuple):
''' dictionary of 2 images passed, gun and shield '''
self._key = random.choice(['shield', 'gun']) # choose one image: 'gun' or 'shield' #
self.image = images[self._key] # assign to self.imag... |
# -*- coding: utf-8 -*-
# Author: David Goodger
# Contact: goodger@users.sourceforge.net
# Revision: $Revision: 4229 $
# Date: $Date: 2005-12-23 00:46:16 +0100 (Fri, 23 Dec 2005) $
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, pleas... |
from uuid import uuid4
import requests
from flask import Blueprint, abort, jsonify, request, url_for
from flask_security.core import current_user
from flask_security.decorators import login_required
from urlobject import URLObject as URL
from ..models import RunToken, db
from ..utils.redis import get_redis_client
_... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... |
from geolite2 import geolite2
import requests
class bColors:
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BLUE = '\033[94m'
def banner():
print(bColors.GREEN + '<<< IP-TRACKER v1.0>>>')
print(bColors.RED + r'''
_
| |
| |___
| _ \ _ _
| |_) | | (_) |
... |
#
# Copyright (c) 2011 Thomas Rampelberg
#
"""
Make doing janky cross domain communication easy.
"""
__author__ = 'Thomas Rampelberg'
__author_email__ = 'thomas@saunter.org'
from setuptools import setup, find_packages
setup(
name = "janky_post",
version = "0.5",
author = __author__,
author_email = _... |
"""
Main module for Flambda APP
Version: 1.0.0
"""
import os
def load_projectrc(projectrc_filepath):
"""
Load the values of .projectrc file
"""
from dotenv import dotenv_values
return dotenv_values(projectrc_filepath)
if __package__:
current_path = os.path.abspath(os.path.dirname(__file__)).... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-05-20 02:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0003_auto_20200518_1637'),
]
operations = [
migrations.AlterField... |
# https://stepik.org/lesson/3369/step/11?unit=952
# Sample Input:
# 5
# Sample Output:
# 1 2 3 4 5
# 16 17 18 19 6
# 15 24 25 20 7
# 14 23 22 21 8
# 13 12 11 10 9
def position(a):
x = 0
y = 0
minX, maxX = 1, a - 1
minY, maxY = 0, a - 1
xyz = 1
for count in range(1, a**2 + 1, 1):
yie... |
"""The ue_smart_radio component."""
|
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
from sys import platform
extra_compile_args = []
extra_link_args = []
try:
from Cython.Distutils.build_ext import build_ext
except ImportError:
print('Error: Cython not installed. please ... |
'''
Problem 7
@author: Kevin Ji
'''
primes_list = [ 2, 3 ] # Cache list, will grow as get_nth_prime gets called
def get_nth_prime( term ):
# Map term number to list index number (1 -> 0)
term -= 1
# If the index is less than the length of the list, then return the cached value
if term < len( pr... |
import syft as sy
import torch
def test_plan_module_tracing():
@sy.func2plan(args_shape=[(1,)])
def plan_test(x, torch=torch):
y = torch.rand([1])
return x + y
p = plan_test(torch.tensor([3]))
assert len(plan_test.role.actions) == 2
|
class ICharacterComponent():
def equip(self):
pass
class CharacterConcreteComponent(ICharacterComponent):
def __init__(self,name):
self.name=name
self.equipamento=[]
def equip(self):
if len(self.equipamento)==0:
return f'{self.name} equipment: Empty'
e... |
#!/usr/bin/env python3
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import fire
import json
import os
import numpy as np
import tensorflow as tf
tf.get_logger().setLevel('ERROR')
import model, sample, encoder
def interact_model(
model_name='poetry-pgclean-117m',
seed=None,
length=50,
temperat... |
from semseg.loader.cityscapes_loader import cityscapesLoader
def get_loader(name):
"""get_loader
:param name:
"""
return {
"cityscapes": cityscapesLoader,
}[name] |
from kpm.commands.deploy import DeployCmd
class RemoveCmd(DeployCmd):
name = 'remove'
help_message = "remove a package from kubernetes"
def _call(self):
self.status = self.kub().delete(dest=self.tmpdir, force=self.force, dry=self.dry_run,
proxy=self.api_pro... |
#!/usr/bin/env python
# coding: utf-8
# # Tone generator
#
# Required: `pip install tones`
# https://pypi.org/project/tones/
# In[53]:
from tones.mixer import Mixer
notes = ['c','d','e','f','g','a','b']
octave = 3
for note in notes:
mixer = Mixer(44100,0.5)
mixer.create_track(0)
mixer.add_note(0,note... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 24 11:01:50 2017
@author: slauniai
******************************************************************************
CanopyGrid:
Gridded canopy and snow hydrology model for SpaFHy -integration
Based on simple schemes for computing water flows and storages within vegetation... |
load("//internal/starlark:util.bzl", "run_starlark_executor")
def _terraform_locals_impl(ctx):
output = ctx.actions.declare_file(ctx.label.name + "_locals.tf.json")
run_starlark_executor(
ctx,
output,
ctx.file.src,
ctx.files.deps,
ctx.executable._starlark_executor,
... |
# -*- coding: utf8 -*-
from QcloudApi.qcloudapi import QcloudApi
from tce.tcloud.utils.config import global_config
# 设置需要加载的模块
module = 'lb'
# 对应接口的接口名,请参考wiki文档上对应接口的接口名
action = 'CreateLoadBalancerListeners'
region = global_config.get('regions')
params = global_config.get(region)
secretId = params['secretId']
secre... |
import great_expectations as ge
import pytest
context = ge.get_data_context('SparkCSV', './tests/test_sets')
titanic_dataset = context.get_dataset('Titanic.csv', header=True)
strf_dataset = context.get_dataset('strf_test.csv', header=True)
def test_expect_column_values_to_be_unique():
result = titanic_dataset.ex... |
def test_request_items_runner_fixture(testdir):
"""Make sure that pytest accepts our fixture."""
# create a temporary pytest test module
testdir.makepyfile(
"""
def test_exists(request_items_runner):
assert request_items_runner
"""
)
# run pytest with the following ... |
# coding=utf-8
"""Survey model definition.
"""
from django.db import models
from django.utils import timezone
from bims.models import LocationSite
class Survey(models.Model):
"""Survey model."""
date = models.DateField(
default=timezone.now
)
sites = models.ManyToManyField(LocationSite)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.