content stringlengths 5 1.05M |
|---|
import argparse
from torch.utils.data import DataLoader
from model import BERT
from trainer import BERTTrainer
from dataset import BERTDataset, WordVocab
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--train_dataset", required=True, type=str)
parser.add_argument("-t", "--test_dataset", type=str, def... |
# Creates an HTML file consisting of an interactive plot from Ontario Covid-19 database.
import pandas as pd
import numpy as np
import ssl
import bokeh.plotting as plt
from bokeh.models import LinearAxis, Range1d, HoverTool, SingleIntervalTicker
from scipy.signal import savgol_filter as sf
data_url = 'https:... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AmpeDeviceVO(object):
def __init__(self):
self._add_time = None
self._device_id = None
self._model_id = None
self._model_name = None
self._model_no = None
... |
from browser import document, bind
# Note: If you could avoid unnecessary import, your script will save several seconds loading time
# For example, use `"message".title()` instead of `import string; string.capwords("message")`
import datetime
from collections import Counter
from dateutil.easter import easter # Came ... |
from typing import Union
class UInt160(bytes):
"""
Represents a 160-bit unsigned integer.
"""
def __init__(self, arg: Union[bytes, int] = 0):
super().__init__()
pass
class UInt256(bytes):
"""
Represents a 256-bit unsigned integer.
"""
def __init__(self, arg: Union[b... |
import json
import asyncio
import pytest
from model_mommy import mommy
from aiohttp import ws_connect, WSServerHandshakeError
from aiohttp.web import Application, MsgType
from rest_framework.authtoken.models import Token
from redis_pubsub.contrib.websockets import websocket, websocket_pubsub
from redis_pubsub.contr... |
from typing import Any
from pyspark.ml.clustering import KMeans
from pyspark.ml.evaluation import MulticlassClassificationEvaluator
from pyspark.sql import DataFrame
from sparksampling.core.job.base_job import BaseJob
import numpy as np
from pyspark.sql.types import DoubleType
from sparksampling.core.mlsamplinglib.fu... |
#!python
import click
# from prettytable import PrettyTable
import json
import requests
import os
from string import Template
import re
METAURL = 'https://api.softlayer.com/metadata/v3.1'
SERVICEMARKDOWN = """---
title: "$service"
description: "$documentation"
date: "2018-02-12"
tags:
- "$layoutType"
- "sld... |
import gzip
from io import BytesIO
try:
from jsmin import jsmin
from cssmin import *
except:
jsmin = None
cssmin = None
def gzip_content(headers, stream):
"Gzips a file"
headers['Content-Encoding'] = 'gzip'
buff = BytesIO()
gz = gzip.GzipFile(filename="tmp", fileobj=buff, mode='w')
... |
import django_filters
from django_filters import rest_framework as filters
from rest_framework import viewsets
from .models import Ilm, Jaam
from .serializers import IlmSerializer, JaamSerializer
class IlmFilter(filters.FilterSet):
# Võimaldab API päringuid: http://18.196.203.237:8000/api/i/?m=2&y=2013&d=24&h=12
... |
import streamlit as st
import pandas as pd
import numpy as np
import functools
import fetch
import data
import error
def main():
if st.sidebar.button("Refresh Data"):
st.caching.clear_cache()
league_id = st.sidebar.text_input("League ID", value="309333")
try:
league_id = int(league_id)
... |
import math
import os
from payton.scene import Scene
from payton.scene.geometry import Wavefront
scene = Scene()
scene.background.top_color = [0, 0, 0, 1]
scene.background.bottom_color = [0, 0, 0, 1]
amount = 0.5
total_angles = -30
def swing(period, total):
global total_angles, amount
scene.objects["lamp"]... |
import numpy as np
# Fuel is infinite, so an agent can learn to fly and then land on its first attempt.
# Action is two real values vector from -1 to +1. First controls main engine, -1..0 off, 0..+1 throttle from 50% to 100% power.
# Engine can't work with less than 50% power.
# Second value -1.0..-0.5 fire left engin... |
from six.moves.urllib.parse import (
parse_qsl,
quote_plus,
unquote_plus,
urlencode,
urlparse,
urlunparse,
)
WEB2DBND_MAP = {"http": "dbnd", "https": "dbnd+s"}
DBND2WEB_MAP = {
"dbnd": "http",
"databand": "http",
"dbnd+s": "https",
"databand+s": "https",
}
def is_composite_u... |
# Copyright 2022 ConvolutedDog (https://github.com/ConvolutedDog/)
#
# 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 ... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/casch/Dropbox/humanoid_robot/catkin_ws/src/pr2_simulator/pr2_gazebo_plugins/msg/PlugCommand.msg;/home/casch/Dropbox/humanoid_robot/catkin_ws/src/pr2_simulator/pr2_gazebo_plugins/msg/ModelJointsState.msg"
services_str = "/home/casch/Dropbox/human... |
source_domain = None # set by user
target_domain = None # set by user
init_cfg = dict(type='studio')
# model settings
model = dict(
type='Pix2Pix',
generator=dict(
type='SAGANGenerator',
output_scale=128,
base_channels=64,
attention_cfg=dict(type='SelfAttentionBlock')... |
"""
Created on 13/nov/2019 with PyCharm
INPI - Instituto Nacional da Propriedade Industrial
@author: Rafael Nunes - rafael.nunes@inpi.gov.br
@title: hackerrank - test_averybigsum.py
--------------------------------------------------------------------------------
*** Description of the module function ***
------... |
from django.apps import AppConfig
class CalendarioConfig(AppConfig):
name = 'frequencia.calendario'
|
import cv2 as cv
def gray_to_ascii(img):
'''convert grayscale image into ascii formated image'''
ascii_format = ['.', ',', '*', '+', '^', ';', '?', '%', '$', "#", '@']
ascii_draw = ''
i=0
for x in img.flatten():
i+=1
ascii_draw+= ascii_format[x//25]
if ... |
"""
Utilities
---------
Utility functions for general operations and plotting.
Contents:
normalize,
gen_list_of_lists,
gen_faction_groups,
gen_parl_points,
swap_parl_allocations,
hex_to_rgb,
rgb_to_hex,
scale_saturation
"""
import colorsys
import numpy as np
import pandas as pd
from ... |
from hopex.client.trade import TradeClient
from hopex.constant.test import t_api_key, t_secret_key
from hopex.utils.log_info import LogInfo
trade_client = TradeClient(api_key=t_api_key, secret_key=t_secret_key)
"""
The condition orders information
:params
contract_code_list: Contract List, Being blank ... |
n=int(input())
a='abcdefghijklmnopqrstuvwxyz'
pad=n+n-1+n+1
res=[]
for i in range(n):
p1=a[i:n]
p2=a[i+1:n][::-1]
a1='-'.join(map(str,list(p1)))
a2='-'.join(map(str,list(p2)))
print(a1,a2)
if a2=='':
req=a1
else:
req=a2+'-'+a1
res.append(req.center(pad,'-'))
res=res[1:][:... |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Firewall Manager"
prefix = "fms"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
... |
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import torch
import numpy as np
from collections import OrderedDict
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
... |
from dps.hyper import run_experiment
from dps.utils import copy_update
from silot.run import basic_config, alg_configs, env_configs
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--max-digits', type=int, choices=[6, 12], required=True)
args, _ = parser.parse_known_args()
distributions = dict... |
from django.db import models
from db.base_model import BaseModel
from tinymce.models import HTMLField
# Create your models here.
class GoodsType(BaseModel):
name = models.CharField(max_length=20)
logo = models.CharField(max_length=20)
image = models.ImageField(upload_to='type')
def __str__(self):
... |
import torch
import torch.nn as nn
import numpy as np
import torchvision
import torch.nn.functional as F
import math
import copy
import collections
from pytorchcv.model_provider import get_model as ptcv_get_model
from pytorchcv.models.common import conv3x3_block
import pretrainedmodels
class Flatten(nn.Module):
def... |
"""
``goless`` introduces go-like channels and select to Python,
built on top of Stackless Python (and maybe one day gevent).
Use :func:`goless.chan` to create a synchronous or buffered channel.
Use :func:`goless.select` like you would the ``Select`` function in Go's reflect package
(since Python lacks a switch/case st... |
COLUMNS=['ts', 'curr_pid', 'pid', 'src_cpu', 'dst_cpu', 'imbalance',
'src_len', 'src_numa_len', 'src_preferred_len',
'delta', 'cpu_idle', 'cpu_not_idle', 'cpu_newly_idle',
'same_node', 'prefer_src', 'prefer_dst',
'delta_faul... |
# The MIT License (MIT)
# Copyright (c) 2017 Massachusetts Institute of Technology
#
# Authors: Victor Pankratius, Justin Li, Cody Rude
# This software has been created in projects supported by the US National
# Science Foundation and NASA (PI: Pankratius)
#
# Permission is hereby granted, free of charge, to any person... |
from app import app, mongo
from flask_restful import Resource, Api
from flask import jsonify, request
from bson.objectid import ObjectId
import bcrypt, datetime
from flask_jwt_extended import (
create_access_token,
create_refresh_token,
jwt_refresh_token_required,
get_jwt_identity,
get_raw_jwt,
... |
inputs = [1.2, 5.1, 2.1]
weights = [3.1, 2.1, 8.7]
bias = 3
output = inputs[0]*weights[0] + inputs[1]*weights[1] + inputs[2]*weights[2] + bias
print(output) |
from pylatex import Section, Command, NoEscape
def add_competence(doc, cv_data):
with doc.create(Section("Competences")):
doc.append(Command("textbf", arguments=NoEscape("Techniques" + " ")))
techniques = ""
for technique in cv_data["technique"]:
techniques += (technique + ", "... |
# ini file
|
from transpose_dict import TD
import json
def test_transpose_dict():
with open("tests/start.json", "r") as f:
start = json.load(f)
for i in range(3):
with open("tests/test_{i}.json".format(i=i), "r") as f:
print(TD(start, i))
assert json.load(f) == TD(start, i) |
from django.urls import path
from . import views
from .decorators import org_admin_only, unauthenticated_user
from django.contrib.auth.views import LoginView, LogoutView
from .views import (
PolicyListView,
PolicyCreateView,
PolicyDeleteView,
PolicyUpdateView,
OrganizationCreateView,
)
urlpatterns ... |
import sys
class Matrix:
def __init__(self, array):
self.rows = len(array)
self.cols = len(array[0])
self.array = array
def calculate_min_top_down_path(self):
return self.calculate_min_top_down_path_impl(0, 0)
def calculate_min_top_down_path_impl(self, row, col):
i... |
import datetime
import math
import itertools
import pytest
import calendar
from homeplotter.timeseries import TimeSeries
sample_data = {
"both-broken":[[datetime.date(2020, 10, 12), 200.0],[datetime.date(2020, 11, 24), 50.0],[datetime.date(2020, 12, 5), 200.0], [datetime.date(2020, 12, 30), 400.0], [datetime.date... |
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Project model."""
from ggrc import db
from ggrc.access_control.roleable import Roleable
from ggrc.fulltext.mixin import Indexed
from ggrc.models import mixins
from ggrc.models.mixins import synchronizable
... |
"""
Exceptions declaration.
"""
__all__ = [
"PyCozmoException",
"PyCozmoConnectionError",
"ConnectionTimeout",
"Timeout",
]
class PyCozmoException(Exception):
""" Base class for all PyCozmo exceptions. """
class PyCozmoConnectionError(PyCozmoException):
""" Base class for all PyCozmo conn... |
# -*- coding: utf-8 -*-
from openprocurement.archivarius.core.utils import Root
def factory(request):
request.validated['contract_src'] = {}
root = Root(request)
if not request.matchdict or not request.matchdict.get('contract_id'):
return root
request.validated['contract_id'] = request.matchd... |
from nbconvert.exporters.exporter import ResourcesDict
from nbdocs.core import read_nb
from nbdocs.process import (
CorrectMdImageLinkPreprocessor,
copy_images,
correct_markdown_image_link,
md_correct_image_link,
get_image_link_re,
md_find_image_names,
)
from nbdocs.tests.base import create_tmp_... |
""" dblist - Detect accessible databases and display properties
(architecture, platform and version),
also return the Field Definition Table if a file number is specified
Usage:
python dblist.py --dbids <dbid> [--fnr <fnr> --xopt <LF-option> <other> ]
Options:
-a, --auth dbid,userid... |
"""
A simple script listing serial ports on the computer.
This requires to install the adafruit-board-toolkit module.
pip3 install adafruit-board-toolkit
"""
import adafruit_board_toolkit.circuitpython_serial
ports = (
adafruit_board_toolkit.circuitpython_serial.repl_comports()
+adafruit_board_toolkit.circuitpython... |
from django.shortcuts import render, redirect, render_to_response, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from .models import *
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import revers... |
import numpy as np
from controller import Dumbbell
from kinematics import attitude
angle = (2*np.pi- 0) * np.random.rand(1) + 0
# generate a random initial state that is outside of the asteroid
pos = np.random.rand(3)+np.array([2,2,2])
R = attitude.rot1(angle).reshape(9)
vel = np.random.rand(3)
ang_vel = np.random.ra... |
"""Functions related to the main event handling."""
import traceback
from extutils.emailutils import MailSender
from msghandle import handle_message_main
from msghandle.models import (
Event, TextMessageEventObject, ImageMessageEventObject,
HandledMessageEventsHolder
)
from .logger import DISCORD
__all__ = (... |
from django.shortcuts import render
from django.http import HttpResponse
from basic_app.models import AccessRecord, Topic, Webpage
# Create your views here.
def index(request):
webpages_list = AccessRecord.objects.order_by("date")
date_dict = {"access_records": webpages_list}
return render(request, "basic_app/ind... |
from __future__ import division, print_function
import copy
import fnmatch
import os
import subprocess
import wave
import struct
import hashlib
import h5py
from copy import deepcopy
from math import ceil
from numpy.fft import fftshift, ifftshift
import numpy as np
from scipy.io.wavfile import read as read_wavfile
fro... |
from django.db import models
from cached_fields.fields import CachedIntegerField
from cached_fields.mixins import CachedFieldsMixin
from reverseapp.handlers import InvoiceSignalHandler
class Item(models.Model):
name = models.CharField(max_length=12)
price = models.IntegerField()
class Invoice(models.Model):
... |
import os
SITE_ID = 1
BASE_DIR = os.path.dirname(__file__)
ROOT_URLCONF = 'urls'
SECRET_KEY = 'secretkey'
SITE_ROOT = os.path.dirname(os.path.abspath(__file__))
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.con... |
#!/usr/bin/env python3
class Node(object):
"""Node class for binary tree"""
def __init__(self, data=None):
self.left = None
self.right = None
self.data = data
class Tree(object):
"""Tree class for binary search"""
def __init__(self, data=None):
self.root = Node(data)
... |
from abc import abstractmethod
import argparse
import copy
import numpy as np
import torch
from tqdm import tqdm
from cogdl.data import Dataset
from cogdl.data.sampler import (
SAINTSampler,
NeighborSampler,
ClusteredLoader,
)
from cogdl.models.supervised_model import SupervisedModel
from cogdl.trainers.b... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
prev = dummy = ListNode(-1, head)
cur = head
while cur:
... |
import pandas as pd
import numpy as np
import joblib
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import RandomizedSearchCV
from sklearn.metrics import mean_squared_error, r2_s... |
from setuptools import setup
import os
import re
if os.environ.get("CI_COMMIT_TAG"):
version = os.environ["CI_COMMIT_TAG"]
if version.startswith("v"):
version = version[1:]
if not re.search(r"^\d+\.\d+\.\d+$", version):
raise AttributeError(
"given CI_COMMIT_TAG {} ... |
from .lrs_layer import TimeAugmentation
from .rlrs_layer import RecurrentLRS
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
import keras
from keras import backend as K
from keras.layers import Dense, BatchNormalization, Reshape
def init_rlrs_model(input_shape, num_levels, num_h... |
#===============================================================================
# Copyright 2020-2021 Intel Corporation
#
# 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.apa... |
'''
Functions for performing Otsu's algorithm.
3 variations:
1. the standard way Otsu's algorithm on the whole image
2. segmenting the image into blocks, and performing Otsu's algorithm on each block
3. use sliding window on the image, and use Otsu's algorithm within the window
'''
import cv2
import numpy as np
def... |
from sklearn import metrics
from sklearn.metrics import roc_auc_score, roc_curve, auc
from matplotlib import pyplot as plt
import preprocess
import utils
class Evaluator:
def accuracy(self, Y_test, preds):
auc = metrics.accuracy_score(preds, Y_test)
print(f"Classification accuracy is {auc}")
... |
# -*- coding: utf-8 -*-
from benedict.core import keypaths as _keypaths
import unittest
class keypaths_test_case(unittest.TestCase):
def test_keypaths(self):
i = {
'a': 1,
'b': {
'c': {
'x': 2,
'y': 3,
},
... |
#
# 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 ... |
# Generated by Django 3.0.4 on 2021-04-07 10:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blogs', '0003_auto_20210407_0913'),
]
operations = [
migrations.AlterModelOptions(
name='postcomment',
options={},
)... |
#mapdatain_5.py
#to read in ALL data
#TRYING TO FIGURE OUT WHERE PHONY FIGURES COMING FROM
"""
These 3 imports needed for the full program
# from classes import *
# from code import *
"""
import math
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
import random
import time
# import data
impo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from irekua_database.models import MimeType
from irekua_rest_api.serializers.base import IrekuaModelSerializer
from irekua_rest_api.serializers.base import IrekuaHyperlinkedModelSerializer
class SelectSerializer(IrekuaModelSerializer):
class Meta:
... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from MyDIPUtils.config import *
# check_ol1: circle[i] and circle[j] overlaps too much
# check_ol2: circle[i] lies too much outside original image
# check_ol3: compare the overlapping area between different stepsize
def direction_map(edge, clockwise):
... |
from binary_array_to_number import binary_array_to_number
import unittest
class Test(unittest.TestCase):
def test_1(self):
result = binary_array_to_number([0, 0, 0, 1])
self.assertEqual(result, 1)
def test_2(self):
result = binary_array_to_number([0, 0, 1, 0])
self.assertEqual... |
from requests import get, post
from subprocess import check_output
from json import dumps
def acessar_dontpad(link_dontpad):
dontpad = get(link_dontpad).text
text = dontpad[dontpad.find('<textarea id="text">' ) + len('<textarea id="text">') : dontpad.find('</textarea>') ]
return text
def listar_processos... |
import numpy as np
import matplotlib.pyplot as plt
curve_F3 = np.loadtxt('./result/CUM_NN_F3_L100_50000.txt', delimiter = ',', dtype = float)
curve_F9 = np.loadtxt('./result/CUM_NN_F9_L100_50000.txt', delimiter = ',', dtype = float)
curve_TC = np.loadtxt('./result/cum_based_all_L100.txt', delimiter = ',', dtype = flo... |
# MINLP written by GAMS Convert at 04/21/18 13:55:18
#
# Equation counts
# Total E G L N X C B
# 1853 1105 307 441 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... |
import os, sys, getopt
import itertools as it
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/src")
from pandocLatex import *
##################
### Formatting ###
##################
# Some global parameters
latexEngine="lualatex"
highlightstyle='"tango"' #pygments, kate, monochrome, espresso, zenburn... |
#!/usr/bin/python
import sys
for line in sys.stdin:
sys.stdout.write(line)
# use like this: ps -ef | ./pipe-in.py
|
#from django.shortcuts import render
from itertools import product
from lzma import FORMAT_ALONE
from random import random
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.views import APIView
#from rest_framework.status import HTTP_200_OK
from .serializers im... |
from locust import HttpLocust, TaskSet, task
import os
import json
class ActionHubTaskSet(TaskSet):
@task
def get_something(self):
uri = "/actions/debug/execute"
data = {
"type": "query",
"form_params": {
"sleep": 0,
"simulated_download_url"... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 4 05:59:46 2020
@author: yoelr
"""
__all__ = ('H2O_CAS',)
H2O_CAS = '7732-18-5' |
from django.test import override_settings
from django.urls import reverse
from knox.auth import TokenAuthentication as KnoxTokenAuthentication
from rest_framework.test import APITestCase
from social_core.utils import parse_qs
from .base import BaseFacebookAPITestCase, BaseTwitterApiTestCase
knox_override_settings = ... |
from data_utils import load_tl_extracts, load_tl_extracts_hkkim
#import numpy as np
from tl_classifier_cnn import TLClassifierCNN, TLLabelConverter
# load data
desired_dim = (32,32)
#data_dirs = ['data/tl-extract-test']
data_dirs = 'data/tl-extract-test'
imgs, labels_gt = load_tl_extracts_hkkim(data_dirs, desired_dim)... |
import json
import datetime
import sys
import os
import random
from utils.node_rpc_wrapper import NodeRpcWrapper
from utils.telegram_wrapper import TelegramWrapper
from utils.discord_wrapper import DiscordWrapper
def check_and_send_reward_collection_message(telegram, discord, cfg, cached_epoch, new_epoch):
chann... |
from osu_parser.beatmap import Beatmap
from osu.ctb.difficulty import Difficulty
from ppCalc import calculate_pp
import os
import threading
import socket
import struct
import sys
import traceback
import time
CMD_KEEP_ALIVE = 0
CMD_KEEP_ALIVE_OK = 1
CMD_CALCULATE_CTB = 2
TIMEOUT = 3
def process_exist(imagename):
... |
from molinterrogator.target import _target_df
from molinterrogator.target import _compound_df
from molinterrogator.target import _compound_from_target_df
def _target_id_2_card_dict(db_id=None, client=None):
result = client.target.filter(target_chembl_id__in=db_id)[0]
tmp_dict = {}
tmp_dict['Na... |
import json
from urllib.parse import urlparse
from abstract_json_storage import AbstractJsonStorage
class JsonStorageStore(AbstractJsonStorage):
def __init__(self):
super().__init__()
def get_name(self):
return "jsonstorage.net"
def create(self, session, json_data=None, store_id=... |
import unittest
import sqlalchemy
from records_mover.db.redshift.sql import schema_sql_from_admin_views
from mock import patch, Mock
class TestSQL(unittest.TestCase):
@patch('records_mover.db.redshift.sql.logger')
def test_schema_sql_from_admin_views_not_installed(self,
... |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'PLUS MINUS TIMES DIVIDE LPAREN RPAREN SPACE COMMENT STARTP FINISHP ASSIGN LSQB RSQB SEMICOLON ELESS LESS EGREATER GREATER EQUAL NOTEQUAL DOT COMMA LOGIC_AND LOGIC_OR LOGIC_NOT IF THEN ELSE WHI... |
#!/usr/bin/env python
"""
Created on Apr 10, 2015
@author: Chen Yang
This script generates simulated Oxford Nanopore 2D reads.
"""
from __future__ import print_function
from __future__ import with_statement
import sys
import getopt
import random
import re
from time import strftime
try:
from six.moves import xr... |
import pygame
from spellingquiz.apilogin import *
import random
import time
import cv2
import sys
import datetime
from pygame.locals import *
import os
import json
import pathlib
pygame.init()
FPS = 30
FramePerSec = pygame.time.Clock()
cap0 = cv2.VideoCapture(0)
#cap1 = cv2.VideoCapture(1)
#create a
completedTests ... |
from bs4 import BeautifulSoup
from collections import namedtuple
import hashlib
class Provider(object):
def __init__(self, name, link):
self.name = name
self.link = link
def serialize(self):
return {'name': self.name, 'link': self.link}
def __str__(self):
return '<Provider... |
import json
import socket
import time
import os
import subprocess
dir_path = os.path.dirname(os.path.realpath(__file__))
def send_json(host, filename):
print(host, filename)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
with open(filename, 'r') as json_file:
data = json... |
# coding: utf-8
import unittest
import os
import sys
import requests_mock
from unittest import mock
sys.path.append("../yyetsbot")
from fansub import BaseFansub, YYeTsOnline
class TestBaseFunsub(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.ins = BaseFansub()
cls.cookie... |
import logging
import os
import sys
from collections import OrderedDict
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pyfmi
from mshoot import SimModel
class SimFMU(SimModel):
def __init__(self, fmupath, outputs=[], states=[], parameters={},
verbose=False):
... |
import os
def pwm_dir():
"""
Returns the directory of the expression dir
"""
return os.path.dirname(__file__)
|
# Program to perform breadth first traversal in a graph
from collections import defaultdict, deque
class Graph:
def __init__(self, directed=False):
self.graph = defaultdict(list)
self.directed = directed
def addEdge(self, frm, to):
self.graph[frm].append(to)
if self.directed ... |
"""
Kaan Altan - Resume.py
Author: Kaan Altan
Date: 2019-11-26
Description
===========
This script is a Python version of my resume featuring a command line interface
to interact with the information
History
=======
2019-11-25 Initial prototype of the script
Information is entered in the form of diction... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^mobile_captcha/$', views.get_mobile_captcha, name="mobile_captcha")
] |
"""ASCII table generator"""
class ASCIITableRenderer(object):
def render(self, table):
total_width = 0
for col in table.cols:
total_width += col.width
# Header
out = self._format_separator(total_width)
cols_widths = [col.width for col in table.cols]
out... |
from django import forms
from accounts.models import UserCred, AnnotatorProfile
from django_countries.data import COUNTRIES
from captcha.fields import CaptchaField
class PasswordResetRequestForm(forms.Form):
email_or_username = forms.CharField(label=("Enter registered email"), max_length=254)
class SetPasswordF... |
def add_letters(*letters):
return chr( (sum(ord(c)-96 for c in letters)-1)%26 + 97)
|
import os
from pymongo import MongoClient
from random import randint
from pprint import pprint
from models import Users, Roles
import testdata
#Step 2: Connect to MongoDB - Note: Change connection string as needed
client = MongoClient(
os.environ['DB_PORT_27017_TCP_ADDR'],
27017)
# Issue the serverStatus comm... |
# -*- coding: utf-8 -*-
import unittest
import time
from pprint import pprint
from flask.json import loads as json_load
from flask.json import dumps as json_dump
try:
from .test_resource_base import ActiniaResourceTestCaseBase, URL_PREFIX
except:
from test_resource_base import ActiniaResourceTestCaseBase, URL_... |
# -*- coding: utf-8 -*-
from odoo import api, fields, models, tools, _
class Company(models.Model):
_inherit = "res.company"
# material_agentid = fields.Char("Material Agent Id", default="0000000",)
# material_secret = fields.Char(
# "Material Secret", default="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.