filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_7453 | from application import app, db
from flask import redirect, render_template, request, url_for
from application.visits.models import Visit
from application.yhteenveto.forms import InYearForm, InMonthForm
from flask_login.utils import login_required, current_user
from application.sivu.models import Sivu
from sqlalchemy.s... |
the-stack_0_7456 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="keras-grid-search-cacheable",
version="1.0.0",
author="Daniel Espinosa",
author_email="daespinosag@unal.edu.co",
description="Reducción de tiempo de ejecución de los algo... |
the-stack_0_7457 | # $Id: __init__.py 7661 2013-05-07 10:52:59Z milde $
# Author: David Goodger
# Maintainer: docutils-develop@lists.sourceforge.net
# Copyright: This module has been placed in the public domain.
"""
Simple HyperText Markup Language document tree Writer.
The output conforms to the XHTML version 1.0 Transitional DTD
(*al... |
the-stack_0_7458 |
import os
from celery import Celery
from django.apps import apps, AppConfig
from django.conf import settings
if not settings.configured:
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover
app = Cele... |
the-stack_0_7459 | from __future__ import unicode_literals
import importlib
import json
import logging
import random
import re
import string
import urlparse
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
import urllib3
logger = logging.getLogger(__name_... |
the-stack_0_7460 | from arm.logicnode.arm_nodes import *
class ExpressionNode(ArmLogicTreeNode):
"""Evaluate a Haxe expression and get its output.
@output Result: the result of the expression."""
bl_idname = 'LNExpressionNode'
bl_label = 'Expression'
arm_version = 1
property0: StringProperty(name='', default=''... |
the-stack_0_7462 | import sys
from sys import argv
from subprocess import call
import threading
import webbrowser
import os
from shutil import copy, move, rmtree
from os.path import join, dirname, realpath, exists
from glob import glob
import re
from setuptools import setup, find_packages, Command
directory = dirname(realpath(__file__)... |
the-stack_0_7463 | import re
import sys
from django import VERSION
from django.conf import settings as django_settings
from django.contrib import admin
from django.db import connection
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views import debug
from celery import current_app... |
the-stack_0_7464 | # ------------------------------------------------------------------------
# Copyright 2015 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.apache.org/li... |
the-stack_0_7466 | # Copyright The OpenTelemetry 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 applicable law or agreed to in ... |
the-stack_0_7467 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import copy
import json
import os
from parlai.core.message import Message
from parlai.core.opt import Opt
from parlai.c... |
the-stack_0_7468 | # Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/
# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http... |
the-stack_0_7470 | """
==========================================
Using cloudknot to run pyAFQ on AWS batch:
==========================================
One of the purposes of ``pyAFQ`` is to analyze large-scale openly-available datasets,
such as those in the `Human Connectome Project <https://www.humanconnectome.org/>`_.
To analyze the... |
the-stack_0_7473 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 19-4-24 下午6:42
# @Author : MaybeShewill-CV
# @Site : https://github.com/MaybeShewill-CV/lanenet-lane-detection
# @File : vgg16_based_fcn.py
# @IDE: PyCharm
"""
Implement VGG16 based fcn net for semantic segmentation
"""
import collections
import tensor... |
the-stack_0_7474 | import chainer
import chainer.functions as F
import chainer.links as L
class SEBlock(chainer.Chain):
"""A squeeze-and-excitation block.
This block is part of squeeze-and-excitation networks. Channel-wise
multiplication weights are inferred from and applied to input feature map.
Please refer to `the ... |
the-stack_0_7476 | from __future__ import print_function
import os.path, json, requests, logging, datetime, argparse, sys
from requests.packages.urllib3.exceptions import InsecureRequestWarning
#suppres warning for certificate
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
#API headers and url
HEADERS = {'co... |
the-stack_0_7478 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Copyright (c) Flo Developers 2013-2018
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mempool limiting together/eviction with the wallet."""
f... |
the-stack_0_7480 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
"""Multi-class Focal loss implementation.
Args:
gamma (float): The larger the gamma, the smaller
the loss weight of easier samples.
weight... |
the-stack_0_7481 | from __future__ import print_function
import pandas as pd
import numpy as np
import sys
from os import listdir, getcwd
from os.path import isdir, join, dirname, abspath
from pandas import concat
from nilmtk.utils import get_module_directory, check_directory_exists
from nilmtk.datastore import Key
from nilmtk.measuremen... |
the-stack_0_7484 | import re
class StringCal:
def __init__(self, formula:str, **variables):
self.formula = formula.replace(' ', '')
self.variables = variables
def get_coefficient(self) -> dict:
coefficients = {}
term = ""
for f in self.formula + ';':
variable_term = re.compil... |
the-stack_0_7488 | # Copyright (c) 2018, Neil Booth
#
# All rights reserved.
#
# The MIT License (MIT)
#
# 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 r... |
the-stack_0_7489 | """StorageTableSeeder Seeder."""
from masoniteorm.seeds import Seeder
from app.Storage import Storage
class StorageTableSeeder(Seeder):
def run(self):
"""Run the database seeds."""
Storage.create({
"storage_name": "blank",
"storage_brand": "blank",
"storage_type... |
the-stack_0_7490 | import re
from .helpers import fuzzy
class ProcessSpeech:
def __init__(self, pa, localize, command, default_cast):
self.pa = pa
self.command = command
self.localize = localize
self.device = default_cast
self.tv_keys = localize["shows"] + localize["season"]["keywords"] + lo... |
the-stack_0_7491 | import math
import time
import torch
import numpy as np
import pandas as pd
from torch import nn
import editdistance as ed
import soundfile as sf
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
#PRESERVE_INDICES = len(['<pad>', '<space>'])
PRESERVE_INDICES = len(['<pad>', '<space>', '<eos>'])
... |
the-stack_0_7492 | """
@author: hugonnet
compile the differences to IceBridge and ICESat into elevation biases, standardized uncertainties, and elevation change biases for all regions and parameters of interest
"""
import os
import pandas as pd
import numpy as np
from pybob.ddem_tools import nmad
from glob import glob
import scipy.inter... |
the-stack_0_7494 | """
Default configurations for action recognition TA3N lightning
"""
import os
from yacs.config import CfgNode as CN
# -----------------------------------------------------------------------------
# Config definition
# -----------------------------------------------------------------------------
_C = CN()
_C.TO_VA... |
the-stack_0_7495 | # coding=utf-8
# Copyright 2022 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 ... |
the-stack_0_7501 | import coreapi
import maya
import logging
import pydash
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.shortcuts import get_object_or_404
from django.http import QueryDict
from django.db.models.functions import Concat
from django.db.models import TextField
from django.conf import ... |
the-stack_0_7502 | import json
import subprocess
import requests
from shutil import copyfile
from distutils.dir_util import copy_tree
import urllib.request
import urllib
from urllib.parse import urlparse
import os
import sys
import argparse
import time
from socket import error as SocketError
from snakemake.io import expand
workflows=['... |
the-stack_0_7506 | """Utilities for real-time data augmentation on image data.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import re
from six.moves import range
import os
import threading
import warnings
import multiprocessing.pool
from functools imp... |
the-stack_0_7507 | import os
import json
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
from tornado.web import url
from gensim.models.word2vec import Word2Vec
import gensim
import re
import requests
class IndexHandler(tornado.web.RequestHandler):
"""Main handler."""
def get(self, *ar... |
the-stack_0_7508 | import os
import pprint
import pymongo
import datetime
import numpy as np
import configparser
from openbox.optimizer import _optimizers
from openbox.utils.start_smbo import create_smbo
from openbox.utils.config_space.space_utils import get_config_space_from_dict
# Read configuration from file.
conf_dir = './conf'
conf... |
the-stack_0_7510 | # -*- coding: utf-8 -*-
from furl import furl
from scrapy.spiders import CrawlSpider as BaseSpider, signals
from scrapy_splash import SplashRequest
from scrapy import Request
from gerapy.server.core.utils import str2list, str2dict, str2body
from scrapy.spiders.crawl import Rule as BaseRule
class Rule(BaseRule):
d... |
the-stack_0_7511 | import tensorflow as tf
init_val = tf.random_normal(shape=(1, 5), mean=0, stddev=1)
# var = tf.Variable(init_val, name='var')
var = tf.get_variable(name='var', shape=(1, 5), initializer=tf.random_normal_initializer(mean=0, stddev=1))
with tf.variable_scope(name_or_scope='', reuse=True):
"""tf.variable_scope 를 사용하면... |
the-stack_0_7512 | # -*- coding: utf-8 -*-
import sys
sys.path.append('.')
from decimal import *
print (sys.argv[1:])
_table = sys.argv[1]
parametro1 = _table.split('.')
_table = parametro1[0]
_prov = int(sys.argv[2])
_dpto = int(sys.argv[3])
_frac = int(sys.argv[4])
_radio = int(sys.argv[5])
#definición de funciones de ady... |
the-stack_0_7516 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2019-2020 by ShabaniPy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the MIT license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------... |
the-stack_0_7517 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
# import urllib
import urllib.request as req
import numpy as np
import tensorflow as tf
# Data sets
IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_... |
the-stack_0_7518 | # -*- coding: utf-8 -*-
# @Author: theo-l
# @Date: 2017-09-08 11:52:55
# @Last Modified by: theo-l
# @Last Modified time: 2017-09-12 15:53:48
import six
import warnings
from fabric.api import run, settings
DEBUG = True
class HostConfig:
def __init__(self, host_config=None, *args, **kwargs):
"""
... |
the-stack_0_7519 | # Copyright 2016 Johns Hopkins University (Dan Povey)
# 2016 Vijayaditya Peddinti
# Apache 2.0.
""" This module contains the parent class from which all layers are inherited
and some basic layer definitions.
"""
from __future__ import print_function
import math
import re
import sys
import libs.nnet3.x... |
the-stack_0_7520 | import logging
log = logging.getLogger(__name__)
from qcodes import VisaInstrument
import qcodes.utils.validators as vals
class DG645(VisaInstrument):
"""Qcodes driver for SRS DG645 digital delay generator.
"""
CHANNEL_MAPPING = {
'T0': 0, 'T1': 1, 'A': 2, 'B': 3, 'C': 4,
'D': 5, 'E': 6, '... |
the-stack_0_7522 | #!/usr/bin/env python3
"""Combine logs from multiple konjocoin nodes as well as the test_framework log.
This streams the combined log output to stdout. Use combine_logs.py > outputfile
to write to an outputfile.
If no argument is provided, the most recent test directory will be used."""
import argparse
from collecti... |
the-stack_0_7523 | # Copyright 2021 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... |
the-stack_0_7527 | #!/usr/bin/env python3
#
# 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 "L... |
the-stack_0_7528 | """
https://stackoverflow.com/questions/42394585/how-to-inspect-a-tensorflow-tfrecord-file
for example in tf.python_io.tf_record_iterator("data/foobar.tfrecord"):
result = tf.train.Example.FromString(example)
"""
import csv
import functools
import json
import multiprocessing.dummy
import os
import random
import n... |
the-stack_0_7531 | # Copyright (c) 2020 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 app... |
the-stack_0_7532 | from . import configurations
from .. import exit, Path, save_configuration, save_weights, load_weights, load_configuration, handle_init, npprod
from tensorflow import data as tfdata, optimizers as tfoptimizers, reshape as tfreshape
from third_party.tensorflow.building.handler import Layer_Handler
from third_party.t... |
the-stack_0_7533 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by Lucas Sinclair and Paul Rougieux.
JRC Biomass Project.
Unit D1 Bioeconomy.
"""
# Built-in modules #
import os
# Third party modules #
from tqdm import tqdm
import pandas
# First party modules #
from autopaths.auto_paths import AutoPaths
# Internal modu... |
the-stack_0_7534 | from lib.hosts import get_host_id
from lib.network import send_json
from train.client.config import get_model_type
from train.events import events
async def register_host_id(websocket):
"""
Sends a hostID registration event on the provided websocket.
"""
host_id = get_host_id()
await send_json(web... |
the-stack_0_7539 | from damster.utils import initialize_logger
import re
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
from pprint import pformat
log = initialize_logger(__name__)
def _sanitize_url(url):
u = urlparse(url)
return u.netloc.split(':')[0].replace('.', '_')
clas... |
the-stack_0_7541 | """Example of a highway section network with on/off ramps."""
from flow.envs.highway_ramps_env import HighwayRampsEnv
from flow.envs.multiagent import highway
from flow.controllers import car_following_models
from flow.controllers.car_following_models import IDMController, LACController
from flow.core.params import Su... |
the-stack_0_7544 | import os
from jobControl import jobControl
from pyspark.sql import SparkSession
from pyspark.sql import functions as f
from pyspark.sql.types import DecimalType, IntegerType
from utils import arg_utils, dataframe_utils, date_utils
job_args = arg_utils.get_job_args()
job_name = os.path.basename(__file__).split(".")[0... |
the-stack_0_7546 | """Module containing tools to calculate statistics of collective events.
Example:
>>> from arcos4py.tools import calcCollevStats
>>> test = calcCollevStats()
>>> out = test.calculate(data = data,frame_column = "frame", collid_column = "collid")
"""
from typing import Union
import numpy as np
i... |
the-stack_0_7548 | """Utilities for managing string types and encoding."""
import six
def force_unicode(string, encoding='utf-8'):
"""Force a given string to be a unicode type.
Args:
string (bytes or unicode):
The string to enforce.
Returns:
unicode:
The string as a unicode type.
... |
the-stack_0_7549 | import _plotly_utils.basevalidators
class SizeValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="size", parent_name="funnelarea.title.font", **kwargs
):
super(SizeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=pare... |
the-stack_0_7550 | import builtins
import dataclasses
from functools import partial
from typing import Any, Dict, List, Optional, Tuple, Type, cast
from pydantic import BaseModel
from pydantic.fields import ModelField
from strawberry.arguments import UNSET
from strawberry.experimental.pydantic.conversion import (
convert_pydantic_m... |
the-stack_0_7551 | import numpy as np
import matplotlib.pylab as plt
class AnimAcross:
'''
Helper class for making subplots,
useful if you're not quite sure how many
subplots you'll be needing
'''
def __init__(self,ratio=.8,sz=4,columns=None,aa=None,asp=1.0):
self.aa=aa
self.axes_list=[]
s... |
the-stack_0_7552 | """Module for the StreamRoles cog."""
# Copyright (c) 2017-2018 Tobotimus
#
# 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 ... |
the-stack_0_7553 | """
Pyinvoke tasks.py file for automating releases and admin stuff.
Author: Shyue Ping Ong
"""
from invoke import task
import glob
import os
import json
import webbrowser
import requests
import re
import subprocess
import datetime
from monty.os import cd
NEW_VER = datetime.datetime.today().strftime("%Y.%-m.%-d")
... |
the-stack_0_7555 | from keyphrase import KeyphraseModel
from keyphrase import ttypes
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import json
import os
import subprocess
import sys
def write_to_input_file(article_li... |
the-stack_0_7557 | #!/usr/bin/env python
# coding=utf-8
import os
import clara_bootstrap
from distutils.core import setup, Command
from setuptools.command.test import test as TestCommand
from setuptools import find_packages
class ClaraTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
... |
the-stack_0_7559 |
import pandas as pd
import h5py
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
print("Mod imported")
data_case_storage='C:/Users/Arthur/Google Drive/Projets/Autres/OliverWyman/Data/transaction_and_locations_resident.h5'
rev_moy_bord=2259
rev_moy_paris=3417
rev_moy_toul=2047
rev_... |
the-stack_0_7561 | # Copyright (c) 2020 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... |
the-stack_0_7564 | """
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 ... |
the-stack_0_7565 | #Image Glitch is a program that is designed to make glitch art. It glitches an image by
# sorting the blue value of pixels in each column.
# This program was designed as an introduction to Python for beginners, and is not
# meant to be efficient.
# Because it is inefficient, please use small filesizes with this algo... |
the-stack_0_7570 | # -*- coding: utf-8 -*-
# flake8: noqa
import os
import string
import random
import tempfile
import requests
import unittest
import pytest
from qiniu import Auth, set_default, etag, PersistentFop, build_op, op_save, Zone
from qiniu import put_data, put_file, put_stream
from qiniu import BucketManager, build_batch_cop... |
the-stack_0_7571 | import json
import sys
# Loads JSON config file
if len(sys.argv) != 2:
print("Provide single filename")
sys.exit()
else:
configFileName = sys.argv[1]
with open(configFileName, 'r') as json_file:
try:
global file
file = json.load(json_file)
except:
print("Unable to load JSON... |
the-stack_0_7572 | from datetime import datetime
import json
import pytz
from majestic.content import BlogObject
from majestic.utils import chunk, absolute_urls
class PostsCollection(BlogObject):
"""Base class for a collection of posts
This should be subclassed for objects that work on several posts,
such as for indexes ... |
the-stack_0_7576 | import logging
import os
import random
import warnings
from functools import wraps
from typing import Optional
import numpy as np
import torch
log = logging.getLogger(__name__)
def seed_everything(seed: Optional[int] = None, workers: bool = False, deterministic: bool = False) -> int:
"""
``
This part of... |
the-stack_0_7577 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Base class for RPC testing
import logging
import optparse
import os
import sys
import shutil
import te... |
the-stack_0_7578 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2018 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test accesibility of resource endpoints."""
from __future__ import unicode_literals
import json
from flask i... |
the-stack_0_7580 | from data_loader import *
import autosklearn.regression
import sklearn
import pickle
import matplotlib.pyplot as plt
import numpy as np
from train_config import train_indexes
def my_train_test_split(X,y,num_point=1,train_size=0.75,select_method='random',logfile=None):
num_point = len(X)
if select_method=='rand... |
the-stack_0_7583 | # 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 ... |
the-stack_0_7586 | import random
from fastapi import APIRouter, Path, Query
from ..dependencies import get_json
router = APIRouter()
quotes = get_json("quotes")
@router.get("/quotes/all")
async def all_quotes():
return {
"quotes": [
{"id": int(q_id), "quote": quotes[q_id][0], "author": quotes[q_id][1]}
... |
the-stack_0_7587 | #
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PRO... |
the-stack_0_7590 | from unittest import TestCase
from plenario.database import postgres_session, postgres_engine
import sqlalchemy as sa
from sqlalchemy import Table, Column, Integer, Date, Float, String, TIMESTAMP, MetaData, Text
from sqlalchemy.exc import NoSuchTableError
from geoalchemy2 import Geometry
from plenario.etl.point import ... |
the-stack_0_7592 | site = {
'html': {
'head': {
'title': 'Мой сайт'
},
'body': {
'h2': 'Здесь будет мой заголовок',
'div': 'Тут, наверное, какой-то блок',
'p': 'А вот здесь новый абзац'
}
}
}
def f(word,depth, data, i=1):
for is_key in data:
... |
the-stack_0_7593 | # pylint: disable=no-name-in-module
# pylint: disable=no-self-argument
import psycopg2
import json
from pydantic import BaseModel, ValidationError
conn = psycopg2.connect(database="digital_breakthrough", user="postgres",
password="4432", host="26.173.145.160", port="5434")
cursor = conn.cursor... |
the-stack_0_7594 | # Copyright Contributors to the OpenCue Project
#
# 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... |
the-stack_0_7595 | # qubit number=4
# total number=11
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(0) # number=1
pr... |
the-stack_0_7597 | from . import animal, pet
def main():
clifford = pet.create_pet('Clifford', 'Dog', 12)
print(('This dog is %d years old.' % clifford.get_age()))
print(clifford)
print((clifford.get_name()))
if __name__ == '__main__':
main()
|
the-stack_0_7599 | """Baseline train
- Author: Junghoon Kim
- Contact: placidus36@gmail.com
"""
import argparse
from datetime import datetime
import os
import yaml
from typing import Any, Dict, Tuple, Union
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.models
from pytz import timezone
from src.datal... |
the-stack_0_7600 | import codecs
import binascii
def xor(bytes, value):
result = []
for i in range(len(bytes)):
result.append(bytes[i] ^ value)
return bytearray(result)
# ascii a-z characters are 97-122, or 0x61-0x7a
# capitals, spaces
# if many characters outside that range, consider it garbage
def englishness(byte... |
the-stack_0_7604 | import re
import math
from ..exception import PygpException
from .vertex import Vertex
from .halfedge import Halfedge
from .face import Face
from .objmesh import ObjMesh
class TriMesh(object):
def __init__(self, filename=''):
self.vertices = []
self.halfedges = []
self.faces =... |
the-stack_0_7605 | # From https://github.com/yunjey/stargan-v2-demo/tree/master/core
import torch
import torch.nn as nn
class MappingNetwork(nn.Module):
"""Mapping network: (latent z, domain y) -> (style s)."""
def __init__(self, latent_dim=64, style_dim=64, num_domains=2):
super(MappingNetwork, self).__init__()
... |
the-stack_0_7606 | import numpy as np
np.random.seed(0)
class Initialization:
zeros_initialization = None
def _zeros_initialization(n_units: int, n_in: int):
W = np.zeros((n_units, n_in))
b = np.zeros((n_units, 1))
return W, b
def _weights_initialization(n_units, n_in):
# multiplying W by a small number makes th... |
the-stack_0_7607 | from cryptography.exceptions import InvalidSignature, InvalidKey
from django.core.handlers.wsgi import WSGIRequest
from django.http import JsonResponse
from pyattest.exceptions import PyAttestException, InvalidNonceException, InvalidCertificateChainException, \
InvalidKeyIdException, ExtensionNotFoundException
fro... |
the-stack_0_7608 | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# 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, publ... |
the-stack_0_7612 | from mie2c.e2c import Encoder, Decoder, Transition, LinearTransition, PWATransition
import torch
from torch import nn
def get_bounce_encoder(dim_in, dim_z):
channels_enc = [6, 32, 32, 16, 16]
ff_shape = [128, 128, 128]
conv_activation = torch.nn.ReLU()
ff_activation = torch.nn.ReLU()
n_channels... |
the-stack_0_7614 | import matplotlib.pyplot as plt
from celluloid import Camera
import sys
fig = plt.figure()
camera = Camera(fig)
infile = sys.argv[1]
with open(infile, "r") as f:
for line in f.readlines():
plt.plot([float(i.strip()) for i in line.strip()[1:-1].split(",")], c="b")
camera.snap()
animation = camera... |
the-stack_0_7617 | # Copyright 2020 The TensorFlow Probability 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 applicable law o... |
the-stack_0_7619 | #
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# co... |
the-stack_0_7622 | from __future__ import print_function, unicode_literals, absolute_import, division
import numpy as np
import warnings
import os
import datetime
from tqdm import tqdm
from zipfile import ZipFile, ZIP_DEFLATED
from scipy.ndimage.morphology import distance_transform_edt, binary_fill_holes
from scipy.ndimage.measurements ... |
the-stack_0_7624 | import pytest
from tools import utils, constants
from launchers.sandbox import Sandbox
from . import protocol
NUM_NODES = 3
@pytest.mark.multinode
@pytest.mark.incremental
class TestDoubleEndorsement:
"""Constructs a double endorsement, and build evidence."""
def test_init(self, sandbox: Sandbox):
... |
the-stack_0_7626 | """
pycmark.utils.compat
~~~~~~~~~~~~~~~~~~~~
Utilities for compatibility.
:copyright: Copyright 2017-2019 by Takeshi KOMIYA
:license: Apache License 2.0, see LICENSE for details.
"""
from typing import Any, Generator
from docutils.nodes import Node
if not hasattr(Node, 'findall'): # for docut... |
the-stack_0_7630 | import math
import timeit
import numpy as np
import random
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
class GA():
def __init__(self, selectionPressure, mutationProbability, chromosomeCount, selectionProbability, problem):
self.selPs = selectionPressure # selection p... |
the-stack_0_7631 | from twilio.rest import Client
import json
class MessageClient:
def __init__(self):
print('Initializing messaging client')
with open('twiliocredentials.json') as creds:
twiliocred = json.loads(creds.read())
twilio_number = int(twiliocred.get('trial_number'))
twi... |
the-stack_0_7632 | import os
for fname in os.listdir('.'):
spl = fname.split('.')
if len(spl) <= 1:
continue
ext = spl[-1]
if ext != 'arc':
continue
print("[Python] Fixing ARC File ", fname)
# ARCTool produces a 0x11 but a 0x07 is expected by the collection
with open(fname, 'r+b') as file:
... |
the-stack_0_7634 | ######################################################################
#
# Copyright (C) 2013
# Associated Universities, Inc. Washington DC, USA,
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Library General Public License as published by
# the Free Software Fo... |
the-stack_0_7635 | #! python3
import SimpleITK as sitk
import numpy as np
def ApplyBiasCorrection(inputImage, shrinkFactor = (1,1,1)):
# Bias correction filter:
biasFieldCorrFilter = sitk.N4BiasFieldCorrectionImageFilter()
mask = sitk.OtsuThreshold( inputImage, 0, 1, 100)
inputImage = sitk.Cast(inputImage, sitk.sitkFloat... |
the-stack_0_7639 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020 Scriptim (https://github.com/Scriptim)
#
# 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 l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.