content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes and CONTRIBUTORS
Email: danaukes<at>asu.edu.
Please see LICENSE for full license.
"""
import numpy
def twopointsthesame(pt1, pt2, tolerance):
v = numpy.array(pt2) - numpy.array(pt1)
l = v.dot(v)**.5
return l < tolerance
def rounded_equal(pt1,pt2,decim... |
""" Cut root
Graph type: Barabasi-Albert
MaxCut formulation: McCormic
Baseline: SCIP with defaults
Each graph is solved using different scip_seed,
and SCIP statistics are collected.
All results are written to experiment_results.pkl file
and should be post-processed using experiments/analyze_experiment.py
utils/analy... |
# -*- 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 ... |
#!/usr/bin/env python
from sensor_msgs.msg import Joy
from std_msgs.msg import Empty
from std_msgs.msg import Int8MultiArray
import rospy
DRIVE_PUB_INDEX = 0
YAW_PUB_INDEX = 1
KILL_INDEX_R1 = 5
DRIVE_INDEX = 1
YAW_INDEX = 3
class DualShock():
def __init__(self):
rospy.Subscriber('joy', Joy, self.callb... |
# -*- coding: utf-8 -*-
# Python imports
import base64
from decimal import Decimal, InvalidOperation
import functools
from http.client import UNAUTHORIZED
import logging
import random
import re
import string
# Django imports
from django.conf import settings
from django.contrib.auth.models import Permission
from django... |
import os
import pickle
import datasets
from dataclasses import dataclass
from typing import Optional
from torch.utils.data import IterableDataset
from datasets import IterableDatasetDict
from datasets.splits import Split, SplitDict, SplitGenerator
logger = datasets.utils.logging.get_logger(__name__)
class Pickl... |
#!/usr/bin/env python
# Copyright 2016-2021 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 require... |
import paddle
def gelu_python(x):
return x * 0.5 * (1.0 + paddle.erf(x / paddle.sqrt(2.0)))
def gelu_new(x):
return 0.5 * x * (1.0 + paddle.tanh(
paddle.sqrt(2.0 / 3.141592653589793) *
(x + 0.044715 * paddle.pow(x, 3.0))))
def gelu_fast(x):
return 0.5 * x * (1.0 + paddle.tanh(x * 0.797... |
"""
Combine .csv files into a single .csv file with all fields
2013-Nov-25 by Robert Woodhead, trebor@animeigo.com
2016-Apr by merrikat
Usage:
python combine-csv.py {csv folder} {output file} [{optional count field name}]
Where:
{csv folder} is a folder containing .csv files.
{output file} is the destination fi... |
'''
Created on Mar 7, 2011
@author: johnsalvatier
'''
from __future__ import division
import numpy as np
import scipy.linalg
import theano.tensor as tt
import theano
from theano.scalar import UnaryScalarOp, upgrade_to_float
from .special import gammaln
from pymc3.theanof import floatX
from six.moves import xrange
f... |
# -*- coding: utf-8 -*-
"""
Created on July 2017
@author: JulienWuthrich
"""
import logging
class LogFile(object):
def __init__(self, logfile, level, show=False, fmt="%(message)s"):
self.logfile = logfile
self.level = level
self.fmt = fmt
self.logger = logging.getLogger(logfile)
... |
import os
import csv
import random
from buses.Demand import Demand
from traffic_types import PEAK
path = os.environ['TS_SIMULATION']
def generate(traffic_type, city):
if traffic_type == PEAK:
generate_peak_hour_traffic(city)
def generate_peak_hour_traffic(city):
random.seed(42)
path = os.envir... |
#!/usr/bin/env python
# Copyright 2016 Google 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 ... |
import os
import sys
os.environ['KMP_DUPLICATE_LIB_OK']='True'
# file path for fitted_Q_agents
FQ_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(FQ_DIR)
# file path for chemostat_env
C_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
C_DIR = os.path... |
from .exchange import Exchange
class ExchangeReleaseFeedback(Exchange):
pass
|
from collections import deque
def readable_size(b):
bytes=iter(["B", "KB", "MB", "GB", "TB", "PB"])
res=deque([])
while b>0:
num, byte=b%1024, next(bytes)
if num>0:
res.appendleft(f"{num} {byte}")
b//=1024
if len(res)<=2:
return ", ".join(res)
last=res.pop... |
# -*- coding:utf-8 -*-
#!/usr/bin/env python
import logging
from typing import List,Dict,Any#,Union
from attrbox import AttrDict
from ....definations.cfg import DY_CONFIGURATION_KEY_DEF, ConfigerDefs
# from ....dataclasses.i.rdb import IDatabase
from ....dataclasses.i.cfg import IDatabaseConfiger
from ....dataclasses.... |
import random
from vardefunc.noise import AddGrain
seed = random.seed()
graigasm_args = dict(
thrs=[x << 8 for x in (26, 75, 130, 180)],
strengths=[(0.7, 0.2), (1, 0.12), (1.05, 0.05), (0.12, 0)],
sizes=(1.1, 1.53, 1.86, 1.7),
sharps=(80, 60, 40, 40),
grainers=[
AddGrain(seed=seed, constan... |
_base_ = '../faster_rcnn/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco-person.py'
# _base_ = [
# '../_base_/models/faster_rcnn_r50_fpn.py',
# '../_base_/datasets/coco_detection.py',
# '../_base_/schedules/schedule_1x.py',
# '../_base_/default_runtime.py'
# ]
# model
# freeze backbone completely
model = dic... |
from DataHandler import *
from Util import *
from DataProcessor import *
from Portfolio import *
from datetime import datetime
from dateutil.relativedelta import relativedelta
def get_date(dat, end_date_intervel, start_date_intervel):
e = (datetime.strptime(dat, '%Y-%m-%d')+ relativedelta(days=end_date_intervel)... |
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
from typing import List, Dict, Tuple
NO_FRIENDSHIP = -1
@dataclass
class User:
user_id: str
friends: List[User]
def __eq__(self: User, other: User) -> bool:
return self.user_id == other.user_id
... |
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import math
>>> math.pi
3.141592653589793
>>>
>>> def circle_area(radius):
area = math.pi * (radius ** 2)
return area
>>> circle_area(... |
# /usr/bin/python3
import datetime
def tup_replace(tup, pos, value):
_l = list(tup)
_l[pos] = value
return tuple(_l)
def get_timestamp(form="%Y%m%d%H%M"):
return datetime.datetime.now().strftime(form)
if __name__ == "__main__":
pass |
from typing import List
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def find_island(row: int, col: int):
if 0 <= row < m and 0 <= col < n and grid[row][col]:
grid[row][col] = 0
return 1 + find_island(row - 1, col) + find_island(row +... |
# Generated file, please do not change!!!
import typing
from ..active_cart.by_project_key_in_store_key_by_store_key_me_active_cart_request_builder import (
ByProjectKeyInStoreKeyByStoreKeyMeActiveCartRequestBuilder,
)
from ..carts.by_project_key_in_store_key_by_store_key_me_carts_request_builder import (
ByPro... |
# encoding: utf-8
"""
@author: jemmy li
@contact: zengarden2009@gmail.com
"""
if __name__ == '__main__':
pass |
import asyncio
import collections
import re
from pychess.System.Log import log
from pychess.ic import BLOCK_START, BLOCK_SEPARATOR, BLOCK_END, BLKCMD_PASSWORD
from pychess.ic.icc import UNIT_START, UNIT_END, DTGR_START, MY_ICC_PREFIX
class ConsoleHandler:
def __init__(self, callback):
self.callback = cal... |
import logging
from airflow_helpers.sdc_airflow_config import dag_emails
from sdc_etl_libs.sdc_data_exchange.SDCDataExchangeEnums import FileResultTypes
class AirflowHelpers:
@staticmethod
def combine_xcom_pulls_from_tasks(tasks_, key_='etl_results',
return_html_=True, ... |
from flask import Flask
import requests
app = Flask(__name__)
@app.route("/")
def hello():
response = requests.get("http://10.0.0.3:5000/companies")
print(response.status_code)
json = str(response.content)
return json
# if __name__ == '__main__':
# app.run(host='0.0.0.0', port=5001) |
from django.apps import AppConfig
class VnfpackagesubscriptionConfig(AppConfig):
name = 'VnfPackageSubscription'
|
import unittest
import pytest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from {{ cookiecutter.project_slug }}.config.settings.base import ROOT_DIR, env
class FunctionalTest(unittest.TestCase):
def setUp(s... |
# -*- coding: utf-8 -*-
def fact(n): # 计算阶乘n! = 1 * 2 * 3 * ... * n
if 1 == n:
return 1
return n * fact(n - 1)
def fact2(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product) # 仅返回递归函数本身,参数... |
import numpy as np
import const
class TrueData():
def __init__(self, path_features="", path_label=""):
assert path_label!= "" and path_features != ""
self._index_in_epoch = 0
self._epochs_completed = 0
#self._num_examples = const.N_EXAMPLE
self._rate = 0.8
n_c... |
import os
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
from detection import detect_people
app = Flask(__name__)
UPLOAD_FOLDER = './static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def main():
return render_template('./main.html')
@a... |
# (c) Copyright IBM Corp. 2021
# (c) Copyright Instana Inc. 2017
import sys
import string
import instana
if sys.version_info.major == 2:
string_types = basestring
else:
string_types = str
def test_id_generation():
count = 0
while count <= 10000:
id = instana.util.ids.generate_id()
ba... |
spark = SparkSession \
.builder \
.appName("exercise_twentysix") \
.getOrCreate()
df.groupBy("gender").avg("salary").show()
df.groupBy("country").avg("salary", "id").show(7)
|
# -*- coding:utf-8 -*-
__author__ = 'XF'
'meta network'
import os
import math
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import torch
import torch.nn as nn
from torch.nn import functional as F
from copy import deepcopy
from tools import metrics as Metrics
torch.set_defaul... |
# Copyright (c) 2017, 2020, DCSO GmbH
import urllib.request, urllib.error, urllib.parse
import urllib.request, urllib.parse, urllib.error
import json
import csv
import sys
import argparse
import time
import os
import logging, logging.handlers
import splunk
from splunk.clilib import cli_common as cli
proxy_args = cli... |
class Bar(object):
pass
class Foo(object):
def __foo__(self):
print 'hi'
f = Foo()
f.__foo__()
x = f.__foo__
x()
#g = Foo()
#b = Bar()
x = Foo.__foo__
x(g)
x(b)
|
"""
Latin Hypercube Sampling and Descriptive Sampling
This file is part of PUQ
Copyright (c) 2013 PUQ Authors
See LICENSE file for terms.
"""
from __future__ import absolute_import, division, print_function
import sys
import numpy as np
from puq.util import process_data
from puq.psweep import PSweep
from logging impo... |
class MagicalGirlLevelOneDivTwo:
def theMinDistance(self, d, x, y):
return min(
sorted(
(a ** 2 + b ** 2) ** 0.5
for a in xrange(x - d, x + d + 1)
for b in xrange(y - d, y + d + 1)
)
)
|
from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
"""
Tests for EntityEnum module
"""
__author__ = "Graham Klyne (GK@ACM.ORG)"
__copyright__ = "Copyright 2014, G. Klyne"
__license__ = "MIT (http://opensource.org/licenses/MIT)"
import os
import unittes... |
"""
Modular Exponential.
Modular exponentiation is a type of exponentiation performed over a modulus.
For more explanation, please check
https://en.wikipedia.org/wiki/Modular_exponentiation
"""
"""Calculate Modular Exponential."""
def modular_exponential(base: int, power: int, mod: int):
"""
... |
#!/usr/bin/env python
"""Test runner for typeshed.
Depends on mypy and pytype being installed.
If pytype is installed:
1. For every pyi, run "pytd <foo.pyi>" in a separate process
"""
import os
import re
import sys
import argparse
import subprocess
import collections
parser = argparse.ArgumentParser(description... |
import copy
from datetime import datetime, timedelta
from dateutil.rrule import DAILY, MONTHLY, WEEKLY, YEARLY, rrule, rruleset
from django.contrib import messages
from django.core.files import File
from django.db import connections, transaction
from django.db.models import F, IntegerField, OuterRef, Prefetch, Subquer... |
"""
"""
import numpy as np
def get_params(lgm):
mu_lgtc = _mean_lgtc_vs_m0(lgm)
sig_lgtc = _sigma_lgtc_vs_m0(lgm)
u_frac_rounder = _u_frac_rounder_vs_m0(lgm)
mean_e_early_rounder = _mean_e_early_rounder_vs_m0(lgm)
mean_e_late_rounder = _mean_e_late_rounder_vs_m0(lgm)
mean_e_early_flatter = _me... |
import csv
import math
from collections import defaultdict
import numpy as np
'''
about:
this code assumes that the output file (the result of our ML) matches the same csv schema as validation.csv, including the first row being collumn names
it loads the expected (validation.csv) grountTruth into a dictionnary and th... |
from __future__ import unicode_literals
import boto3
import datetime
import requests
import json
def ping(event, context):
"""Ping the status of a webpage."""
options = {
'domain': 'example.com',
'protocol': 'http',
'path': '/',
'method': 'GET',
'allow_redirects': "Fals... |
from selinon import SelinonTask
class HelloTask(SelinonTask):
def run(self, node_args):
"""A simple hello world."""
return {"result": "Hello, {}!".format(node_args.get('name', 'world'))}
|
from flask import Blueprint
profile_blue = Blueprint('profile',__name__,url_prefix='/profile')
from . import views |
from typing import Any, Dict, List
from lit_nlp.api import model as lit_model
from lit_nlp.api import types as lit_types
from expats.profiler.base import TextClassifier
class LITModelForTextClassifier(lit_model.Model):
def __init__(self, profier: TextClassifier, labels: List[str]):
self._profiler = pro... |
from django.shortcuts import render
def gone(request, *args, **kwargs):
"""
Display a nice 410 gone page.
"""
return render(request, '410.html', status=410)
|
"""Tests for neurodocker.interfaces.PETPVC"""
# Author: Sulantha Mathotaarachchi <sulantha.s@gmail.com>
from __future__ import absolute_import, division, print_function
import pytest
from neurodocker import DockerContainer, Dockerfile
from neurodocker.interfaces import petpvc
from neurodocker.interfaces.tests import... |
import math
import json
from cocoa.web.main.db_reader import DatabaseReader as BaseDatabaseReader
from cocoa.core.util import write_json
class DatabaseReader(BaseDatabaseReader):
@classmethod
def get_chat_outcome(cls, cursor, chat_id):
outcome = super(DatabaseReader, cls).get_chat_outcome(cursor, chat... |
from django import forms
from .models import Participant
class RegistrationForm(forms.Form):
email=forms.EmailField(label='Your Email')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tagger wrappers that wrap AllenNLP functionality. Used for and named entity recognition.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import math
import logging
import re
import copy
import datetime
... |
import board
import piece
def mov_to_coord(movement):
if type(movement) is not str or len(movement) != 2:
return None
y = int(movement[1]) - 1
x = ord(movement[0].upper()) - ord('A')
if x<0 or x>7 or y<0 or y>7:
print(x,y)
return None
return (x,y)
game = board.B... |
import requests
from os.path import basename, isdir
from sys import argv, exit
VERSION = "0.1.2"
def download(url, path, *, headers: dict = None, payloads: dict = None):
"""
:param url: url for file.
:param path: directory_name with file_name.
"""
resp = requests.get(url, stream=True, param=paylo... |
"""Backfill PRM Database
Revision ID: 670ea976fe9f
Revises: 0c393dd2ea3c
Create Date: 2021-05-06 16:14:02.348642
"""
from alembic import op
import sqlalchemy as sa
import pendulum
# revision identifiers, used by Alembic.
revision = '670ea976fe9f'
down_revision = '0c393dd2ea3c'
branch_labels = None
depends_on = Non... |
#!/usr/bin/python3
import re
import subprocess
import sys
# list of custom filter regexs
FILTER_REGEXS = [
r"^ system commands enabled\.$",
r"^entering extended mode$",
r"^ restricted \\write18 enabled.$",
r"^LaTeX2e <[0-9\-]+>$",
r"^luaotfload | main : initialization completed in ",
r"^Babel <.*> and hyp... |
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import authenticate
from dj_rest_auth.serializers import LoginSerializer
from rest_framework import exceptions
class LoginSerializerCustom(LoginSerializer):
def _validate_username(self, username, password):
user = None
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
' strings_comparator.py '
__author__ = 'Hyman Lee'
############## main code ###############
import os
# from xml.dom import minidom
from translators import YouDaoTranslator
import const
from openpyxl import Workbook
from openpyxl import load_workbook
from excel_helper i... |
import gmsh
OUTPUT_TEMPLATE = """# GENERATED by gmsh_interop/contrib/gmsh-node-tuples.py
# GMSH_VERSION: %s
# DO NOT EDIT
triangle_data = %s
tetrahedron_data = %s
quadrangle_data = %s
hexahedron_data = %s
"""
TRIANGLE_ELEMENTS = {
"MSH_TRI_3": 2,
"MSH_TRI_6": 9,
"MSH_TRI_10": 21,
... |
from math import ceil, floor
def get_ix_slice(relayoutData):
if relayoutData is None:
return None
else:
try:
return slice(
floor(relayoutData['xaxis.range[0]']),
ceil(relayoutData['xaxis.range[1]'])
)
except KeyError:
... |
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext as _
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile')
about = models.TextField(_('About'))
zip = models.CharField(_('Zip Code'), help_tex... |
import unittest2 as unittest
import os
import datetime
class HouseKeeping(unittest.TestCase):
def test_license_year(self):
self.assertTrue(os.path.exists('LICENSE.txt'))
now = datetime.datetime.now()
current_year = datetime.datetime.strftime(now, '%Y')
license_text = open('LICENSE... |
import sys
import os
import argparse
from tools import remote, Action
from actions import check, request
from subprocess import getstatusoutput
def parse_parames():
parse = argparse.ArgumentParser()
request_group = parse.add_mutually_exclusive_group()
request_group.add_argument('-l', '--list', action='store_tru... |
import sys
import pprint
import json
import windows.generated_def.winfuncs
import windows.generated_def.winstructs
import windows.generated_def.interfaces
from ctypes import _CFuncPtr, Structure, _Pointer, Union, _SimpleCData, CDLL, c_ulong
class Dumper:
def __init__(self, debug_level = 0):
self.debug_le... |
import numpy as np
import pandas as pd
csv = 'C:\Program Files\Git\data301\course-project-group_6016\Analysis\Daven Minhas\Electric_Vehicle_Population_Data.csv'
def load_and_process(csv):
df1 = (
pd.read_csv(csv)
.drop('State', axis=1)
.drop('Clean Alternative Fuel Vehicle (CAFV) Eli... |
"""
Unit tests for `EncryptionEngine`s.
"""
# Standard Library
import base64
import io
import random
import string
import unittest
import numpy as np
# Vimcryption
from encryptionengine import *
class TestEncryptionEngine(unittest.TestCase):
""" Unit tests for EncryptionEngine
"""
def test_encrypt_str(sel... |
from django.db import models
from model_utils import FieldTracker
class Location(models.Model):
address = models.CharField(max_length=255, null=True)
postal_code = models.CharField(max_length=20, null=True)
city = models.CharField(max_length=150, null=True)
country_code = models.CharField(max_length=20... |
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'jack.settings'
import django.core.handlers.wsgi
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../'))
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
application = django.core.handlers.wsgi.WSGIHandler()
|
import numpy as np
# import pandas as pd
import random
# import copy
import matplotlib.pyplot as plt
# import csv
ENABLE_PRINT = 0
DETAILED_ENABLE_PRINT=0
#convert the preference matrix into ranking matrix
def get_ranking(preference):
ranking = np.zeros(preference.shape,dtype=int)
for row in range(0,len(prefer... |
from xendbg.xen._bindings import ffi, lib
from xendbg.xen.exceptions import XenException
class XenForeignMemory:
def __init__(self):
self.fmem = lib.xenforeignmemory_open(ffi.NULL , 0)
if self.fmem == ffi.NULL:
raise XenException('failed to open xen foreign memory handle', errno=True)
... |
#imports
from pynput.keyboard import Key, Controller
import urllib.request
import re
import time
import random
keyboard = Controller()
postmemesSubList = ["d", "e", "n", "m", "r"]
html = urllib.request.urlopen("https://pastebin.com/raw/NUMtwjAx").read().decode()
def checkKillSwitch():
global killSwitchOn
htm... |
# -*- coding: utf-8 -*-
import os, logging
from telegram import (InlineKeyboardButton, InlineKeyboardMarkup,
InlineQueryResultArticle, InputTextMessageContent)
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, InlineQueryHandler, ChosenInlineResultHandler
impo... |
# Test methods with long descriptive names can omit docstrings
# pylint: disable=missing-docstring
import unittest
import Orange
from Orange.clustering.dbscan import DBSCAN
class TestDBSCAN(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.iris = Orange.data.Table("iris")
def test_dbsca... |
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return flag
# Modify variable names to be more descriptive. Add in commentary.
def any_lowercase4(word):
"""
- Returns a True or False to the question of whether the inputted word has any lower case letters.
... |
#!/usr/bin/env/ python
# coding=utf-8
__author__ = 'Achelics'
__Date__ = '2017/05/16'
from data_pre_process.split_banner_man import *
import os
import json as _json
def get_ip_banner(path, filename, protocol_validity_json):
"""
提取ip和标语
:param path: 标语文件所在路径
:param filename: 标语文件名称
:param prot... |
# _*_ coding: utf-8 _*_
"""
Bill Classifier.
Author: Genpeng Xu
"""
import joblib
from typing import Union, List
# Own customized variables & modules
from bill_helper.tokenizer import MyTokenizer
from bill_helper.global_variables import (T1_VECTORIZER_FILEPATH,
T1_MODEL_FIL... |
import json
from bots.common.helpers import non_slash
from bots.groupme.groupme_helpers import send_message
from bots.helpers import ShowView
def handle_groupme(request) -> bool:
"""Handles groupme bot inputs
Parameters
----------
request : Request
The request object provided by FASTAPI
... |
from django.db import models
from django.conf import settings
# Create your models here.
class Papaya(models.Model):
id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True)
name = models.CharField(max_length=200)
class Task(models.Model):
id = models.ForeignKey(settin... |
from django.db import models
from django.conf import settings
class Report(models.Model):
# Restrict choices for certain fields- format is 'stored value', 'readable value'
REPORT_TYPE_CHOICES = [('RV', "Review"), ('PF', "Profile"), ('ND', "Noodle")]
REASON_CHOICES = [('AD', "Advertising"), ('HR', "Harassme... |
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from allauth.account.models import EmailAddress
from factory import Faker, SelfAttribute, Sequence, SubFactory, post_generation
from factory.django import DjangoModelFactory
from factory.fuzzy import FuzzyChoice
class GroupFa... |
from PyQt4.Qt import QDialog, QLineEdit, QFormLayout, QPushButton, SIGNAL, QErrorMessage
from Geon.utils import DEFAULT_HOST, DEFAULT_PORT, DEFAULT_DATABASE, DEFAULT_USER, DEFAULT_PASSWORD
class GDialConnectDatabase(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setWin... |
#!/usr/bin/env python3
"""
exercise 4 for jinja rendering
"""
from __future__ import unicode_literals, print_function
from jinja2 import FileSystemLoader, StrictUndefined
from jinja2.environment import Environment
env = Environment(undefined=StrictUndefined)
env.loader = FileSystemLoader("./templates")
my_vars = [
... |
import unittest
import json
from mock import Mock, patch
from unittest.mock import MagicMock, PropertyMock
from cfBroker.applicationSettings import ApplicationSettings
from cfBroker.cfClient import CfClient
class TestCfClient(unittest.TestCase):
def setUp(self):
appSettings = ApplicationSettin... |
from unittest import TestCase
from unittest.mock import patch
from btfix.parser import _rename_dir
def mocked_rename(*args, **kwargs):
pass
class ParserTestCase(TestCase):
@patch('os.rename', mocked_rename)
def test_rename_dir(self):
mac = 'AA:BB:CC:DD:EE:FF'
path = '/some/path/to/file... |
#!/usr/bin/env python3
import blynklib, blynktimer
import datetime as dt
import calendar as cal
isSystemEnabled = False
isSchedulerEnabled = False
weissVPINs = { "VPIN_ALARM": 0 }
weekdayVPINs = { "Monday": 10, "Tuesday": 11, "Wednesday": 12, "Thursday": 13, "Friday": 14, "Saturday": 15, "Sunday": 16 }
timerangeVPINs... |
import torch
import torchvision
from PIL import Image
from Models import U_Net
data_transform = torchvision.transforms.Compose([
# torchvision.transforms.Resize((128,128)),
# torchvision.transforms.CenterCrop(96),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean=[0.5, 0.5, 0... |
# coding: utf-8
# Copyright (c) 2017 Hitachi, Ltd. All Rights Reserved.
#
# Licensed under the MIT License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/MIT
#
# This file is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OF ANY KIND.
from bottle import route
from common imp... |
from .swarm import Swarm
from .insect import Insect
from .hive import Hive |
class Account:
id = int
name = str
document = str
email = str
password = str
def __init__(self, name, document):
self.name = name
self.document = document |
import _init_paths
import os
import sys
import argparse
import os.path as osp
import random
import pickle
import glob
import numpy as np
import ipdb
st = ipdb.set_trace
# from lib.tree import Tree
# from modules import Layout, Combine, Describe
######### hyperparameters ##########
def refine_tree_info(tree):
t... |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
"""Provides a base Test class."""
from math import floor
from typing import Any, Dict, List
from okpt.io.config.parsers.test i... |
# Copyright (c) 2021 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 appli... |
# Author: legend
# Mail: kygx.legend@gmail.com
# File: docker.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
def install():
"""
Ref:
1. https://github.com/dhiltgen/docker-machine-kvm
2. https://www.howtoforge.com/how-to-install-kvm-and-libvirt-on-centos-6.2-with-bridged-networking
3. http://blog.aru... |
from django.urls import reverse
from service_catalog.forms import FormUtils
from tests.test_service_catalog.base import BaseTest
class TestServiceRequestForm(BaseTest):
def setUp(self):
super(TestServiceRequestForm, self).setUp()
def test_get_available_fields(self):
expected_result = {
... |
import abc
from typing import Dict, Iterable
from phdTester.common_types import KS001Str, PathStr, DataTypeStr
from phdTester.commons import UnknownStringCsvReader
from phdTester.model_interfaces import IResourceManager, IDataSource, ICsvResourceManager
class AbstractCsvResourceManager(ICsvResourceManager, abc.ABC):... |
#!/usr/bin/env python
"""
This copies and converts files in nii folder to a bids folder in BIDS format
Usage:
bidsify.py [options] [-s <SUBJECT>]... <study>
Arguments:
<study> Study name defined in master configuration
.yml file to convert to BIDS format
Opti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.