text stringlengths 957 885k |
|---|
#!/usr/bin/env python
# vim:set ts=8 sw=4 sts=4 et:
# Copyright (c) 2007-2013 <NAME>
#
# 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... |
<reponame>scottwedge/OpenStack-Stein<gh_stars>0
# 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 a... |
import codecs
import csv
import json
import os
import re
import sys
import tarfile
from itertools import islice
from biorun import convert
from biorun import utils
from biorun.libs import placlib as plac
from biorun.libs.sqlitedict import SqliteDict
JSON_DB_NAME = "taxdb.json"
SQLITE_DB_NAME = "taxdb.sqlite"
TAXDB_U... |
<filename>PuzzleGame/env/Lib/site-packages/bangtal/game.py
from ctypes import *
from bangtal.singleton import *
import enum
class EventID(enum.Enum):
ENTER_SCENE = 1
LEAVE_SCENE = 2
PICK_OBJECT = 3
DROP_OBJECT = 4
COMBINE_OBJECT = 5
DISMANTLE_OBJECT = 6
TIMER... |
<reponame>sarnold/chiptools<filename>chiptools/wrappers/synthesisers/ise.py
import os
import logging
import datetime
import shutil
import traceback
import re
import shlex
from chiptools.common.filetypes import FileType
from chiptools.common import exceptions
from chiptools.common.exceptions import FileNotFoundError
fr... |
<reponame>eax64/apacheconfig
#
# This file is part of apacheconfig software.
#
# Copyright (c) 2018, <NAME> <<EMAIL>>
# License: https://github.com/etingof/apacheconfig/LICENSE.rst
#
import os
import sys
from apacheconfig import *
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
... |
<reponame>ettoreferranti/walkingpad
#!/usr/bin/env python3
from bleak import BleakScanner, discover
from ph4_walkingpad.pad import Controller, WalkingPad
import logging
import asyncio
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class Treadmill:
address = None
co... |
<gh_stars>0
# coding=utf-8
from copy import copy
from mov_sdk.mov_api import MovApi
from bmc_sdk.log_service import log_service_manager
from util import *
# from config import strategy_config, account_config
class SDKImpl(object):
def __init__(self, _guid, _private_key):
self.guid = _guid
self.... |
<reponame>dyf-2316/Comment_Sentiment_Analysis
# -*- coding:utf-8 -*-
# @Time: 2020/7/11 10:31 PM
# @Author: dyf-2316
# @FileName: getData.py
# @Software: PyCharm
# @Project: Comment_Sentiment_Analysis
# @Description: get data from html/json
import re
from Logger import Logger
from config import *
from WebCrawler.getPa... |
<filename>tests/color_system_test.py
# -*- coding: utf-8 -*-
import json
import requests
import unittest
from pycolorname.color_system import ColorSystem
from pycolorname.utilities import make_temp
class ColorSystemTest(unittest.TestCase):
def setUp(self):
self.uut = ColorSystem()
def test_dict(se... |
# Copyright 2012,2013 <NAME>
# Copyright 2012,2013 <NAME>
#
# 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... |
<gh_stars>10-100
# Copyright (C) 2015 Catalyst IT 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/licenses/LICENSE-2.0
#
# Unless required by... |
# Create your views here.
from django.db import transaction
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django.utils.translation import gettext as _
from openbook_circles.serializers ... |
<filename>src/rival_regions_wrapper/api.py
"""
Rival Regions API methods
"""
import time
from rival_regions_wrapper import LOGGER
from rival_regions_wrapper.cookie_handler import CookieHandler
from rival_regions_wrapper.exceptions import (
SessionExpireException,
NoLogginException,
)
def session_handler(fun... |
<filename>tumor_migration_analysis/piv_analyze_vectors.py
#!/opt/local/bin/python
"""
This script reads PIV vector data for different experiments and for each time point,
analyzes the correlation length, mean flow and speed (root mean squared velocity).
The script plots the correlation Cvv over distance delta_r and... |
<gh_stars>0
import csv
import cv2
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers
from tensorflow.keras import models
from tensorflow.keras import Sequential
def datasetGen():
with open('... |
#!/usr/bin/env python3
from __future__ import print_function
import sys, re
import os
import glob
import hashlib
def bytehex(x):
return ''.join('{:02x}'.format(x) for x in x)
def wc_for_iteration(todo_dir, fni):
with open("%s/%u_all.txt" % (todo_dir, fni), "rb") as f:
return sum(1 for _ in f)
def... |
#!/usr/bin/env python
import functools
import urwid
import pyperclip
from components import StyledButton, OkDialog, OkCancelDialog, Dialog
from crypto.ninja import EncryptedImageNinja
from crypto.vault import ImageVault, Password
def close_app(*args):
raise urwid.ExitMainLoop()
palette = [
('banner', 'dar... |
<filename>prologGeneral.py<gh_stars>1-10
import re
import subprocess
from util import SilentLimitedBuffer
testfileName = '/tmp/tmp-testfile.pl'
plTestfile = re.compile(testfileName.replace(".", "\\.") + r"(:[0-9]*)?:?")
plStatus = re.compile(r"^[A.!+-]+$")
plResult = re.compile(r"^(ERROR|Warning): (.*)")
plDone = re.... |
from __future__ import absolute_import
import numpy as np
import os
import pytest
from mirdata import medleydb_pitch, utils
from tests.test_utils import mock_validated, mock_validator, DEFAULT_DATA_HOME
def test_track():
# test data home None
track_default = medleydb_pitch.Track('AClassicEducation_NightOwl... |
#coding=utf-8
''' '''
'''
XPath 是一门语言
XPath可以在XML文档中查找信息
XPath支持HTML
XPath通过元素和属性进行导航
XPath可以用来提取信息
XPath比正则表达式厉害
XPath比正则表达式简单
'''
'''
安装lxml库
from lxml import etree
Selector = etree.HTML(网页源代码)
Selector.xpath(一段神奇的符号)
'''
'''
树状结构
逐层展开
逐层定位
寻找独立节点
手动分析法
Chrome生成法
'''
'''
语法:
//定位根节点
/往下层寻找
提取文本内容:/text()
提取属性内容... |
import gzip
import importlib
import logging
import uuid
import zlib
import six
from six.moves import urllib
from . import packet
from . import payload
from . import socket
class Server(object):
"""An Engine.IO server.
This class implements a fully compliant Engine.IO web server with support
for websock... |
<reponame>ashwinahuja/HowQuicklyCanWeGetBackToThePub
import numpy as np
from .. import config, utils
from ..case import CaseFactors
from . import registry
from .common import _limit_contact, RETURN_KEYS
@registry("delve")
def delve(case, contacts, rng, **kwds):
strategy_factors = utils.get_sub_dictionary(kwds, c... |
#!/usr/local/bin/python
from argparse import ArgumentParser
from datetime import datetime
from os import chdir, getcwd, mkdir, system
from shutil import rmtree
from sys import exit
from time import time
from ftplib import FTP
arg = ArgumentParser()
#arg.add_argument('-s', help="Start Date")
#arg.add_argument('-e', h... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014 <NAME> <thiebaud at weksteen dot fr>
#
# 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 2 of the License, o... |
# 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... |
<reponame>NixGD/ergo<gh_stars>0
import math
import os
from types import SimpleNamespace
from typing import cast
from dotenv import load_dotenv
import jax.numpy as np
import pytest
import ergo
from ergo.distributions import Logistic, LogisticMixture, Truncate
from ergo.scale import LogScale, Scale, TimeScale
def thr... |
import sys
import json
import bson
import yaml
import os
import math
import numpy as np
from modelspec.base_types import print_
from modelspec.base_types import EvaluableExpression
verbose = False
def load_json(filename):
"""
Load a generic JSON file
"""
with open(filename) as f:
data = jso... |
<filename>mod/UJlib.py
import collections
import copy
import datetime
import math
import os
import pickle
import re
from collections import ChainMap
import pandas as pd
import json
import shutil
import progressbar
def get_dictlist_findidx(dictlist, fkey):
"""idx 를 찾아줌 이런형식 [{'11': 100},,,]"""
... |
# Copyright 2020 <NAME> (<EMAIL>)
# 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 writi... |
"""This module encapsulates methods for running time course simulations.
main method provided is the :func:`run_time_course` method, that will
simulate the given model (or the current :func:`.get_current_model`).
Examples:
To run a time course for the duration of 10 time units use
>>> run_time_course(10)
... |
<reponame>ever391/base-crawler<gh_stars>1-10
# coding:utf8
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from basecrawler import BaseCrawler, BeautifulSoup
import pymysql
from collections import OrderedDict
import re
import pymongo
class LianJia(BaseCrawler):
d... |
#!/usr/bin/env python3
import pysam
import numpy as np
import os
import sys
import logging
class ReconGene:
def __init__(self, tupleOfReadsA, tupleOfReadsB, fusion_idx_dir):
self.readsA = tupleOfReadsA
self.readsB = tupleOfReadsB
self.GeneAName = tupleOfReadsA[0].reference_name
sel... |
import datetime
from django.core.cache import cache
from django.test import TestCase, override_settings
from django.utils import timezone
from wagtail.core.models import Page, Site
from wagtail.tests.utils import WagtailTestUtils
from tests.app.models import NewsIndex, NewsItem
def dt(*args):
return datetime.da... |
<gh_stars>0
import traceback, logging
from datetime import datetime, timedelta, date
from decimal import Decimal
from dateutil.relativedelta import relativedelta
from django.urls import reverse
from django.test import TestCase, override_settings
from django.utils.timezone import localtime, now
from django.contrib.auth... |
<reponame>BCI-NET/FUCONE
"""
==============================================================
Cho2017 - Parameters optimization: Frequency band - FUCONE
===============================================================
This module is design to select the frequency bands that enhance the accuracy
"""
# Authors: <NAME> <<EM... |
<reponame>sungcheolkim78/py_imlib
"""
fmin (scipy.optimize 1.3.1) sckim version for numba optimization
"""
import numpy as np
from numba import njit
# standard status messages of optimizers
_status_message = {'success': 'Optimization terminated successfully.',
'maxfev': 'Maximum number of function ... |
<gh_stars>0
#!/usr/bin/env python
#coding: utf-8
from riak_common import *
import riak
import time
import redis
from riak.datatypes import Set
from time import sleep
def test_set_dt_empty():
(riak_client, _, nutcracker, redis) = getconn()
key = distinct_key()
nc_key = nutcracker_sets_key(key)
riak_set... |
# -*- coding: utf-8 -*-
#================================================================
# Don't go gently into that good night.
#
# author: klaus
# description:
#
#================================================================
import time
from tqdm import tqdm
import torch
from torch.utils.data.distributed im... |
<gh_stars>1-10
import glob
import os
import sys
import uuid
import arcpy
def create_wksp(path, gdb):
"""Create a .gdb workspace in given path
"""
wksp = os.path.join(path, gdb)
# create the workspace if it doesn't exist
if not arcpy.Exists(wksp):
arcpy.CreateFileGDB_management(path, gdb)
... |
'''in_use_do_not_archive
constants.py module used with the CCA3
contains constants, many used in gdata.py, ndata.py, hdata.py
no classes at this time in this module
requirements.txt:
provided simply here as a roadmap to the modules in the CCA3
please check with cca4.py to make sure latest requirem... |
<filename>terragrunt_action.py<gh_stars>0
#!/usr/bin/env python3
import argparse
import json
import os
import re
import subprocess
import sys
from pathlib import Path
import git
GIT_WORKSPACE = "/github/workspace/"
TERRASCAN_PATH = "/usr/local/bin/terrascan"
def get_command_line_options(args):
options = []
... |
<gh_stars>1-10
import argparse
from os.path import join, isdir, exists
from glob import glob
import logging
from logging import FileHandler, StreamHandler
import yaml
import multiprocessing
from utils.file_io import make_dirs
import sys
logger = logging.getLogger(__name__)
import os
from os.path import join, basen... |
#!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatib... |
#!/usr/bin/python
import os.path
import posixpath
import pytest
from aspen.testing.harness import Harness
tablefile = os.path.join(os.path.dirname(__file__), 'dispatch_table_data.rst')
def find_cols(defline, header_char='='):
"""
return a sorted list of (start, end) indexes into defline that
are the begi... |
"""
Tests for Markov Autoregression models
Author: <NAME>
License: BSD-3
"""
from __future__ import division, absolute_import, print_function
from statsmodels.compat.testing import skip
import warnings
import os
import numpy as np
import pandas as pd
from statsmodels.tools import add_constant
from statsmodels.tsa.reg... |
import os
import rnnSMAP
# from rnnSMAP import runTrainLSTM
import numpy as np
import imp
imp.reload(rnnSMAP)
rnnSMAP.reload()
import matplotlib
#################################################
# noise affact on sigmaX (or sigmaMC)
doOpt = []
# doOpt.append('train')
doOpt.append('test')
doOpt.append('plotBox')
noise... |
<filename>external/vcm/vcm/derived_mapping.py
import numpy as np
from typing import Mapping, Hashable, Callable, Iterable, MutableMapping
import xarray as xr
import vcm
class DerivedMapping(Mapping):
"""A uniform mapping-like interface for both existing and derived variables.
Allows register and computi... |
## Advent of Code 2018: Day 12
## https://adventofcode.com/2018/day/12
## <NAME>
## Answers: [Part 1]: 3059, [Part 2]: 3650000001776
import re, time, math
def maskHash(pots):
hash = 0
exp = 4
for char in pots:
if char == '#':
hash += 2**exp
exp -= 1
return hash
def advance... |
"""
Python Implementation of the EDDN publisher:
https://github.com/EDSM-NET/EDDN/blob/master/examples/PHP/EDDN.php
"""
from datetime import datetime, timezone
import hashlib
import json
import random
import requests
class EDDN:
_gateways = (
'https://eddn.edcd.io:4430/upload/',
# 'http://eddn-g... |
#!/usr/bin/env python
from concurrent.futures import ThreadPoolExecutor
from optparse import OptionParser
import requests
from datetime import datetime
from datetime import timedelta
import json
import os
import sys
prog = os.path.basename(__file__)
parser = OptionParser(usage="Usage: %s <wv.json> <overrides_file>" %... |
<reponame>risilab/Autobahn<gh_stars>10-100
import bisect
import datetime
import dataclasses
import os
import random
import warnings
from typing import Dict, List, Optional, Sequence
import hydra.utils
import pytorch_lightning
import pytorch_lightning.callbacks
import torch
from torch.utils.tensorboard import SummaryW... |
# main imports
import numpy as np
import pandas as pd
import sys, os, argparse
# image processing
from PIL import Image
from ipfml import utils
from ipfml.processing import transform, segmentation
import matplotlib.pyplot as plt
# model imports
import joblib
from keras.models import load_model
# modules and config ... |
# -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Author: ryanss <<EMAIL>> (c) ... |
<gh_stars>0
import requests
import json
class ClubhouseAPI:
def __init__(self, user):
self.api_url = 'https://www.clubhouseapi.com/api'
self.user = user
def me(self):
return requests.post('{}/me'.format(self.api_url), headers=self.user.headers, cookies=self.user.cookies)
def get... |
<filename>colors/__init__.py
"""
HOW TO USE:
In a string, put the color you want first, with the first item and the second item at the emd. (Example: _str = f"{green[0]}Green!{green[1]}"
"""
reset = [str(u"\u001b[0m"), str(u"\u001b[0m")]
bold = [str(u"\u001b[1m"), str(u"\u001b[22m")]
dim = [str(u"\u001b[2m"... |
<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright (C) 2013, the Pyzo development team
#
# Yoton is distributed under the terms of the 2-Clause BSD License.
# The full license can be found in 'license.txt'.
""" Module yoton.channels.channels_pubsub
Defines the channel classes for the pub/sub pattern.
"""
i... |
<reponame>j-sulliman/acici
from .models import FvAEPg, Nxos_vlan_svi
import os
import pprint as pp
os.environ['DJANGO_SETTINGS_MODULE'] = 'nxos_aci.settings'
import django
django.setup()
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
... |
#Uses python3
import sys
class Dgraph:
"""
A class to represent a directed graph.
...
Attributes
----------
adj_list : list()
Vertices and their neighbors
prev : dict()
Vertex and value assigned at the beginning of the exploration
post : dict()
Vertex and valu... |
import decimal
import json as _json
import sys
import re
from _plotly_utils.optional_imports import get_module
from _plotly_utils.basevalidators import ImageUriValidator
PY36_OR_LATER = sys.version_info >= (3, 6)
class PlotlyJSONEncoder(_json.JSONEncoder):
"""
Meant to be passed as the `cls` kwarg to json.... |
<reponame>rakytap/QAC_prime_factoring
from dwave.cloud import Client
#client = Client.from_config(token='<KEY>')
#available_solvers = client.get_solvers()
#print( available_solvers )
# Manual embedding using th ehybrid solver
print(' ')
print( 'Composed sampler' )
from dimod import FixedVariableComposite, ExactSolver... |
<filename>sandiego.gov/businesses/bundle.py
'''
Example bundle that builds a single partition with a table of random numbers
'''
from ambry.bundle import BuildBundle
class Bundle(BuildBundle):
''' '''
def __init__(self,directory=None):
super(Bundle, self).__init__(directory)
@property
de... |
<reponame>mintproject/topoflow36
#-------------------------------------------------------------------
# Copyright (c) 2013-2020, <NAME>
#
# Apr 2013. New time interpolator class from/for emeli.py.
#
#-------------------------------------------------------------------
#
# class time_interp_data()
# __init__(... |
<filename>task_edit.py
import discord
import asyncio
import datetime
import re
import mysql.connector
import settings as setting
###############################################################################################################
# MANUAL IMPORT
#####################################################... |
from pyisim.entities.role import Role
from pyisim.exceptions import InvalidOptionError
from pyisim.entities import (
Activity,
Access,
OrganizationalContainer,
Person,
Service,
StaticRole,
DynamicRole,
ProvisioningPolicy,
Group,
Account,
)
from typing import List, TYPE_CHECKING
... |
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from controllers.main_controller import MainController
from models.watch_only_wallet import WatchOnlyWallet
from views.modal_view import Message, Modal
class AddressListView(QFrame):
controller: MainController
watch_only_walle... |
# coding=utf-8
# import libraries
import pandas as pd
import streamlit as st
from annoy import AnnoyIndex
import os
import math
import warnings
from unidecode import unidecode
warnings.simplefilter("ignore")
# variables
all_name = "All"
# read df
@st.cache(allow_output_mutation=True)
def load_data():
df = pd.re... |
#!/usr/bin/env python
# coding: utf-8
# # Image Classifier
# Creating a classifier model for images
# Author: <NAME> (Chrono-Logical)
# Requirements:
# 1. tensorflow - view documentation to install
# 2. keras - view documentation to install
#
# (If you have ananconda installed, you can simply use anaconda navigato... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 14 21:57:56 2021
@author: cui_hao
"""
# 转发网络
#server_crawl_repost.py
import pandas as pd
import os
#from datetime import datetime, timedelta
import random
import requests
from bs4 import BeautifulSoup
import re
import time
#cwd = "/mnt/sdb1/cuihao... |
from osgeo import gdal
import numpy as np
import os
from datetime import datetime
class Composite:
"""
Creates an averaged composite of any number of
individual single band rasters.
Developed for use within QGIS plugin, but can be
used as a standalone module, although the metadata
is currently specific to sea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Written in place of AboutBlocks in the Ruby Koans
#
# Note: Both blocks and generators use a yield keyword, but they behave
# a lot differently
#
from runner.koan import *
class AboutGenerators(Koan):
# def test_generating_values_on_the_fly(self):
# resu... |
<filename>warthog/config.py
# -*- coding: utf-8 -*-
#
# Warthog - Simple client for A10 load balancers
#
# Copyright 2014-2016 <NAME>
#
# Available under the MIT license. See LICENSE for details.
#
"""
warthog.config
~~~~~~~~~~~~~~
Load and parse configuration for a client from an INI-style file.
"""
import collecti... |
<gh_stars>1-10
# Copyright (c) 2011-2012 <NAME> and <NAME>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Character encoding detection library."""
import os
import sys
import struct
ENCODE_REPLACEMENT_CHARACTER ... |
<reponame>samarthdd/cdr-plugin-folder-to-folder
import json
from unittest import TestCase
import dotenv
import pytest
from cdr_plugin_folder_to_folder.configure.Configure_Env import Configure_Env
from osbot_utils.utils.Files import folder_exists, folder_delete_all
from os import environ,path,remove,rename
from unitt... |
"""
TODO: Not complete.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from itertools import count, cycle
from typing import Hashable, get_args
from EasyNN._abc import AutoDocumentation
from EasyNN.typing import Array1D, Command
import EasyNN.model.abc
class Optimizer(AutoDocumentation, AB... |
<reponame>domwillcode/home-assistant<filename>homeassistant/components/tplink/light.py
"""Support for TPLink lights."""
from datetime import timedelta
import logging
import time
from typing import Any, Dict, NamedTuple, Tuple, cast
from pyHS100 import SmartBulb, SmartDeviceException
from homeassistant.components.ligh... |
<filename>src/wizard/view/clsAddNewUnitPanel.py
import wx
from src.wizard.controller.frmRequiredValidator \
import RequiredValidator
from src.wizard.controller.frmRequiredComboValidator \
import RequiredComboValidator
class AddNewUnitPanelView ( wx.Panel ):
def __init__( self, parent ):
wx.Panel.__... |
<reponame>GudniNatan/GSKI-PA6<filename>ui/ui.py
import typing
from dataclasses import asdict, fields
from ui.menu import Menu
from my_dataclasses import Sport, Member, Plays, Group
class UI(object):
"""Class for quick UI shortcuts."""
def get_member(self):
print("Enter member info:")
name = i... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__a... |
from __future__ import division
import tensorflow as tf
class SSD_fcLoss:
def __init__(self,
alpha=1.0):
self.alpha = alpha
def smooth_L1_loss(self, y_true, y_pred):
absolute_loss = tf.abs(y_true - y_pred)
square_loss = 0.5 * (y_true - y_pred)**2
l1_loss = ... |
"""Django ORM models for Social Auth"""
import base64
import six
import sys
from django.db import transaction
from django.db.utils import IntegrityError
from social_core.storage import UserMixin, AssociationMixin, NonceMixin, \
CodeMixin, PartialMixin, BaseStorage
from seahub.base.accou... |
# @Time : 2021/08/01
# @Author : <NAME>
# @Email : <EMAIL>
r"""
GPT-2
################################################
Reference:
Radford et al. "Language models are unsupervised multitask".
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from textbox.model.abstract_generator import Seq... |
<reponame>kevinkit/polyproto<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 5 11:48:41 2020
@author: Kevin
"""
from polyproto.drawFunctions import drawRandomCircle,drawRandomLine,drawRandomEllipse,drawRandomRectangle,drawRandomPolygon
import numpy as np
import tensorflow as tf
if int(tf.__version__.s... |
<filename>tojs.py
#!/usr/bin/env python2
# Author: <NAME> <<EMAIL>>
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commerc... |
r"""Provides tools to parse and convert PEG grammars and expressions
Much of the syntax is pretty intuitive. `|` is for ordered choice, ` ` to
join expressions, `!` for negative lookahead, `&` for positive lookahead, `*`
for zero or more matches, `+` for one or more matches, `?` for an optional
match, `.` for any char... |
import os
import json
import logging
import jsonschema
from functools import wraps
from flask import current_app, jsonify, request, json
from werkzeug.exceptions import BadRequest, InternalServerError
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as st... |
from colorama import Fore
import re
from copy import deepcopy
from itertools import product
from ChessDRF.logic.board_and_controller import Controller
from ChessDRF.logic.figure import Figure
class Checker:
def __init__(self, game, board, test: bool):
self.game, self.board, self.test = game, board, test
... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: <NAME>
## Modified from: https://github.com/cbfinn/maml
## Tianjin University
## <EMAIL>
## Copyright (c) 2019
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of t... |
<reponame>wsutc/SEAS-purchase-system<gh_stars>0
from asyncio.windows_events import NULL
from django.db import models
from django.utils import timezone
from phonenumber_field.modelfields import PhoneNumberField
from pyexpat import model
###------------------------------- Item Setup -----------------------------------
... |
<filename>gym_unblockme/envs/unblockme_class.py<gh_stars>1-10
import numpy as np
# Unblock Me class
def get_example():
## Example matrix input
matrix_input = np.array(
[ [0, 2, 2, 0],
[1, 1, 0, 3],
[0, 0, 0, 3],
[2, 2, 0, 0]
])
target_input = [1,3]
# 0: Empty
# 1: Red Block
# 2: Horiz... |
<reponame>nitz14/hackaton
import multiprocessing
import time
from enum import Enum
import cv2
import keyboard
import numpy as np
import tensorflow as tf
class Key(Enum):
UP = "up"
DOWN = "down"
LEFT = "left"
RIGHT = "right"
class DetectorAPI:
def __init__(self, path_to_ckpt):
self.path_... |
"""Test LinearActuator state plotting functionality."""
# Standard imports
import argparse
import asyncio
import logging
# Local package imports
from lhrhost.dashboard.linear_actuator.plots import LinearActuatorPlotter as Plotter
from lhrhost.messaging import (
MessagingStack,
add_argparser_transport_selector,... |
<gh_stars>1-10
from datetime import timedelta
from prefect import task, Flow, unmapped
from prefect.engine.executors import DaskExecutor
import os
# the async db client pool used for the API is not serializable
from prefect.tasks.postgres import PostgresExecute, PostgresFetch
from db.schemas import observations, annot... |
<filename>tests/conftest.py<gh_stars>1-10
import pytest
@pytest.fixture(autouse=True)
def setup(fn_isolation):
"""
Isolation setup fixture.
This ensures that each test runs against the same base environment.
"""
pass
@pytest.fixture(scope="module")
def aave_lending_pool_v1(Contract):
"""
... |
<filename>symposion/sponsorship/views.py
from zipfile import ZipFile, ZIP_DEFLATED
import StringIO #as StringIO
import os
import json
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from django.contrib... |
import os
import numpy as np
import cv2
import torch
from PIL import Image
import torchvision
#from torchvision.transforms import ToTensor, ToPILImage
import random
import torch.nn as nn
import torch.nn.functional as F
import multiprocessing
import torch.optim as optim
import math
from functools import reduce
class ... |
"""
field_parser.py
parser for field data
"""
import os
import numpy as np
from collections import OrderedDict
from .parser import foam_comment, parseFoamDict, printdict
class foamField:
"""Openfoam dict class that support read/write openfoam dict file
especially for the file in the "0" folder
"""
... |
from __future__ import print_function
import tensorflow as tf
import argparse
import os
from six.moves import cPickle
from model import LineModel,ReversedModel,PostModel
from six import text_type
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpF... |
<filename>util/mx_tools.py
import numpy as np
from util.misc import assert_shape
def project_points(calib, points3d):
"""
Projects 3D points using a calibration matrix.
Parameters:
points3d: ndarray of shape (nPoints, 3)
"""
assert points3d.ndim == 2 and points3d.shape[1] == ... |
# -*- coding: utf-8 -*-
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from imutils import paths
import matplotlib.pypl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.