content stringlengths 5 1.05M |
|---|
import math
from torch.optim.lr_scheduler import _LRScheduler
from bisect import bisect_right
class WarmupCosineLR(_LRScheduler):
def __init__(self, optimizer, milestones, min_ratio=0., cycle_decay=1., warmup_iters=1000, warmup_factor=1./10, last_epoch=-1):
if not list(milestones) == sorted(milestones):
... |
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import unittest
import os
from datetime import datetime, timedelta
from asn1crypto import core, util
from .unittest_data import data_decorator, data
from ._unittest_compat import patch
patch()
tests_root = os.path.di... |
# -*- coding: utf-8 -*-
import numpy as np
def generateNumberArray(N_spins, max_n_spins_in_basket):
num_baskets = (N_spins/max_n_spins_in_basket+1,
N_spins/max_n_spins_in_basket)\
[N_spins-(N_spins/max_n_spins_in_basket)*\
max_n_spins_in_basket==0]
num... |
from django.db import models
# Create your models here.
class Student(models.Model):
name = models.CharField(max_length=10)
age = models.IntegerField()
sex = models.CharField(max_length=10)
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_leng... |
# coding: utf-8
"""Training tools subpackage."""
__all__ = [
'Manager',
'Updater',
'ScatterPlot',
'set_log_scale',
]
from hdnnpy.training.extensions import (ScatterPlot,
set_log_scale,
)
from hdnnpy.training.manager i... |
from collections import Counter
class P8XMatrixTransformation:
def solve(self, original, target):
def c(m):
c = Counter()
for r in m:
c += Counter(r)
return c
return ("NO", "YES")[c(original) == c(target)]
|
"""
Please contact the author(s) of this library if you have any questions.
Authors: Kai-Chieh Hsu ( kaichieh@princeton.edu )
Vicenc Rubies Royo ( vrubies@berkeley.edu )
"""
from gym.envs.registration import register
register(
id="multi_player_lunar_lander_reachability-v0", entry_point=(
"gym_rea... |
"""Helper functions for logging purposes."""
__all__ = ["log_function_code"]
from typing import Callable
import inspect
def log_function_code(func_to_log: Callable) -> str:
"""
Extracts function code into str.
It is used for preparing functions code to be logged into external files.
:param func_t... |
import requests
import json
from library import *
def showAll(self):
res = requests.get(
'https://us-central1-kcc-library.cloudfunctions.net/showAll')
result = res.json()
showData(self, result)
def showAvailables(self):
res = requests.get(
'https://us-central1-kcc-library.cloudfuncti... |
from socket import *
from time import *
from shumeipai.bme280 import get_temp_pressure_humidity_from_sensor
from shumeipai.power_control import blink
from shumeipai.soil_sensor import get_result_from_sensor
from shumeipai.settings import sensor_channel, ADDR, BUFSIZ
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSoc... |
from sentence_transformers import SentenceTransformer
import scipy.spatial
import numpy as np
import PrepareData
embedder = SentenceTransformer('output/training_stsbenchmark_roberta-base-2020-06-20_15-58-09')
corpus = PrepareData.load_data()
# Corpus with example sentences
corpus_embeddings = []
for document in corp... |
"""
Database stuff.
_
(Yes, I cut/pasted this from the flask docu. ¯\_(ツ)_/¯ )
"""
import sqlite3
from flask import g, session
from flask import flash
import sys
import os
from app import app
DATABASE = 'roborank'
def full_db_path(dbname=None):
if dbname is None:
... |
from CvPythonExtensions import *
import CvUtil
import CvScreenEnums
gc = CyGlobalContext()
class CvPediaConcepts:
def __init__(self, main):
self.top = main
self.X_TEXT = self.top.X_PEDIA_PAGE
self.Y_TEXT = self.top.Y_PEDIA_PAGE
self.H_TEXT = self.top.H_PEDIA_PAGE
self.W_TEXT = self.top.W_PEDIA_PAGE
... |
import json
import os
from datetime import datetime
import click
import pytz
from click import ClickException
from cmr import render
from connect.cli.core.http import get_user_agent
from connect.cli.plugins.report.constants import AVAILABLE_RENDERERS, AVAILABLE_REPORTS
from connect.cli.plugins.report.utils import (
... |
# vFabric Administration Server API
# Copyright (c) 2012 VMware, Inc. 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... |
from . import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from . import login_manager
from datetime import datetime
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(UserMixin,db.Model):
__table... |
from matplotlib.pyplot import figure
from matplotlib.ticker import ScalarFormatter
import xarray
sfmt = ScalarFormatter(useMathText=True) # for 10^3 instead of 1e3
sfmt.set_powerlimits((-2, 2))
sfmt.set_scientific(True)
sfmt.set_useOffset(False)
def plotigrf(mag: xarray.Dataset, model: str):
mode = "contour"
... |
#!/usr/bin/python
import web
import MySQLdb
import sqlite3
import urllib2
render = web.template.render('templates/')
urls = (
'/', 'index',
'/login', 'login',
'/auth', 'auth',
'/register', 'register',
'/about', 'about',
'/user/(.*)', 'user',
'/masthead', 'masthead',
'/faq', 'faq',
'/... |
# Copyright 2019 Intel, Inc.
# 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 a... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import base64
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from helper.authenticatedencryption import Authe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the artifacts attribute containers."""
import unittest
from plaso.containers import artifacts
from plaso.lib import definitions
from tests import test_lib as shared_test_lib
class EnvironmentVariableArtifactTest(shared_test_lib.BaseTestCase):
"""Tests f... |
from .group import Group
from .widgets import Button, Slider
class Component:
made = 0
def __init__(self, tag=None):
if tag is None:
tag = type(self).__name__ + str(type(self).made)
self.tag = tag
type(self).made += 1
def show(self, *args, **kwargs):
pass
... |
#!/usr/bin/env pytest
# -*- coding: UTF-8 -*-
import json
import logging
import os
import sys
import unittest
from unittest import mock
testdir = os.path.realpath(os.path.dirname(os.path.realpath(__file__)) + "/../../../")
sys.path.append(testdir)
import webserver.main
from webserver.plugins.meta.baike import Baidu... |
# Forbidden Words
class MedicalPaper:
def __init__(self, text):
self.text = text
self.color = 'red'
self.text_color = 'golden'
def treat(self, patient):
patient.see(self.text)
patient.believe(self.text)
treatment = MedicalPaper('calm')
if patient.illness == 'bipolar d... |
'''
Code: DeAuthenticating a WiFi Access Point and a WiFi Client
Author: Qaidjohar Jawadwala
Usage: python wifi_dos.py channel ap_mac client_mac count interface
Example: python wifi_dos.py 7 E8:94:F6:D5:83:5E 98:0C:A5:5B:61:0B 10 wlan0mon
Note: Only for educational purposes.
'''
from scapy.all import * #Importing Kal... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 2 23:46:39 2019
@author: Ghayasuddin Adam
"""
import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
#insert Twitter Keys
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET =... |
import pytups as pt
from .solution import Solution
from cornflow_client import ExperimentCore
from .instance import Instance
class Experiment(ExperimentCore):
def __init__(self, instance: Instance, solution: Solution):
super().__init__(instance, solution)
if self.solution is None:
self... |
import time
from threading import Thread, Event
import random
items = []
event = Event()
"""
Summary
event.wait() -> used by consumer to wait an event occurs to continue its processing
event.set() -> set the Event, notifying the consumer
event.clear() -> Event is set to false by clear() method"
"""
class... |
# -*- coding: utf-8 -*-
# Copyright 2020 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 o... |
import os
from kgx import PandasTransformer
cwd = os.path.abspath(os.path.dirname(__file__))
resource_dir = os.path.join(cwd, 'resources')
target_dir = os.path.join(cwd, 'target')
def test_load():
"""
Test for loading data into PandasTransformer
"""
t = PandasTransformer()
os.makedirs(target_dir,... |
# Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
from django.test import TestCase
from django.core.exceptions import ObjectDoesNotExist
from contacts.models import Office365Connection
import contacts.o365service
# Create your tests here.
api_e... |
from orchespy import device, transfer_array
from orchespy.devicetype import Host, VE
import numpy
import nlcpy
@device(Host)
def sum_host(x, y):
return x + y
@device(VE)
def sum_dev(x, y):
return x + y
@device(Host, numpy_module_arg='xp')
def create_host(size, xp):
return xp.random.rand(*size)
@dev... |
# plot an histogram of binomial distributed numbers
import numpy
import matplotlib.pyplot as plt
randNumbers = numpy.random.binomial(1000, .75, 5000)
plt.hist(randNumbers,100)
plt.title("Histogram of randomly choosen binomial numbers")
plt.xlabel("range")
plt.show() |
from torch import nn
from Model.Block import ResidualBlock, list_to_sequential
from Model.Block import UpsamlingBlock
import numpy as np
class Generator(nn.Module):
def __init__(self, in_channels=3, num_residual_blocks=16):
super(Generator, self).__init__() ... |
from InstruccionesPL.TablaSimbolosPL.InstruccionPL import InstruccionPL
class CallFun(InstruccionPL):
def __init__(self, id , op,tipo, strGram, linea, columna):
InstruccionPL.__init__(self, tipo, linea, columna, strGram)
self.id = id
self.op = op
def ejecutar(self, tabl... |
import os
import platform
import pytest
import torch
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import Callback
from pytorch_lightning.plugins import DDPShardedPlugin, DDPSpawnShardedPlugin
from pytorch_lightning.utilities import _APEX_AVAILABLE, _FAIRSCALE_AVAILABLE, _NATIVE_AMP_AVAILABLE... |
allSyms = {}
fn = None
for line in file('funcdb', 'r').read().strip().split('\n'):
if not line:
continue
if line[0] != '\t':
fn = line
continue
sym, encoding = line[1:].split(' = ', 1)
if not encoding.startswith('~f{'):
continue
encoding = encoding[3:-1]
if sym not in allSyms or len(allSyms[sym][0]) > le... |
from scoring_engine.engine.basic_check import CHECKS_BIN_PATH
from tests.scoring_engine.checks.check_test import CheckTest
class TestElasticsearchCheck(CheckTest):
check_name = 'ElasticsearchCheck'
properties = {
'index': 'events',
'doc_type': 'message'
}
cmd = CHECKS_BIN_PATH + "/ela... |
import asyncio
import re
from telethon import Button, custom, events
from telethon.tl.functions.users import GetFullUserRequest
from userbot import bot
from userbot.plugins.sql_helper.blacklist_assistant import (
add_nibba_in_db,
is_he_added,
removenibba,
)
from userbot.plugins.sql_helper.botusers import ... |
# Copyright 2021 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff
# This software is distributed under the 3-clause BSD License.
"""
An example of using amalgamator and solving directly the EF
To execute this:
python farmer_ama.py --num-scens=10 --crops-multiplier=3 --farmer-with-integer
... |
# 使用Tensorflow的CNN网络识别MNIST手写数字
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
from tensorflow.examples.tutorials.mnist import input_data
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
# Hyper Parameters
BATCH_SIZE = 128
LR_BASE = 0.0002
LR_DECAY = 0.99
TRAIN_STEP = 6000
mnist = inp... |
# Nameko relies on eventlet
# You should monkey patch the standard library as early as possible to avoid
# importing anything before the patch is applied.
# See http://eventlet.net/doc/patching.html#monkeypatching-the-standard-library
import eventlet
eventlet.monkey_patch()
import logging
logger = logging.getLogger(__... |
import model
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("command", nargs="?", default="all")
parser.add_argument("text", nargs="*")
args = parser.parse_args()
if args.command == "predict":
text = " ".join(args.text)
score = model.predict(text)
desc = "positive" if score > 0.5 ... |
import helper
from helper import Command
def start(args, logfile, errfile):
helper.set_database_host(args)
command = Command("rvm jruby-1.7.8 do bundle exec trinidad --config config/trinidad.yml", False)
return helper.run([command], logfile, errfile, args.troot)
def stop(logfile, errfile):
return helper.stop(... |
"""
Copyright (c) 2021 Zakru
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, modify, merge, publish, distribute, sublicen... |
# Copyright 2020 Varun Verma
#
from flask import Flask, render_template, request, jsonify
from src.app_functions import predict_match_result
from src.app_functions import update_team_assignment
from src.app_functions import current_match_prediction
from src.app_functions import update_match_details, update_final_over... |
"""
Created on 31 Jan 2021
Example to show myself that PCA when you don't drop any
dimensions gives you back the same data with the transform,
and show the amount of variance lost with different num
of principal components
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import ... |
# Author: Andreas Putz
# Copyright (c) 2013, PyhtonFCST
# License: TBD.
r"""
:mod:`PythonFCST`: Python helpers for OpenFCST
===============================================================================
Documentation is available in the docstrings and in ths sphinx documentation.
Contents
--------
The PythonFCST pac... |
print ('Hola Mundo, soy del TERCERO C')
|
"""Configure LBANN experiment with Transformer model."""
import math
import os.path
import lbann
import lbann.models
import lbann.contrib.launcher
from lbann.util import str_list
import dataset
# ----------------------------------------------
# Options
# ----------------------------------------------
# Dataset prop... |
from argparse import ArgumentParser # use traditional argparse instead hiargparse
from hiargparse import ArgsProvider, Arg, ChildProvider # need to define child arguments
from hiargparse import Namespace # wrapper for argparse.Namespace
# just same as example.py
from example import Son
if __name__ == '__main__':
... |
from __future__ import annotations
import collections
import inspect
import pathlib
from typing import Any
from typing import Callable
from typing import Dict
from typing import List
from typing import Tuple
from typing import TypeVar
from typing import cast
from multipledispatch.dispatcher import Dispatcher
from mul... |
'''
@author: frank
'''
from virtualrouter import virtualrouter
from zstacklib.utils import http
from zstacklib.utils import jsonobject
from zstacklib.utils import linux
from zstacklib.utils import log
from zstacklib.utils import lock
logger = log.get_logger(__name__)
class VipTO(object):
def __init__(self):
... |
import pytest
import numpy as np
from solarforecastarbiter.metrics import summary
@pytest.mark.parametrize("ts", [
[1, 2, 3],
np.random.rand(10),
np.random.rand(1000),
])
def test_scalar(ts):
for metric in summary._MAP:
f = summary._MAP[metric][0]
assert np.isscalar(f(ts))
|
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_... |
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
import torch.nn.functional as F
import functools
from PIL import Image
import os
import os.path
import numpy as np
from numpy import linalg as LA
import csv
import pandas as pd
import pickle
def make_dataset(dir):
val_csv_fi... |
from markovdp.q_state import QState
class QStateDT(QState):
"""Class to represent a q-state in a Decision Tree MDP model."""
def remove_state(self, state_num):
"""Removes the transition and reward information for that Q-state.
Args:
state_num (int): The unique state number in the... |
'''
A Multilayer Perceptron implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
# Import MINST data
import input_data
mnist = input_... |
from thumt.optimizers.optimizers import exclude_variables
from thumt.optimizers.optimizers import AdamOptimizer
from thumt.optimizers.optimizers import AdadeltaOptimizer
from thumt.optimizers.optimizers import SGDOptimizer
from thumt.optimizers.optimizers import MultiStepOptimizer
from thumt.optimizers.optimizers impor... |
import datetime
import pandas as pd
import numpy as np
from dask import dataframe as dd
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
#load in the dask dataframe
df = dd.read_parquet("/Users/amyferrick/Downloads/5_min_gps_subset/unr_5min_gps... |
from sqlalchemy import *
from databases import Database
import aiomysql
import sqlalchemy
from sqlalchemy.engine import reflection
import pytest
import functools
import asyncio
from devtools import debug
from unimeta.table import Table
from loguru import logger
import configparser
from unimeta.libs.liburl import parse_... |
# Copyright 2010-2011 OpenStack Foundation
# Copyright 2012-2013 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
#
# http://www.apache.org/li... |
from synchp.settings import Settings
def test_parse_config_file():
Settings.init("synch.yaml")
def test_settings():
assert isinstance(Settings.debug(), bool)
assert isinstance(Settings.insert_num(), int)
assert isinstance(Settings.insert_interval(), int)
|
from mpi4py import MPI
import json
import re
from collections import Counter as c
from collections import Counter, defaultdict
from collections import OrderedDict
import time
import sys
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
grids = {}
gridCounter = {}
hashtagCounter = {}
start_time = tim... |
#!/bin/env python3
from mempatch import *
import struct
flashes = [
("bin/internal.bin", 0x00200000),
("bin/external.bin", 0x90000000, 0x800000)
]
files = [
("bin/pkey.bin", 0x00208ac8),
("bin/kernel0.bin", 0x90000008),
("bin/kernel1.bin", 0x90400008),
("bin/exam0.bin", 0x903F0000),
("bin... |
import os
import unittest
from unittest.mock import Mock, patch
from cache_gs.cache_classes.cache_data_file import CacheData, CacheDataFile
from tests.test_tools import raise_test_exception
def force_exception(*args, **kwargs):
raise_test_exception()
class TestCacheDataFile(unittest.TestCase):
def setUp(s... |
"""
Django settings for socialdistribution project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
f... |
from __future__ import absolute_import, division, print_function
del absolute_import, division, print_function
from .._core.axis import options
from .._core import axis as ca
from .kwargs import KWArgs
from .sig_tools import inject_signature
from .axis_transform import AxisTransform
from .utils import cast, registe... |
#!/usr/bin/env python
# coding: utf-8
# # Angular Velocity
# There are two ways to think about <i>angular velocity</i>.
#
# ## Case 1
# Body 1 is orbiting body 2, just like Earth travels on a curved path about the sun's rotational axis.
# 
# <i>Caption</i>. On the left, ... |
from .response import BotResponse
class NothingResponse(BotResponse):
def run(self):
pass
|
# Copyright 2015 The Switch Authors. All rights reserved.
# Licensed under the Apache License, Version 2, which is in the LICENSE file.
"""
Defines model components to describe unit commitment of projects for the
SWITCH-Pyomo model. This module is mutually exclusive with the
project.no_commit module which specifies s... |
# Generated by Django 2.2.1 on 2019-11-12 16:47
import core.storage.utils
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0007_auto_20190827_1138'),
]
operations = [
migrations.AddField(
model_name='user',
... |
#!/usr/bin/env python
"""
_GetOutputMap_
MySQL implementation of Jobs.GetOutputMap
"""
from WMCore.Database.DBFormatter import DBFormatter
class GetOutputMap(DBFormatter):
sql = """SELECT wmbs_workflow_output.output_identifier AS wf_output_id,
wmbs_workflow_output.output_fileset AS wf_output_... |
# scored.py
# Repeatedly read test scores (from 0 to 100), until the user
# enter -1 to finish. The input part of the program will ensure
# that the numbers are in the correct range.
# For each score, report the corresponding grade:
# 90-100 = A, 80-89 = B, 70-79 = C, 60-69 = D, < 60 = F
# When you have all the scores,... |
## -*- coding: utf-8 -*-
import sys
import cv2
import numpy as np
import time
from math import sqrt
ball_color = 'yellow'
color_dist = {'red': {'Lower': np.array([0, 60, 60]), 'Upper': np.array([6, 255, 255])},
'blue': {'Lower': np.array([100, 80, 46]), 'Upper': np.array([124, 255, 255])},
... |
dist=float(input('qual a distancia da viagem em km? '))
if dist<=200:
preco=0.50*dist
else:
preco=0.45*dist
print('a passagem será de R${:.2f}.'.format(preco))
|
from decimal import Decimal, ROUND_HALF_UP
from django.test import TestCase
from .utils import create_test_expenses
from ..models import Expense
from ..reports import summary_overall
class ReportsTestCase(TestCase):
"""Test reports utilities for the expenses"""
def setUp(self) -> None:
"""Set up fo... |
from django.apps import AppConfig
class FuturecostsConfig(AppConfig):
name = 'futurecosts'
|
# ---------------------------------------------------------------------
# inv.inv log plugin
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# NOC modules
... |
from fastparquet import ParquetFile
import seaborn as sns
import matplotlib.pyplot as plt
import os
import pandas as pd
import numpy as np
from src.data.make_dataset import DataLoader
def load_all():
df = ParquetFile(os.path.join(project_dir, 'data', 'interim', 'data.parq')).to_pandas().set_index('date')
data... |
from django.db import connection
from django.http import JsonResponse
from django.shortcuts import render
import requests
import json
from administer.models import Services, Nodes
from django.contrib import messages
from administer import context_processors
from configuration.models import Restart_after_configuration
... |
# vFabric Administration Server API
# Copyright (c) 2012 VMware, Inc. 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
... |
from django.contrib.auth import get_user_model
from django.test import TestCase, Client
from django.urls import reverse
from bills.models import BillSet, Bill
from houses.models import House
from utils.models import BillFile
class BillsViewsTests(TestCase):
def setUp(self):
self.client = Client()
User = get_use... |
#!/usr/bin/env python2
import sys
from os.path import dirname, realpath
sys.path.append(realpath(dirname(__file__)))
import gimpfu as gfu
from gimpfu import main
from _plugin_base import GimpPluginBase
class FaceGen(GimpPluginBase):
def run(self, img_layer, mask_layer, mask_m_layer):
self.model_file = 'M... |
#!/usr/bin/env python3
import math
print("Tartály festése" + "\n")
magassag = float(input("Milyen magas? "))
sugar = float(input("Mennyi az átmérője? ")) / 2
felulet = 2 * math.pi * sugar * (sugar + magassag)
dobozok_szama = felulet / 2
print(dobozok_szama, "doboz festék kell.")
|
class Newssources:
'''
newssources class to define news sources objects
'''
def __init__(self,id,name,description,url,category,language,country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.la... |
import unittest
from src.graph import Graph
from src.breadth_first_search import bfs
class BreadthFirstSearchTest(unittest.TestCase):
def test_bfs_parses_the_graph_in_order(self):
"""
Correctly explore the following graph:
_(a)--(c)--(e)
/ | / \ |
... |
from pathlib import Path
import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from starlette.middleware.cors import CORSMiddleware
from app.core import config
from app.core.routes import core_router
def get_application() -> FastAPI:
application = FastAPI(title=config.PROJECT_NA... |
"""Tests for register_mongodb.py"""
from flask import Flask
from flask_pymongo import PyMongo
from foca.database.register_mongodb import (
create_mongo_client,
register_mongodb,
)
from foca.models.config import MongoConfig
MONGO_DICT_MIN = {
'host': 'mongodb',
'port': 27017,
}
DB_DICT_NO_COLL = {
... |
# FindStringusingRecursive.py
# Create a function that you return True if the exat word is find in the string or sentence
# string = "I love bananas and apples."
# is the word ana in the string/sentence? return True
# is the word live in the string/sentence ? return False
# if the string/sentence or the word is empt... |
class Solution:
def calPoints(self, ops: 'List[str]') -> int:
s = []
for op in ops:
if op == 'C':
s.pop()
elif op == 'D':
s.append(s[-1] * 2)
elif op == '+':
s.append(s[-1] + s[-2])
else:
... |
"""
pytest.fixture() 允许fixture有参数化功能
@pytest.mark.parametrize 允许在测试函数或类中定义多组参数和fixtures
pytest_generate_tests 允许定义自定义参数化方案或扩展(拓展)
"""
import pytest
@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
def test_eval(test_input, expected):
print(f"测试数据{test_input},期望结果{expected}... |
"""
Probability based traffic generator
"""
import os
import threading
import sched
import time
import sys
import random
import subprocess
DESTINATION = str(sys.argv[1])
PACKET_SIZE = int(sys.argv[2])
PROBABILITY = float(sys.argv[3])
RATE_IF_TRANS = int(sys.argv[4])
scheduler = sched.scheduler(time.time, time.sleep)
... |
#!/usr/bin/env python
from oauth_client.config import settings
from redis import StrictRedis, ConnectionError
import json
import logging
from datetime import datetime
from filelock import Timeout, FileLock
class OAuthTokenStore:
"""
Generic method to save and retrieve values from file and redis backed token s... |
import logging
import os
import sys
from collections import defaultdict
# Configure Logger
Log = None
Cache = defaultdict(lambda: list())
CacheOrder = list()
def log(msg, level='debug'):
if Log is None:
return
if level == 'info':
Log.info(msg)
elif level == 'moreinfo':
Log.log(15,... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 3 14:49:43 2020
@author: zzc14
"""
import torch
from Mnn_Core.mnn_utils import *
from torch import Tensor
from torch.nn.parameter import Parameter
import torch.nn.functional as F
from torch.nn import init
from Mnn_Core.fast_dawson import *
torch.set_default_tensor_typ... |
# Import packages that are needed
import pandas as pd # tested with version 0.22.0
import matplotlib as mpl
import matplotlib.pyplot as plt # tested with version 2.1.2
import seaborn as sns # tested with version 0.8.1
import matplotlib.gridspec
from .summary_stats import get_merged
mpl.use("Agg")
ALPHA = 0.1 # n... |
from pwn import *
context.arch = 'amd64'
p = process("./filters_isprint")
shellcode = b""
print(shellcode)
p.send(shellcode)
p.interactive() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from qtplotlib.barplot import QBarPlot
from PyQt5.QtWidgets import QApplication
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = QBarPlot()
#widget.data = (10, 20, 30, 5, 15)
widget.data = (8, None, 7, 5, -5, 6)
widget.d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import subprocess
import re
class Task(object):
tasknum = 0
processor = 0
utilization = 0
def make_task(tasknum, utilization):
task = Task()
task.tasknum = tasknum
task.utilization = utilization
task.processor = 0
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.