text stringlengths 2 999k |
|---|
import json
import traceback
from copy import deepcopy
from alarm.config import HUPUN_SYNC_ABNORMAL_ROBOT
from alarm.helper import Helper
from alarm.page.ding_talk import DingTalk
from cookie.config import ROBOT_TOKEN
from hupun.config import HUPUN_SEARCH_DAYS
from hupun.model.es.purchase_order_close_msg import PurOrde... |
#!/usr/bin/python3
import xml.etree.ElementTree as et
from optparse import OptionParser
client_nodes = [
'node9', 'node10', 'node11', 'node12',
'node13', 'node14', 'node15', 'node16',
];
parser = OptionParser()
parser.add_option("-n", "--clients_per_server", dest="clients_per_server",
... |
from past.types import basestring
class PropFind:
def __init__(self, matches):
self.matches = matches
self.search = None
def clear(self):
search = list()
for match in self.matches:
d = dict()
d["values"] = match
d["found"] = False
... |
# DADSA - Assignment 1
# Reece Benson
class Menu():
# Define the variables we will be using
menu = None
def __init__(self):
#TODO: Define our Menu
self.menu = {
'Item 1': {
'Sub Item 1': self.load_action,
'Sub Item 2': self.load_action
... |
# -*- encoding: utf-8 -*-
#
# Copyright © 2013 IBM Corp
#
# Author: Tong Li <litong01@us.ibm.com>
#
# 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... |
# Copyright 2010 Jacob Kaplan-Moss
# Copyright 2011 Nebula, Inc.
"""
Exception definitions.
"""
class CommandError(Exception):
pass
class ValidationError(Exception):
pass
class AuthorizationFailure(Exception):
pass
class NoTokenLookupException(Exception):
"""This form of authentication does not ... |
# -*- coding: utf-8 -*-
"""
Base class for the forward model operator
"""
import numpy as np
import copy
from shutil import rmtree
import os
import subprocess
import tensorflow as tf
import time
class FclassError(Exception):
pass
class Subprocess_op:
"""Class to create a Tensorflow operator from a pr... |
try:
with open('VERSION') as f:
version = f.read().strip()
except Exception:
version = '0.0.1'
__version__ = version
|
# -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
""" System tests that obtain the set of available packages for the current platform
It then installs each of those plugin packages via REST API endpoints
"""
import os
import subprocess
import http.client
import json
impor... |
"""class URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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='home')
Class-base... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack LLC.
# 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/... |
""" Abstract Object Detection, Each model implementation has to follow this
apis
"""
import abc
from typing import Tuple, Dict
import numpy as np
from PIL import Image
class AbstractObjectDetection(
metaclass=abc.ABCMeta
): # pylint: disable=missing-class-docstring
@abc.abstractmethod
def get_objects... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__a... |
i=0
k=0
def setup():
size(500, 500)
smooth()
strokeWeight(1)
background(0)
def draw():
global i,k
stroke(i, 20)
line(mouseX , mouseY , random(0,500), 500)
i +=k
if(i == 255):
k=-1
if(i == 0):
k=1
def keyPressed():
if (key=="s"):
... |
import os
import matplotlib.pyplot as plt
import torch
import src.envs.core as ising_env
from experiments.utils import test_network, load_graph_set
from src.envs.utils import (SingleGraphGenerator,
RewardSignal, ExtraAction,
OptimisationTarget, SpinBasis,
... |
from os import system
system('Hello') |
"""empty message
Revision ID: c763cdb7a96c
Revises: 03a541062ae3
Create Date: 2017-11-28 03:13:37.858152
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c763cdb7a96c'
down_revision = '03a541062ae3'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from pirates.piratesgui.RadarGui import *
from pirates.quest.QuestIndicatorNode import QuestIndicatorNode
from direct.showbase.PythonUtil import report, StackTrace
class QuestIndicatorNodeArea(QuestIndicatorNode):
def __init__(self, questStep):
self.pendingStepObj = None
QuestIndicatorNode.__init_... |
#!/usr/bin/python2
"""
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"); yo... |
from copy import deepcopy
import numpy as np
from rlcard.games.blackjack import Dealer
from rlcard.games.blackjack import Player
from rlcard.games.blackjack import Judger
class BlackjackGame(object):
def __init__(self, allow_step_back=False):
''' Initialize the class Blackjack Game
'''
se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0, '../')
import asyncio
import configparser
import discord
from mafia.game import Game
from mafia.game import Player
from mafiaclients.discord.messenger import Messenger
client = discord.Client()
games = {}
players = {}
class DiscordPlayer(... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Weapon()
result.template = "object/weapon/melee/sword/crafted_saber/shared_sword_lightsaber_one_handed_s11_gen3.if... |
"""2017-11-28 18:08:00"""
|
#Alex Holcombe alex.holcombe@sydney.edu.au
#See the README.md for more information: https://github.com/alexholcombe/attentional-blink/blob/master/README.md
#git remote add origin https://github.com/alexholcombe/attentional-blink.git
from __future__ import print_function
import time, sys, os#, pylab
if os.name != 'mac':... |
#!/usr/bin/env python3
import sys
# Functions
def read_numbers():
try:
n = int(sys.stdin.readline())
k = int(sys.stdin.readline())
v = [int(sys.stdin.readline()) for _ in range(n)]
except ValueError:
return 0, 0, None
return n, k, v
def compute_unfairness(n, k, v):
v... |
from sparseml.keras.optim import ScheduledModifierManager
from tensorflow.keras.utils import to_categorical
from autogoal.contrib.keras import KerasClassifier
from autogoal.grammar import CategoricalValue
def build_sparseml_keras_classifier(path_to_recipe: str):
"""Build custom KerasClassifier algorithm applaying... |
from collections import defaultdict
PAD = u'PAD'
UNK = u'UNKNOWN'
MARK = u'MARK'
NMARK = u'NMARK'
NA = u'NA'
GA = u'Ga'
O = u'O'
NI = u'Ni'
PRD = u'V'
GA_INDEX = 0
O_INDEX = 1
NI_INDEX = 2
class Vocab(object):
def __init__(self):
self.i2w = []
self.w2i = {}
def add_word(self, word):
... |
# coding: utf-8
"""
Payoneer Mobile API
Swagger specification for https://mobileapi.payoneer.com
OpenAPI spec version: 0.9.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import payoneer_mobile... |
# -*- coding: utf-8 -*-
#
# csgo documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 15 03:43:47 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... |
#!/usr/bin/env python3
# Copyright (c) 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Create a blockchain cache.
Creating a cache of the blockchain speeds up test execution when running
mu... |
# link: https://leetcode.com/problems/partition-labels/
class Solution(object):
def partitionLabels(self, S):
"""
:type S: str
:rtype: List[int]
"""
start = 0
length = 0
dic = {c:i for i,c in enumerate(S)}
result = []
for i in range(len(S)):
... |
# SPDX-License-Identifier: Apache-2.0
# To register a converter for scikit-learn operators,
# import associated modules here.
from . import ada_boost
from . import array_feature_extractor
from . import bagging
from . import binariser
from . import calibrated_classifier_cv
from . import cast_op
from . import concat_op... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Implementation of the Apriori algorithm.
"""
# We use semantic versioning
# See https://semver.org/
__version__ = "1.1.1"
import sys
from efficient_apriori.apriori import apriori
from efficient_apriori.itemsets import itemsets_from_transactions
from efficient_apriori... |
#
# @lc app=leetcode id=4 lang=python3
#
# [4] Median of Two Sorted Arrays
#
# @lc code=start
from typing import List
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
pass
# @lc code=end
|
# Automatically generated from poetry/pyproject.toml
# flake8: noqa
# -*- coding: utf-8 -*-
from setuptools import setup
packages = \
['c7n',
'c7n.actions',
'c7n.filters',
'c7n.reports',
'c7n.resources',
'c7n.ufuncs']
package_data = \
{'': ['*']}
install_requires = \
['argcomplete>=1.11.1,<2.0.0',
'boto3>=1.12... |
#
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# 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, pu... |
water_names = [
'H2O',
'HHO',
'OHH',
'HOH',
'OH2',
'SOL',
'WAT',
'TIP',
'TIP2',
'TIP3',
'TIP4'
]
|
# AudioCollection - manage audio collections and databases
# Bregman - python toolkit for music information retrieval
__version__ = '1.0'
__author__ = 'Michael A. Casey'
__copyright__ = "Copyright (C) 2010 Michael Casey, Dartmouth College, All Rights Reserved"
__license__ = "gpl 2.0 or higher"
__email__ = 'mcasey@dar... |
# Copyright 2020 Tier IV, 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 applicable law or... |
#!/usr/bin/env python3
# Copyright (c) 2016-2017 Bitcoin Core Developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# This script will locally construct a merge commit for a pull request on a
# github repository, inspect it, ... |
#!/usr/bin/env python
'''
So I heard you want to use OAuth2? This is a helper tool that gets the
authenticaton code for you and fires it into praw.ini.
How to use:
- Visit: https://www.reddit.com/prefs/apps
- Create new "script", under "redirect uri" put http://127.0.0.1:65010
- Open praw.ini
- oau... |
import argparse
import itertools
import json
from pathlib import Path
from typing import Any, Dict, List, TextIO
from allennlp.data.vocabulary import DEFAULT_PADDING_TOKEN
from allennlp.predictors import Predictor, CorefPredictor
import spacy
from spacy.matcher import Matcher
from spacy.tokens import Doc, Token
from t... |
from mock import PropertyMock, mock
from requests import RequestException
from requests.sessions import Session
from coinbase_commerce.api_resources import Charge, Checkout, Event
from coinbase_commerce.client import Client
from coinbase_commerce.error import (
APIError,
AuthenticationError,
InternalServer... |
# -*- coding: utf-8 -*-
""" Comparison of the accuracy and computational speed of different load
aggregation algorithms.
The g-function of a single borehole is calculated for boundary condition of
uniform borehole wall temperature along the borehole. Then, the borehole
wall temperature variations resul... |
"""
https://leetcode.com/problems/lru-cache/
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or in... |
# -*- encoding: utf-8 -*-
"""
HubbleStack Nova plugin for using grep to verify settings in files.
Supports both blacklisting and whitelisting patterns. Blacklisted patterns must
not be found in the specified file. Whitelisted patterns must be found in the
specified file.
This audit module requires yaml data to execut... |
# coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from pants.backend.docgen.targets.doc import Page
from pants.backend.jvm.... |
# -*- coding: UTF-8 -*-
"""
This module provides the abstract base classes and core concepts
for the model elements in behave.
"""
import os.path
import sys
import six
from behave.capture import Captured
from behave.textutil import text as _text
from enum import Enum
if six.PY2:
# -- USE: Python3 backport for bet... |
"""Atakama sdk."""
from os import path
from setuptools import setup
def long_description():
"""Extract description from readme."""
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md")) as readme_f:
contents = readme_f.read()
return content... |
primes = []
n = 10
arr = [1]*(n+1)
arr[0] = 0
arr[1] = 0
for i in range(2, n+1, 1):
if arr[i]:
primes.append(i);
for j in range(2*i, n+1, i):
arr[j] = 0
# Regression
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
... |
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
import xgboost as xgb
import lightgbm as lgb
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns
color = sns.color_palette()
import matplotlib as mpl
from sklearn i... |
# pylint: disable=no-self-use,invalid-name
import torch
from pytorch_pretrained_bert.modeling import BertConfig, BertModel
from allennlp.common.testing import ModelTestCase
from allennlp.data.dataset import Batch
from allennlp.data.fields import TextField, ListField
from allennlp.data.instance import Instance
from al... |
"""
Set of wrapper functions for gym environments taken from
https://github.com/Shmuma/ptan/blob/master/ptan/common/wrappers.py
"""
import collections
import numpy as np
import torch
from pl_bolts.utils import _GYM_AVAILABLE, _OPENCV_AVAILABLE
from pl_bolts.utils.warnings import warn_missing_pkg
if _GYM_AVAILABLE:
... |
from dnsimple2.resources import BaseResource
class UserResource(BaseResource):
fields = ('id', 'email', 'created_at', 'updated_at',)
def __init__(self, **kwargs):
self.id = kwargs.get('id')
self.email = kwargs.get('email')
self.created_at = self.parse_datetime(kwargs.get('created_at')... |
#!/usr/bin/env python3
# Software License Agreement (BSD License)
#
# Copyright (c) 2021, UFACTORY, Inc.
# All rights reserved.
#
# Author: Vinman <vinman.wen@ufactory.cc> <vinman.cub@gmail.com>
from launch import LaunchDescription
from launch.actions import OpaqueFunction, IncludeLaunchDescription, DeclareLaunchArgum... |
# -*- coding: utf-8 -*-
from collections import defaultdict
try:
import numpy as np
except ImportError:
np = None
import pytest
from ..util.testing import requires
from ..units import (
amount,
allclose,
concatenate,
concentration,
fold_constants,
energy,
get_derived_unit,
is_... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function, division, absolute_import
import tempfile
import os
from .. import logger as pyyaks_logger
import six
def test_suppress_newline():
stdout = six.StringIO()
logger = pyyaks_logger.get_logger(level=pyyaks_logge... |
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, 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 ... |
import os, sys
config = dict()
# Supported module(s)
# <module>: {'status': True, 'help': '<help message>', 'description': '<module description>'}
config['modules'] = {
'default': {'status': True, 'help': 'Prints Hello World', 'description': 'Prints Hello World', 'args_chk': False},
'albus': {'status': True, ... |
import time
import pytest
from helpers.cluster import ClickHouseCluster
from multiprocessing.dummy import Pool
from helpers.test_tools import assert_eq_with_retry
def _fill_nodes(nodes, shard, connections_count):
for node in nodes:
node.query(
'''
CREATE DATABASE test;
CR... |
from django.core.management.base import BaseCommand
from core import fixtures
class Command(BaseCommand):
help = "Create demo site data"
def handle(self, *args, **options):
self.stdout.write(self.style.SUCCESS("creating perm group"))
fixtures.create_perm_group()
self.stdout.write(se... |
"""
Class for a more OOP interface to several potentials.
"""
# Import NumPy which is used to define pi, sqrt, array, .transpose etc. as
import numpy as np
from scipy.interpolate import CubicSpline
class Potential(object):
def __init__(self, file=None):
"""Constructor method, added vectorized version of... |
from django.shortcuts import render
from bokeh.plotting import figure, output_file, show
from django.http import HttpResponse
from django.urls import reverse
from bokeh.resources import CDN
from bokeh.embed import components
import math
# Create your views here.
def index(request):
if request.method == "GET":
... |
'''
Created on Oct 27, 2018
@author: nilson.nieto
'''
print("Int values")
a=12
b=231
c=2323
print(a,b,c)
print("Float point")
x=1.23
y=23.01
print(x,y)
print("Complex")
d = 3+ 2j
print(d)
print("Type conversion")
print("Binary ",bin(10))
print("Float",float("2.34"))
print("Hex",hex(18)) |
#Creating and Manipulating PDFs with pdfrw
# https://www.blog.pythonlibrary.org/2018/06/06/creating-and-manipulating-pdfs-with-pdfrw/
# Extract certain types of information from a PDF
# Splitting PDFs
# Merging / Concatenating PDFs
# Rotating pages
# Creating overlays or watermarks
# Scaling pages
# Combining the use o... |
# Copyright 2014 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/licenses/LICENSE-2.0
#
# Unless required by app... |
import pytest
from lhotse.cut import CutSet
from lhotse.dataset.speech_synthesis import SpeechSynthesisDataset
@pytest.fixture
def cut_set():
return CutSet.from_json('test/fixtures/ljspeech/cuts.json')
def test_speech_synthesis_dataset(cut_set):
dataset = SpeechSynthesisDataset(cut_set)
example = datas... |
# Generated by Django 2.2.8 on 2019-12-04 16:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reputation', '0010_auto_20191204_1515'),
]
operations = [
migrations.RemoveField(
model_name='withdrawal',
name='amount_deci... |
from setuptools import setup, find_packages
setup(
name='celery_zabbix',
version='1.0.5.pirdev1',
author='Zeit Online',
author_email='zon-backend@zeit.de',
url='https://github.com/zeitonline/celery_zabbix',
description="Sends task execution metrics to Zabbix",
long_description='\n\n'.join(... |
import requests
class ChuckTester:
def __init__(self):
self.chuck_endpoint = "http://127.0.0.1:8123"
self.endpoint = "https://test.net"
self.s = requests.Session()
self.s.proxies = {'https': 'https://127.0.0.1:8123'}
self.s.verify = False
def activate_scenario(self, s... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# ============================================================================
# Copyright (c) nexB Inc. http://www.nexb.com/ - All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the... |
from collections import namedtuple
import common.numpy_fast as np
from common.realtime import sec_since_boot
from selfdrive.config import CruiseButtons
from selfdrive.boardd.boardd import can_list_to_can_capnp
from selfdrive.controls.lib.drive_helpers import rate_limit
from common.numpy_fast import clip, interp
def a... |
"""
MISSING INDICATOR
- Adding a variable to capture NA
- In previous examples we learnt how to replace missing values by the mean, median or by extracting a random value.
- In other words we learnt about mean / median and random sample imputation.
- These methods assume that the data are missing completely at ... |
# -*- coding: utf-8 -*-
"""
@author: Yi Zhang.
Department of Aerodynamics
Faculty of Aerospace Engineering
TU Delft, Delft, Netherlands
"""
import sys
if './' not in sys.path: sys.path.append('./')
from root.config.main import *
from objects.CSCG._3d.forms.standard._2s.discretize.main impo... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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,... |
import pyfits as pf
import numpy as np
import matplotlib.pyplot as plt
from MuSCADeT import MCA
from MuSCADeT import pca_ring_spectrum as pcas
import scipy.stats as sc
from MuSCADeT import colour_subtraction as cs
## Openning data cube
cube = pf.open('./Simu_real/Cube.fits')[0].data
num,n,n = np.shape(cube)
## A for ... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "invoice4django.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
# 1. Read /Users/dkawata/work/obs/LAMOST/DR3/dr3_stellar.fits
# 2. output sels_rv.asc for gcdp-ana/lbsels.dat for mock data generation
# 3. Plot x-y distribution
#
# History:
# 29/03/2018 Written - Daisuke Kawata
#
import pyfits
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as... |
import time
from datetime import timedelta
from http.cookies import SimpleCookie
from unittest.mock import Mock, AsyncMock
import pytest
from fastapi import HTTPException
from fastapi.security import SecurityScopes
from starlette.responses import Response
from fastapi_login import LoginManager
from fastapi_login.exce... |
# Ensure that the local version of the runway module is used, not a pip
# installed version
import sys
sys.path.insert(0, '..')
sys.path.insert(0, '.')
import os
import pytest
import numpy as np
from PIL import Image
from runway.data_types import *
from runway.exceptions import *
# UTIL FUNCTIONS --------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# batsky documentation build configuration file, created by
# sphinx-quickstart on Tue Feb 25 18:58:55 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... |
#!/usr/bin/python3
'''Advent of Code 2018 Day 4 tests'''
import unittest
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from aoc2018 import day04 # pylint: disable=wrong-import-position
class TestUM(unittest.TestCase):
'''Unit Tests'''
def test_day04(sel... |
from rest_framework import serializers
from todo.models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ('id', 'title', 'complete', 'created')
# from django.contrib.auth.models import User, Group
#
# class UserSerializer(serializers.ModelSerializer... |
import requests
import time
import json
import datetime
from utils import cookie_string_to_mapping, read_configuration_file
from login_bot import login_bot
from vote_bot import VoteBot
if __name__ == "__main__":
config = read_configuration_file()
username = config['credentials']['username']
password = c... |
# -*- coding: utf-8 -*-
from ctypes import c_int, c_void_p
from functools import cached_property
import numpy as np
from pyfr.backends.base import BaseBackend
from pyfr.backends.openmp.compiler import OpenMPCompiler
class OpenMPBackend(BaseBackend):
name = 'openmp'
blocks = True
def __init__(self, cfg... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import re
__all__ = ['HTTP', 'redirect']
defined_status = {
200: 'OK',
201: 'CREATED',
20... |
import unittest
import os
import requests_mock
import tableauserverclient as TSC
import xml.etree.ElementTree as ET
from tableauserverclient.datetime_helpers import format_datetime
from tableauserverclient.server.endpoint.exceptions import InternalServerError
from tableauserverclient.server.request_factory import Requ... |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Recipe, Tag, Ingredient
from recipe.serializers import RecipeSerializer, RecipeDetailSerializer
RECIPES... |
# %%
#######################################
def new_objects_from_csv(csv_file: str):
"""For each row in the .csv, returns a list of custom objects with properties/attributes corresponding to the header names of each column.
Example:
>>> results = new_objects_from_csv('brandnew.csv')\n
>>> ppri... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
import re
from phising.blob_storage_operations.blob_operations import Blob_Operation
from utils.logger import App_Logger
from utils.read_params import read_params
class Raw_Train_Data_Validation:
"""
Description : This method is used for validating the raw training data
Version : 1.2
Revisio... |
#!/usr/bin/env python
#
# Copyright, Michael Vittrup Larsen
# Origin: https://github.com/MichaelVL/oidc-oauth2-workshop
import os
import flask
from flask_cors import CORS
import datetime
import json
import uuid
import urllib
import base64
import hashlib
import logging
from authlib.jose import jwt, jwk, JsonWebKey
ap... |
import requests
import sys
import os
from showtimes.app import app
def test_cinema_1_showtimes_index():
client = app.test_client()
reply = client.get("/")
actual_reply = reply.json
assert reply.status_code == 200
def test_cinema_1_booking_showtimes_showtimes():
client = app.test_client()
repl... |
import pytest
from top2vec import Top2Vec
from sklearn.datasets import fetch_20newsgroups
import numpy as np
# get 20 newsgroups data
newsgroups_train = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'))
newsgroups_documents = newsgroups_train.data[0:2000]
# train top2vec model without doc_ids ... |
from excel2py.base_proforma_calc import BaseProformaCalc
import unittest
class Sub(BaseProformaCalc):
inputs = {'x'}
class TestBaseProformaCalc(unittest.TestCase):
def test_good(self):
s = Sub()
s.calculate(x=4)
def test_missing(self):
s = Sub()
with self.assertRaises(Ty... |
import json
import logging
import time
import datetime as dt
import calendar
import numpy as np
from six.moves import cPickle as pickle
try:
import pandas as pd
is_pandas = True
except ImportError:
is_pandas = False
try:
from dateutil.relativedelta import relativedelta
is_dateutil = True
except I... |
# Copyright 2007 Google 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 applicable law or ag... |
from django.apps import apps
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from .models import Schema, Table, Column
@receiver(post_save, sender=Schema)
def schema_updated_handler(sender, **kwargs):
if apps.is_installed('daiqu... |
from pypy.interpreter.typedef import (TypeDef, GetSetProperty,
interp_attrproperty, interp_attrproperty_w)
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.gateway import unwrap_spec, interp2app
from pypy.interpreter.pycode import PyCode
from pypy.interpreter.error import OperationError
from... |
# Составить UML-диаграмму деятельности и программу для решения задачи: склавиатуры вводится номер месяца от 1 до 12,
# необходимо для этого номера месяца вывести наименование времени года
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if __name__ == '__main__':
n = int(input("Введите номер месяца: "))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.