text stringlengths 1 927k |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thus Jan 07 15:54:13 2021
@author: Filipe Souza
Based on Josh Varty (https://github.com/JoshVarty/AlphaZeroSimple)
"""
import numpy as np
from random import shuffle
import keras
from gym_go import gogame
from monte_carlo_tree_search import MCTS
class Trai... |
import random
import statistics
import time
def _generate_gene(length,geneset):
genes = []
while len(genes) < length:
sample = min(length - len(genes), len(geneset))
genes.extend(random.sample(geneset,sample))
return ''.join(genes)
def _mutate(parent,geneset):
childgene = list(parent)
index = random.randran... |
colors = {
"blue" : "#256EFF",
"violet" : "#46237A",
"green" : "#3DDC97",
"white" : "#FCFCFC",
"red" : "#FF495C",
"gray" : "#E8E8E8" #"#8D99AE"
} |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
# Copyright (C) 2019 Intel Corporation.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import os
import getopt
import re
import common
import board_cfg_lib
import scenario_cfg_lib
import lxml
import lxml.etree
ERR_LIST = {}
BOOT_TYPE = ['no', 'ovmf']
RTOS_TYPE = ['no', 'Soft RT', 'Hard RT']
DM_VUART0 = ['Disable', 'Ena... |
# -*- coding: utf-8 -*-
#
# AutoFolio documentation build configuration file, created by
# sphinx-quickstart on Mon Sep 14 12:36:21 2015.
#
# 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.
#
#... |
# =============================================================================
# Step1: Input
# =============================================================================
import numpy as np
from PyLMDI import PyLMDI
if __name__=='__main__':
#--- Step1: Input
Ct = 794.6119504871361 # Carbon emissio... |
"""ArcSight Plugin SSL Log Handler."""
import os
import codecs
import logging
import logging.handlers
import ssl
import socket
from tempfile import NamedTemporaryFile
class SSLArcSightHandler(logging.handlers.SysLogHandler):
"""SSL ArcSightHandler Class."""
# We need to paste all this in because __init__ co... |
from tkinter import filedialog, Tk
from os import getcwd
def epic_file_dialog(title: str) -> str:
root = Tk()
root.attributes('-topmost',True)
root.withdraw()
path = filedialog.askopenfilename(title=title, initialdir=getcwd())
return path |
from datetime import timedelta, datetime
# noinspection PyPackageRequirements
import airflow
# noinspection PyPackageRequirements
from airflow import DAG
# noinspection PyPackageRequirements
from airflow.operators.dummy_operator import DummyOperator
# noinspection PyPackageRequirements
from airflow.operators.python_op... |
import os
def removeComments(filename):
savedFile = filename.replace('.txt', 'Copy.txt')
os.rename(filename, savedFile)
with open(filename, 'w') as new_file:
with open(savedFile) as old_file:
for line in old_file:
if '#' not in line and line != '\n':
... |
import numpy as np
import torch
from torch.utils.data.dataset import TensorDataset
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.autograd import Variable
def my_softmax(input, axis=1):
trans_input = input.transpose(axis, 0).contiguous()
soft_max_1d = F.softmax(trans_input)... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError, Optional, URL
from flask_login import current_user
from app.mod... |
# shadow - De Mysteriis Dom jemalloc
import os
import sys
import argparse
import pickle
import comtypes
import comtypes.client
import symbol
# this has to be before the import that follows
msdia = comtypes.client.GetModule('msdia\\msdia90.dll')
from comtypes.gen.Dia2Lib import *
# https://msdn.microsoft.com/en-us/... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
"""
1. Clarification
2. Possible solutions
- In-Order Traversal
3. Coding
4. Tests
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# T=O(n), S=O(n)
class Solution:
... |
import logging
import os
import random
import click
import flask
from OpenSSL import crypto
from pegaflow.service import cache
from pegaflow.service._encoder import PegasusJsonEncoder
from pegaflow.service.base import BooleanConverter
from pegaflow.service.filters import register_jinja2_filters
from pegaflow.service.... |
class JacobianError(ArithmeticError):
def __init__(self,value=None):
self.value = value
def __str__(self):
if self.value is None:
self.value = 'Jacobian of mapping is close to zero'
return repr(self.value)
class IllConditionedError(ArithmeticError):
def __init__(self,v... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from account import views
urlpatterns = patterns(
'account.views',
url(r'^my-account/$', 'get_my_account'),
url(r'^password/$', 'change_passwd'),
url(r'^create-seed-user/$', 'create_seed_user'),
) |
"""
WSGI config for Finetooth project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.wsgi imp... |
from . import SOM
from . import classification
from . import visualizations
from . import metrics |
sports = ['baseball', 'golf', 'soccer', 'football']
print(sports)
# sorted() function does only make changes temporarily
print(sorted(sports))
print(sports)
print(sorted(sports, reverse=True))
print(sports)
grades = [88, 74, 95, 100, 92]
print(grades)
print(sorted(grades))
print(sorted(grades, reverse=True))
print(gr... |
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms import TextField
from wtforms.fields.html5 import EmailField
from wtforms import SubmitField
from wtforms import PasswordField
from wtforms.validators import DataRequired
from wtforms.validators import Length
from wtforms.validators import Ema... |
from unittest.mock import patch
import pytest
import great_expectations.exceptions as ge_exceptions
from great_expectations import DataContext
from great_expectations.checkpoint import SimpleCheckpointConfigurator
from great_expectations.checkpoint.checkpoint import (
Checkpoint,
CheckpointResult,
SimpleC... |
from threading import Lock
class FooBar:
def __init__(self, n):
self.n = n
self.lock1 = Lock()
self.lock2 = Lock()
self.lock2.acquire()
def foo(self, printFoo: "Callable[[], None]") -> None:
for _ in range(self.n):
self.lock1.acquire()
printFoo(... |
"""GraphDegeneracy.py
Compute the degeneracy of graphs, and degeneracy orderings of graphs.
D. Eppstein, July 2016.
"""
import unittest
from Graphs import isUndirected
from BucketQueue import BucketQueue
def degeneracySequence(G):
"""Generate pairs (vertex,number of later neighbors) in degeneracy order."""
... |
from __future__ import annotations
from spark_auto_mapper_fhir.fhir_types.uri import FhirUri
from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode
from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType
# This file is auto-generated by generate_classes so do not edi... |
from decimal import Decimal
from typing import Optional
# Validators
def validate_exchange(value: str) -> Optional[str]:
from hummingbot.client.settings import EXCHANGES
if value not in EXCHANGES:
return f"Invalid exchange, please choose value from {EXCHANGES}"
def validate_derivative(value: str) ->... |
import hashlib,time,sys
def hash(hashType,userHash,wordlist):
if hashType == "md5" or hashType == "MD5":
h = hashlib.md5
elif hashType == "sha1" or hashType == "SHA1":
h = hashlib.sha1
elif hashType == "sha224" or hashType == "SHA224":
h = hashlib.sha224
... |
from tasks.models import Task, TaskTaken
from issues.models import Issue
from django.conf import settings
from django.db.models import Q
from django.db import transaction
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.t... |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_with_email_successful(self):
"""Test creating a new user with an email is sucessful"""
email = "test@respposta.com"
password = "Test@123"
user = get_us... |
# -*- coding: utf-8 -*-
"""
chemdataextractor.scrape.clean
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tools for cleaning up XML/HTML by removing tags entirely or replacing with their contents.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import ... |
"""
Copyright (c) 2015-2020 Raj Patel(raj454raj@gmail.com), StopStalk
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
... |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from tasks.enums import TaskStatusEnum
from tasks.models import Task
from tasks.tests.factories import UserFactory, TaskFactory
class TaskViewSetTestCase(APITestCase):
@classmethod
def setUpTestData(... |
# Copyright 2017 The KaiJIN 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 applicable ... |
# test_bridges.py - unit tests for bridge-finding algorithms
#
# Copyright 2004-2019 NetworkX developers.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
"""Unit tests for bridge-finding algorithms."""
import networkx as nx
class TestBridges... |
# flake8: noqa
# There's no way to ignore "F401 '...' imported but unused" warnings in this
# module, but to preserve other warnings. So, don't check this module at all.
# Copyright 2020 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
# pylint: disable=C0111,R0902,R0913
# Smartsheet Python SDK.
#
# Copyright 2017 Smartsheet.com, 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/LICE... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayMarketingCashlessvoucherTemplateModifyModel import AlipayMarketingCashlessvoucherTemplateModifyModel
class Alipa... |
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from gameIdGenerator import createNewGameId
from models import Game, Player, Player_Answers, Question
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import dbManager
import logging
import gameManager
im... |
#!/usr/bin/env python3
"""Tetra-nucleotide counter"""
import sys
import os
from collections import defaultdict
args = sys.argv[1:]
if len(args) != 1:
print('Usage: {} DNA'.format(os.path.basename(sys.argv[0])))
sys.exit(1)
arg = args[0]
dna = ''
if os.path.isfile(arg):
dna = ''.join(open(arg).read().spl... |
import numpy as np
from .. import logger
from ..constants import *
from ..mobject.mobject import Mobject
from ..mobject.types.opengl_vectorized_mobject import (
OpenGLDashedVMobject,
OpenGLVGroup,
OpenGLVMobject,
)
from ..utils.color import *
from ..utils.deprecation import deprecated_params
from ..utils.i... |
import argparse
import logging
import os
import json
import pandas as pd
def get_logger(name):
logger = logging.getLogger(name)
log_format = '%(asctime)s %(levelname)s %(name)s: %(message)s'
logging.basicConfig(format=log_format, level=logging.INFO)
logger.setLevel(logging.INFO)
return logger
de... |
PYTHONPATH = '~/Documents/gym-extensions/'
import sys
sys.path.append(PYTHONPATH)
import numpy as np
from gym import utils
from gym.envs.mujoco import mujoco_env
import os.path as osp
from gym.envs.mujoco.reacher import ReacherEnv
try:
import mujoco_py
from mujoco_py.mjlib import mjlib
except ImportError as e:... |
#!/usr/bin/env python3
import unittest
import unittest.mock
import json
from clang_tidy_converter import CodeClimateFormatter, ClangMessage
class CodeClimateFormatterTest(unittest.TestCase):
def test_format(self):
child1 = ClangMessage('/some/file/path1.cpp', 8, 10, ClangMessage.Level.NOTE, 'Allocated her... |
import copy
from dataclasses import make_dataclass
from unittest import mock
from tests.fixtures.books import Books
from tests.fixtures.models import AttrsType
from tests.fixtures.models import ExtendedListType
from tests.fixtures.models import ExtendedType
from tests.fixtures.models import FixedType
from tests.fixtur... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import numpy
import scipy.stats
import itertools
import copy
import string
import os
from collections import Counter, defaultdict
from filter_data_methods import *
from igraph import *
from transCSSR import *
data_prefix = ''
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#
# The various test transducers. Xt i... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (c) 2014-2018, Lars Asplund lars.anders.asplund@gmail.com
"""
Create simulator instances
"""
import os
fr... |
from selenium.webdriver.support.wait import WebDriverWait
class MainPage:
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def open(self):
self.driver.get("http://localhost/litecart")
return self
@property
def choose_item_on_main... |
# github link: https://github.com/ds-praveenkumar/kaggle
# Author: ds-praveenkumar
# file: forcasting/build_model.py/
# Created by ds-praveenkumar at 13-06-2020 02 09
# feature:
import os
import psutil
from fbprophet import Prophet
from pathlib import Path
import pandas as pd
import numpy as np
import pickle
from src.... |
class NetworkGenerator(object):
def build_model(self, *args, **kwargs):
import tensorflow as tf
depth = kwargs.get('depth', 1)
input_shape = kwargs.get('input_shape', (2,))
width = kwargs.get('width', 8)
activation = kwargs.get('activation', 'relu')
model = tf.keras.... |
#!/usr/bin/env python
"""Tests for bwaWrapper.py"""
########################################################################
# File: test_bwaWrapper.py
# executable: test_bwaWrapper.py
#
# Author: Andrew Bailey
# History: Created 08/14/18
########################################################################
import... |
from fstop import Runner
if __name__ == '__main__':
with open("tests/test.fstop") as ft:
string = ft.read()
run = Runner()
print(run.execute(string)) |
def is_prime(n):
return all(n % i for i in range(2,n)) |
import csv
import json
import time
import re
import requests
from pprint import pprint
from bs4 import BeautifulSoup
clean = lambda x: x.lower().replace(' ','').replace('\n','')
def averages_100(avg_url):
r = requests.get(avg_url)
soup = BeautifulSoup(r.content, 'lxml')
avg={
'stats':[],
}
... |
#
# PySNMP MIB module VMWARE-NSX-MANAGER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VMWARE-NSX-MANAGER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:34:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
# coding: utf-8
from streaming_api import sample
# Replace keys with your own keys
APIKEYS = dict(
CONSUMER='consumer key',
CONSUMER_SECRET='consumer secret key',
ACCESS_TOKEN='access token key',
ACCESS_TOKEN_SECRET='access token secret key')
# NOTICE: this script shows delimited output in your termin... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2018, Exa Analytics Development Team
## Distributed under the terms of the Apache License 2.0
#"""
#Tests for the Atom DataFrame
##############################
#The tests here use some contrived examples.
#"""
#import numpy as np
#from unittest import TestCase
#from exa impo... |
# Copyright (c) 2011, Found IT A/S and Piped Project Contributors.
# See LICENSE for details.
from twisted.application import internet, service, strports
from twisted.conch import manhole, manhole_ssh, error as conch_error
from twisted.conch.insults import insults
from twisted.conch.ssh import keys
from twisted.cred im... |
from flask import Flask
from flask.ext.httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
app = Flask(__name__)
app.config.from_object('config')
from app import views
from app.api import v1_0 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2021/12/27 15:47
Desc: 中国公路物流运价、运量指数
http://index.0256.cn/expx.htm
"""
import pandas as pd
import requests
def index_cflp_price(symbol: str = "周指数") -> pd.DataFrame:
"""
中国公路物流运价指数
http://index.0256.cn/expx.htm
:param symbol: choice of {"周指数", "月指... |
# 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 or agreed to in writing, ... |
x = [0.0, 3.0, 5.0, 2.5, 3.7] #define array
print(type(x))
#remove third element
x.pop(2)
print(x) #will print without third element
#remove 2.5
x.remove(2.5)
print(x)
#add an element to the end
x.append(1.2)
print(x)
#copy
y = x.copy()
print(y)
#how many elements are 0.0
print (y.count(0.0))
#print the index wit... |
''' Various stretch functions. Easy to add more. Room for refinement,
methinks.
'''
import numpy as np
def stretch(x, method='linear', param=None, NR=0, background=None):
# if no noise reduction just use stretch alone
if (NR <= 0) or (background is None):
return stretch_main(x, method=method, par... |
from .archive import Archive
from .resource import Resource |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Application Insights SDK for Python documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 22 23:32:45 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration val... |
# Unix SMB/CIFS implementation.
# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) a... |
#!/usr/bin/env python3
"""
Author : abennett1 <abennett1@localhost>
Date : 2021-09-20
Purpose: Rock the Casbah
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Do Re Mi solfege',... |
# Shows the compass heading on your scroll:bit
# You will need to calibrate the compass by tilting the micro:bit
# when your program starts.
# Flash a blank file to your micro:bit,
# then save this as main.py and transfer it to your micro:bit using the Files menu
# you will also need to copy over scrollbit.py, see REA... |
'''
* Use rocksdb as cardano-sl did.
* Store each epoch in seperate db.
'b/' + hash -> block data
'u/' + hash -> undo data
g -> hash of genesis block of epoch.
* Main database:
* 'c/tip' -> hash
* 'b/' + hash -> BlockHeader
* 'e/fl/' + hash -> hash of next block.
* 'ut/t/' + txIn -> TxOut
* 's/' +... |
import numpy as np
class Mol():
r"""
Molecule.
"""
__g6_string = ''
# Adjacency matrix
__A = []
# Incidence matrix
__B = []
# Laplacian matrix
__L = []
# Normalized laplacian matrix
__NL = []
# Signless laplacian matrix
__Q = []
# Distance matrix
__D = [... |
import pytest
from data.map import Map
from data import constants
def test_set_get_map():
map = Map()
map.set_map(
[
[(0, 0), constants.DEFAULT_WALL, 0],
[(0, 1), constants.DEFAULT_WALL, 90],
[(0, 2), constants.DEFAULT_WALL, 180]
]
)
assert map.... |
# Copyright 2015, 2016 OpenMarket Ltd
# Copyright 2017 Vector Creations Ltd
# Copyright 2018 New Vector Ltd
#
# 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/licen... |
"""
Official page for Nigeria COVID figures:
https://covid19.ncdc.gov.ng/
"""
import logging
import os
import re
from bs4 import BeautifulSoup
import requests
from .country_scraper import CountryScraper
logger = logging.getLogger(__name__)
class Nga(CountryScraper):
def fetch(self):
url = 'https... |
from django.apps import AppConfig
class ShortenerConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "manti_by.apps.shortener" |
from .mobilenet import StridedInflatedMobileNetV2
from .efficientnet import StridedInflatedEfficientNet |
from .base import *
DEBUG = get_env_variable('DEBUG_MODE')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': get_env_variable('DATABASE_NAME'),
'USER': get_env_variable('DATABASE_USER'),
'PASSWORD': get_env_variable('DATABASE_PASSWORD'),
... |
import json
from loader.KITTI15Mask import KITTI15Mask
from loader.SceneflowMask import SceneflowMask
from loader.DrivingStereoMask import DrivingStereoMask
from loader.MiddleburyMask import MiddleburyMask
def get_loader(name):
"""get_loader
:param name:
"""
print(name.lower())
return {
'... |
# Generated by Django 2.2 on 2021-03-23 12:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
... |
BAD_CHARS = [
u"\u202a",
u"\u200e",
u"\u202c",
u"\xa0",
]
IS_STARTING_LINE = r"""
(\[?) #Zero or one open square bracket '['
(((\d{1,2}) #1 to 2 digit date
(/|-) #'/' or '-' separator
(\d{1,2}) #1 to 2 digit month
(/|-) #'/' or '-' separator
(\d{2,4})) #2... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from sentry_sdk._types import MYPY
if MYPY:
import sentry_sdk
from typing import Optional
from typing import Callable
from typing import Union
from typing import List
from typing import Type
from typing import Dict
from typing import Any
from typing import Sequence
from typing_... |
from rest_framework import serializers
from ..models import *
class UserSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
kwargs["partial"] = True
super(UserSerializer, self).__init__(*args, **kwargs)
class Meta:
model = User
# fields = "__all__"
... |
"""
This module holds functionality that connects the models to the views
"""
from flask import session
from app.models import db
from app import utilities
def process_form_data(dict_form_data, *args):
"""
After casting form data to dict, the values
become lists. Transform the lists to non-iterables
... |
# -*- coding: utf-8 -*-
# Create a geo (gmsh input file) file from a contour file
# the contour file contains the (x,y) coordinates of the ordered
# points defining the contour of the domain
#
import numpy as np
import matplotlib.pyplot as plt
# Test these options
# edge size of the elements
el_size = 18.0
... |
from typing import FrozenSet, Tuple
import pysmt.typing as types
from pysmt.environment import Environment as PysmtEnv
from pysmt.fnode import FNode
from utils import symb_to_next
from hint import Hint, Location
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
... |
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
from lists.models import List
class Person(models.Model):
user = models.OneToOneField(User)
bio = models.TextField()
dob = models.DateField()
lo... |
#!/usr/bin/env python
# -- coding: utf-8 --
"""
Copyright (c) 2019. All rights reserved.
Created by C. L. Wang on 2020/1/2
"""
import math
from UGATIT import UGATIT
from main import parse_args
from root_dir import DATA_DIR
from utils.project_utils import traverse_dir_files, mkdir_if_not_exist
from utils.ugatit_utils im... |
from django.db.models import fields
from rest_framework import serializers
from decimal import Decimal
from .models import Cart, CartItem, Product, Collection, Customer, Order, OrderItem, Review
from uuid import uuid4
class ReviewSerializer(serializers.ModelSerializer):
class Meta:
model = Review
... |
from datetime import datetime
from flask import render_template, flash, redirect, url_for, request
from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.urls import url_parse
from app import app, db
from app.forms import LoginForm, RegistrationForm, EditProfileForm, \
EmptyForm... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from floodsystem.stationdata import build_station_list
from floodsystem.geo import rivers_with_station
from floodsystem.geo import stations_by_river
def run():
stations = build_station_list()
riversWithStation = rivers_with_station(stations)
print(len(riversWithStation), "stations. First 10 -", sorted(riv... |
# Copyright 2017-2018 Amazon.com, Inc. and its affiliates. All Rights Reserved.
#
# Licensed under the MIT License. See the LICENSE accompanying this file
# for the specific language governing permissions and limitations under
# the License.
import mount_efs
import pytest
from botocore.exceptions import ClientError, E... |
from django.conf.urls.defaults import patterns, url
from django.test import TestCase
from django.test.client import RequestFactory
from rest_framework import generics, status, serializers
from rest_framework.tests.models import Anchor, BasicModel, ManyToManyModel, BlogPost, BlogPostComment, Album, Photo
factory = Requ... |
#!/usr/bin/env python
"""
.. py:currentmodule:: FileFormat.Results.test_Dump
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Tests for module `Dump`
"""
# Script information for the file.
__author__ = "Hendrix Demers (hendrix.demers@mail.mcgill.ca)"
__version__ = ""
__date__ = ""
__copyright__ = "Cop... |
import webbrowser
import wx
from eplaunch import DOCS_URL, VERSION
# wx callbacks need an event argument even though we usually don't use it, so the next line disables that check
# noinspection PyUnusedLocal
class WelcomeDialog(wx.Dialog):
CLOSE_SIGNAL_OK = 0
def __init__(self, *args, **kwargs):
su... |
#!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open('README.md') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = ['httpx', ]
setup_requirements = ['pytest-runner', ]
test_req... |
from aws_cdk import (
aws_lambda as lambda_,
aws_sqs as sqs,
aws_dynamodb as ddb,
aws_ec2 as ec2,
aws_kinesis as kinesis,
aws_ssm as ssm,
core
)
from aws_cdk.aws_dynamodb import StreamViewType
from aws_cdk.aws_ec2 import SubnetSelection, SubnetType
from aws_cdk.aws_iam import PolicyStatement... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.