content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import tensorflow as tf
from tensorflow import keras
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
from tensorflow.keras.layers import Input, Lambda, Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.applications.inception_resnet_v2 import ... | python |
from django.test import TestCase
from ..models import Tag, Medium
from ..management.commands.add_tag_to_media import AssignTag
class RenameTagTest(TestCase):
fixtures = ['test_basic_data.yaml']
def setUp(self):
pass
def tearDown(self):
pass
def test_assign_tag_to_one_file(self):
... | python |
r"""
``$ mwtext preprocess_text -h``
::
Converts MediaWiki XML dumps to plaintext. One line per text chunk with
wiki markup and punctuation cleaned up. This utility is designed with word
embeddings in mind. Generally, you can expect one line per paragraph.
Usage:
preprocess_text (-h|--help)... | python |
# -*- coding: utf-8 -*-
# Transformers installation
import numpy as np
from transformers import GPT2LMHeadModel, GPT2TokenizerFast
from qtorch.quant import posit_quantize, float_quantize, configurable_table_quantize
device = 'cuda'
model_id = 'gpt2-large'
tokenizer = GPT2TokenizerFast.from_pretrained(model_id)
fro... | python |
# coding=utf-8
import tensorflow as tf
from tensorflow.python.ops import variable_scope
import numpy as np
import sys
import os
sys.path.append('..')
from tensor2tensor.models import transformer
from tensor2tensor.layers import common_layers
from tensor2tensor.utils import trainer_lib
from tensor2tensor.utils import r... | python |
#!/bin/python
import listify_circuits
listify_circuits.optimize_circuits(48, 'forward') | python |
"""
Register Me Silly
Repeatedly checks Drexel's Term Master Schedule for availability of class sections
Author: Anshul Kharbanda
Created: 9 - 21 - 2018
"""
from . import LabeledInput
from tkinter import *
class LabeledSpinbox(LabeledInput):
"""
Docstring for LabeledSpinbox
"""
def __init__(self, ma... | python |
#Detector Functions
# ------------------ Importing Libraries ------------------ #
import cv2
import os
import time
# ------------------ Importing Functions ------------------ #
from utils import open_thresholds, get_audio_list, reshape_image, input_output_details, make_prediction, get_dist_values, play_audio_record... | python |
"""
Xero Accounts API
"""
from .api_base import ApiBase
class Accounts(ApiBase):
"""
Class for Accounts API
"""
GET_ACCOUNTS = '/api.xro/2.0/accounts'
def get_all(self):
"""
Get all accounts
Returns:
List of all accounts
"""
return self._get... | python |
"""Defines a Tornado Server that consumes Kafka Event data for display"""
import logging
import logging.config
from pathlib import Path
import tornado.ioloop
import tornado.template
import tornado.web
# Import logging before models to ensure configuration is picked up
logging.config.fileConfig(f"{Path(__file__).paren... | python |
link_template="""\
<ul>
<li><a href="{langfam_code:}/overview/introduction.html">Introduction</a></li>
<li><a href="{langfam_code:}/overview/tokenization.html">Tokenization</a></li>
<li>Morphology
<ul>
<li><a href="{langfam_code:}/overview/morphology.html">General principles</a></... | python |
import tensorflow as tf
hello =tf.constant('hello')
sess=tf.Session()
print(sess.run(hello)) | python |
import os, numpy, sys
from numpy.linalg import norm
import isambard_dev
def get_SHparams(protein):
sequence = protein[0].sequence
residue_ids = [protein[0][i].id for i in range(len(protein[0].sequence))]
reference_axis = isambard_dev.analyse_protein.reference_axis_from_chains(protein)
residue_code = [sequence[n... | python |
# coding=utf-8
import toml
class Config(object):
def __init__(self, config_file_name):
dictionary = toml.load(config_file_name)
mqtt = Config.get_value_or_default(dictionary, "mqtt")
self.broker_address = Config.get_value_or_default(mqtt, "broker_address")
csv = Config.get_value_... | python |
#! /usr/bin/env python
import argparse
import itertools
import cv2
import numpy as np
if __name__=='__main__':
parser = argparse.ArgumentParser(
description='Arrange a number of images as a matrix.')
parser.add_argument('f', help='Output filename.')
parser.add_argument('w', type=int,
... | python |
#!/usr/bin/env python
import rospy
import numpy as np
from sensor_msgs.msg import Image, CompressedImage
import cv2
from cv_bridge import CvBridge, CvBridgeError
bridge = CvBridge()
image_pub = rospy.Publisher("output",Image,queue_size=1)
def callback(original_image):
np_arr = np.fromstring(original_image.data, ... | python |
import sys
filename=sys.argv[1]
def tableHTMLtoMatrix(filename):
file=open(filename,"r")
for i in range (2):
file.readline()
all_lines=file.readline().split("</td></tr></tbody></table></td></tr></thead>")
entries=all_lines[1].split('<tr align="center">')
dict,Enodes={},[]
for entry in entries[1:]:
entry=entry... | python |
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as col
import math
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
#import string
INTP_METHODS = ["bilinear", "bicubic"]
COLOR_SPECTRUMS = ["rainbow", "gray", "BuGn"]
FILE_NAMES = [ "aug_6_temp","Aug-2016... | python |
from brownie import accounts, web3, Wei, reverts, chain
from brownie.network.transaction import TransactionReceipt
from brownie.convert import to_address
import pytest
from brownie import Contract
from settings import *
# reset the chain after every test case
@pytest.fixture(autouse=True)
def isolation(fn_isolation):
... | python |
from __future__ import annotations
import re
from librespot.common import Utils
from librespot.metadata import SpotifyId
from librespot.metadata.PlayableId import PlayableId
class TrackId(PlayableId, SpotifyId):
_PATTERN = re.compile("spotify:track:(.{22})")
_hexId: str
def __init__(self, hex_id: str):... | python |
import torch
import numpy as np
from models_repo.massive_resnets import *
from models_repo.tiny_resnets import *
from models_repo.Middle_Logit_Generator import *
import argparse
from train_funcs import train_regular_ce,\
train_regular_middle_logits,\
train_kd_or_fitnets_2,\
stage_1_fitnet_train,\
dml_tr... | python |
from nlgen.cfg import read_cfg
EXAMPLE_NO_FEATURE = """
# example.nlcfg
SENTENCE -> PRONOUN VI NOUN;
VI -> VERB;
PRONOUN -> "I";
VERB -> "play";
NOUN -> "blackjack" | "poker";
""".strip()
def test_no_feature_example():
cfg = read_cfg(EXAMPLE_NO_FEATURE)
# permutations returns a generator.
# we use sets f... | python |
from typing import Optional
from pydantic import BaseModel, Field
class UserModel(BaseModel):
name: str = Field(...)
user_id: str = Field(...)
password: str = Field(...)
email: str = Field(...)
is_admin: bool = Field(...)
en_date: str = Field(...)
de_date: str = Field(...)
birth_date:... | python |
"""
Misc lr helper
"""
from torch.optim import Adam, Adamax
from .adamw import AdamW
def build_optimizer(model, opts):
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimi... | python |
# Generated by Django 3.0.5 on 2020-04-07 16:08
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('django_products', '0001_initial'),
]
operations = [
migra... | python |
import aiodocker
async def get_docker_images():
docker = aiodocker.Docker()
print("== Images ==")
for image in await docker.images.list():
tags = image["RepoTags"][0] if image["RepoTags"] else ""
print(image["Id"], tags)
async def pull(name: str):
docker = aiodocker.Docker()
awai... | python |
from train import d_conv_dim, g_conv_dim, z_size, model_name, img_size
import torch
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from train_class.load_model import Discriminator, Generator
from train_class.load_model import build_network
import torch.nn.functional as F
# load pretrained mod... | python |
import numpy as np
from core import Cache
from core import scipy_diffev
from core import notification
from core import preset
from core import track_and_update_metric
from visualization import display_iterations
def diffev_function_test(w, *args):
cache = args[0]
cache.w = w
residual = 0
for x, y in ... | python |
from stockpyle._base import BaseDictionaryStore
class ShoveStore(BaseDictionaryStore):
"""Represents a store that places all objects in a Shove (see http://pypi.python.org/pypi/shove)"""
def __init__(self, shove=None, shoveuri=None, polymorphic=False, lifetime_cb=None):
# TODO: deprecate 'sho... | python |
# 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... | python |
##########################################################
### Import Necessary Modules
import argparse #provides options at the command line
import sys #take command line arguments and uses it in the script
import gzip #allows gzipped files to be read
... | python |
# from .__S3File import s3_set_profile as set_profile
from .__S3File import s3_xlist as xlist
from .__S3File import s3_download as download
from .__S3File import s3_upload as upload
from .__S3File import s3_load as load
from .__S3File import s3_save as save
from .__S3File import s3_open as open
from .__S3File import s3... | python |
# Copyright 2017, 2018 Google, Inc. 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 l... | python |
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
class SEIRModelAge:
"""
This class implements a SEIR-like compartmental epidemic model
consisting of SEIR states plus death, and hospitalizations and age
structure.
In the diff eq modeling, these parameters a... | python |
#!/usr/bin/env python
from dissect.cstruct import cstruct, dumpstruct
import socket
import struct
protocol = cstruct()
protocol.load("""
enum AttackType : uint8 {
ATK_OPT_DPORT = 7,
ATK_OPT_DOMAIN = 8,
ATK_OPT_NUM_SOCKETS = 24,
};
struct AttackTarget {
DWORD ipv4;
BYTE netmask;
};
stru... | python |
from celery import task
import re
from django.utils import timezone
from backups.models import Backup, BackupRun, BackupSetOfRun, BackupNotification
import os
from django.conf import settings
from app.utils import DjangoLock
@task(ignore_result=True, queue="backups")
def run_backup(id, mode='hourly', backupsetpk=... | python |
import logging
from dicewars.client.ai_driver import BattleCommand, EndTurnCommand
class AI:
def __init__(self, player_name, board, players_order):
self.player_name = player_name
self.logger = logging.getLogger('AI')
def ai_turn(self, board, nb_moves_this_turn, nb_turns_this_game, time_left)... | python |
import random
from typing import List
from project.conf import get_configuration
from project.utils import ITEMS_SECTION
from project.effect import SideEffect, instantiate_side_effects
from project.interface import IItem, IHealingItem, IRecoveryItem, IEquipmentItem, ISideEffect
class Item(IItem):
def __init__(se... | python |
import RPi.GPIO as GPIO
import time
from libdw import pyrebase
#Database Set-Up
projectid = "cleanbean-9e2f5"
dburl = "https://" + projectid + ".firebaseio.com"
authdomain = projectid + ".firebaseapp.com"
apikey = "AIzaSyA6H-rDpfGJZcTqFhf69t3VYbbOzfUW0EM"
email = "kenzho_lim@mymail.sutd.edu.sg"
password = "123456"
c... | python |
"""Metaclass that overrides creating a new pipeline by wrapping methods with validators and setters."""
from functools import wraps
from rayml.exceptions import PipelineNotYetFittedError
from rayml.utils.base_meta import BaseMeta
class PipelineBaseMeta(BaseMeta):
"""Metaclass that overrides creating a new pipeli... | python |
from setuptools import setup
import glob
import os
import sys
import json
def package_files(package_dir, subdirectory):
# walk the input package_dir/subdirectory
# return a package_data list
paths = []
directory = os.path.join(package_dir, subdirectory)
for (path, directories, filenames) in os.walk... | python |
""" Advent of Code Day 2 - Bathroom Security"""
def get_code(start_pos, keypad, valid_pos):
"""Returns the code generated from instructions on specified keypad."""
pos = start_pos
code = ''
for line in lines:
for move in line:
if move == 'R':
next_pos = [pos[0], pos... | python |
import chanutils.reddit
from chanutils import get_json
from playitem import PlayItem, PlayItemList
_SEARCH_URL = "https://www.googleapis.com/youtube/v3/search"
_FEEDLIST = [
{'title':'Trending', 'url':'http://www.reddit.com/domain/youtube.com/top/.json'},
{'title':'Popular', 'url':'https://www.googleapis.com/yout... | python |
"""
Demo for chunk extraction in pyClarion.
Prerequisite: Understanding of the basics of pyClarion as discussed in the demo
`free_association.py`.
"""
from pyClarion import (
Structure, Construct,
agent, subsystem, buffer, flow_bt, flow_tb, features, chunks, terminus,
feature, updater,
Chunks, Asset... | python |
import numpy
from pylab import *
from scipy.interpolate import interp1d
d1,e1,ee1,f1,ef1=numpy.loadtxt("full.txt",unpack=True)
f1=-f1*31.6e-15
inds=argsort(d1)
d1=d1[inds]
f1=f1[inds]
d2,e2,ee2,f2,ef2=numpy.loadtxt("PEC.txt",unpack=True)
f2=-f2*31.6e-15
inds=argsort(d2)
d2=d2[inds]
f2=f2[inds]
d3,e3,ee3,f3,ef3=numpy... | python |
# _*_ coding:utf-8 _*_
# 练习函数调用。
def hello(name):
print "hello",name
pass
def manyHello():
for i in ["a","bobo","green"]:
hello(i)
pass
manyHello() | python |
from comex_stat.assets.models import (CGCE, CUCI, NCM, SH, AssetExportFacts,
AssetImportFacts, Country,
FederativeUnit, TradeBlocs,
Transportation, Urf)
from graphene_django.filter.fields import DjangoFilte... | python |
import numpy as np
import pandas as pd
np.random.seed(101)
df = pd.DataFrame(np.random.randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'. split())
print(df)
print(df[['W', 'Z']])
df['new'] = df['W'] + df['X']
print(df)
print(df.loc['A', 'X'])
print(df.loc['A'])
| python |
# coding: utf-8
"""
Prisma Cloud Compute API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.04.439
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_impor... | python |
import boto3
def post_handler(event, context):
sns= boto3.client('sns')
response = sns.publish(
TopicArn='arn:aws:sns:eu-west-1:538353771716:mytopic',
Message='testinglambda'
)
return{
"message" : "successful"
}
| python |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""Test... | python |
from __future__ import absolute_import
from django.core import mail
from sentry.utils.compat.mock import patch
from social_auth.models import UserSocialAuth
from sentry.exceptions import InvalidIdentity, PluginError
from sentry.models import (
Commit,
Deploy,
Integration,
LatestRepoReleaseEnvironment,... | python |
from src.models import Movie
from src.api import Api
from flask import request
from os import remove , listdir
from os.path import exists
class Movies(Api):
def __init__(self):
super().__init__()
def create_model(self):
self.model = Movie()
def sanitize_data(self):
data = [
... | python |
import unittest
from python_tuya_oittm.api_client import ApiClient
TEST_DEVICE_ID = '<enter a device id>'
TEST_ENCRYPTION_KEY = '<enter an encryption key>'
class TestTuyaApiClientIntegratedMethods(unittest.TestCase):
def test_get_metadata(self):
api_client = ApiClient()
data = api_client.get_met... | python |
# -*- coding: utf-8 -*-
"""Sentinel Tools API Class
Sentinel Tools - API Class
============================
Simple wrapper class for the Sentinel API that takes a Config object.
This file is a part of Sentinel Tools
Copyright 2020 - MET Norway (Machine Ocean Project)
Licensed under the Apache License, Version ... | python |
"""
plenum package metadata
"""
import os
import json
from typing import Tuple, List, Union
import collections.abc
from common.version import PlenumVersion, InvalidVersionError
VERSION_FILENAME = '__version__.json'
VERSION_FILE = os.path.join(
os.path.abspath(os.path.dirname(__file__)), VERSION_FILENAME)
def lo... | python |
from utils.orm.db import BaseModel
import httpx
import json
from sanic.log import logger as _logger
class DemoModel(BaseModel):
__tablename__ = 'demo_model'
async def demo_method(self):
print('demo method')
| python |
import json
from operator import itemgetter
from orchard_watch import query_db
from orchard_watch import respond
annoucement_schema = [
['annoucementid', 'longValue'],
['title', 'stringValue'],
['description', 'stringValue'],
['dateTime', 'stringValue'],
['email', 'stringValue']
]
def annoucement... | python |
# Copyright 2021 Adam Byerly. 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 law or agre... | python |
import copy
import logging
from random import uniform
import matplotlib.pyplot as plt
import numpy as np
from morpho import BrillouinZonePath as BZPath
from morpho import SymmetryPoint as SPoint
from scipy.signal import find_peaks
from fdtd import EFieldDetector, Grid, HFieldDetector, Material
from fdtd.boundaries im... | python |
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T
#
# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyx... | python |
import sys
sys.path.append('objection_engine/')
import objection_engine
# You can also import the components like this
from objection_engine.renderer import render_comment_list
from objection_engine.beans.comment import Comment
foo = [objection_engine.comment.Comment(), objection_engine.comment.Comment(text_content='Se... | python |
from bs4 import BeautifulSoup
from bs4 import NavigableString
import requests
import logging
import pandas as pd
import json
def get_cleaned_movie(movie_bs4):
"""Get a dictionary of a movie from its bs4 object"""
# parse directors and stars arrays
movie_directors_array = []
movie_stars_array = []
... | python |
from ...kernel import core
from ...kernel.core import VSkillModifier as V
from ...kernel.core import CharacterModifier as MDF
from ...character import characterKernel as ck
from functools import partial
class AuraWeaponBuilder():
def __init__(self, enhancer, skill_importance, enhance_importance):
self.Aura... | python |
import datetime
import decimal
import functools
from sqlalchemy.ext.associationproxy import _AssociationList
from geojson import dumps as _dumps
from geojson.codec import PyGFPEncoder
class GeoJSONEncoder(PyGFPEncoder):
# SQLAlchemy's Reflecting Tables mechanism uses decimal.Decimal
# for numeric columns an... | python |
# Generated by Django 3.1.7 on 2021-03-25 19:48
from django.db import migrations, models
import django.utils.timezone
import phonenumber_field.modelfields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... | python |
import logging
import allure
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from models.auth import AuthData
from pages.app import Application
logger = logging.getLogger("moodle")
@pytest.fixture(scope="s... | python |
class RouteException(Exception):
"""Raise when there is a general problem in a route"""
def __init__(self, message, status_code=500, data=None, *args):
self.message = message
self.status_code = status_code
self.data = data
super().__init__(message, status_code, data, *args)
cl... | python |
"""
class to extract domain-specific terms
for examples, 'JavaScript' in CS and 'limit' in math
"""
import logging
logger = logging.getLogger(__name__)
from DST.utils.TermUtil import filterTerm
class DomainTerm(object):
"""
class to extract domain-specific terms
"""
def __init__(self, maxTermsCount=3... | python |
"""Bare wrapper around IPOPT using numpy arrays and exception handling.
This module has an intermediate level of abstraction in the wrapping. Exception
handling is done in the callbacks and the error is signalled back to IPOPT. The
parameters in the callbacks are converted to ndarrays and the function inputs
are valid... | python |
import omemo
from omemo_backend_signal import BACKEND as SignalBackend
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tests")))
from deletingotpkpolicy import DeletingOTPKPolicy
from dr_chat import mainLoop
import example_data
try:
input = raw_input
except Na... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... | python |
import os
import numpy as np
from tqdm import tqdm
from stable_baselines import PPO2
from navrep.envs.navreptrainencodedenv import NavRepTrainEncodedEnv
from crowd_sim.envs.utils.info import Timeout, ReachGoal, Danger, Collision, CollisionOtherAgent
from navrep.tools.commonargs import parse_common_args
class NavRepCP... | python |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class DbusGlib(AutotoolsPackage):
"""dbus-glib package provides GLib interface for D-Bus API.""... | python |
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
class Meeting(models.Model):
title = models.CharField(
max_length=256,
verbose_name=_('Title'),
help_text=_('Title of the meeting')
)
... | python |
"""Test the sum_odd_numbers function."""
import pytest
def test_nth_even():
"""test the nth_even function."""
from get_nth_number import nth_even
test_value = nth_even(100)
assert test_value == 198 | python |
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2008, Yung-Yu Chen <yyc@solvcon.net>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyrigh... | python |
'''
HecTime and writing Irregular time-series safely
'''
import sys
from pydsstools.heclib.dss.HecDss import Open
from pydsstools.core import TimeSeriesContainer
from pydsstools.heclib.utils import HecTime, DssLastError
dss_file = "example.dss"
fid = Open(dss_file)
def decor(func):
def f(*arg,**kwargs):
... | python |
# -*- coding: utf-8 -*-
# @File : baseview.py
# @Date : 2021/2/25
# @Desc :
from rest_framework.generics import UpdateAPIView, DestroyAPIView
from rest_framework.serializers import Serializer
from rest_framework.viewsets import ModelViewSet
class FakeSerializer(Serializer):
pass
class BaseView(ModelViewSet, ... | python |
import math
import time
import pytest
from . import assert_javascript_entry
@pytest.mark.asyncio
async def test_types_and_values(bidi_session, current_session, inline, wait_for_event):
await bidi_session.session.subscribe(events=["log.entryAdded"])
on_entry_added = wait_for_event("log.entryAdded")
exp... | python |
"""
LibriParty Dataset creation by using official metadata.
Author
------
Samuele Cornell, 2020
Mirco Ravanelli, 2020
"""
import os
import sys
import speechbrain as sb
from hyperpyyaml import load_hyperpyyaml
from speechbrain.utils.data_utils import download_file
from local.create_mixtures_from_metadata import create... | python |
import simplejson as json
class PConf():
def __init__(self, filename="", schema={}):
"""initialize with a schema dictionary"""
if not filename or not isinstance(schema, dict):
return None
with open(filename, "r") as f:
self.conf = json.loads(f.read())
self.schema = schema
self.validate(self.conf, ... | python |
from flask import request
def get_locale():
rv = request.accept_languages.best_match(['zh', 'en'])
return rv or 'en'
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2022 askusay
#
# 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 b... | python |
from pyit.cop import ITokenCop, Cop
from pyit.offence import Offence
from token import *
class SpaceIndentationCop(Cop):
COP_CONFIG = {}
OPEN_BRACKETS = {
'(': LPAR,
'[': LSQB,
'{': LBRACE,
}
CLOSE_BRACKETS = {
'}': RBRACE,
']': RSQB,
')': RPAR,
}
... | python |
import sys
import pandas as pd
import matplotlib.pyplot as plt
sys.path.append('../minvime')
import estimator_classification as esti # The file ../minvime/estimator_classification.py
fprates = [0.0, 0.00001, 0.0001, 0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.015,
0.02,0.025, 0.03, 0.035, 0.04, 0.045, 0... | python |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. 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 requir... | python |
from flask import Flask, jsonify, request
from pymongo import MongoClient
from flask_script import Manager, Command, Shell
from flask_mail import Mail, Message
import nltk
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer
from nltk import word_tokenize, pos_tag
from tenseflow ... | python |
from mayan.apps.appearance.classes import Icon
icon_statistics = Icon(driver_name='fontawesome', symbol='chart-line')
icon_execute = Icon(driver_name='fontawesome', symbol='cog')
icon_namespace_details = Icon(driver_name='fontawesome', symbol='chart-line')
icon_namespace_list = Icon(driver_name='fontawesome', symbol='... | python |
from distutils.core import setup
# py2exe stuff
import py2exe, os
# find pythoncard resources to add as 'data_files'
pycard_resources=[]
for filename in os.listdir('.'):
if filename.find('.rsrc.')>-1:
pycard_resources+=[filename]
# includes for py2exe
includes=[]
for comp in ['button','multicolumnlist','s... | python |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import shutil
from pathlib import Path
from typing import Tuple
import subprocess
import tempfile
import pytest
from flexmock import flexmock
from packit.utils.commands import cwd
from packit.utils.repo import create_new_repo
from tests.s... | python |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... | python |
# -*- coding: utf-8 -*-
import unittest
import numpy as np
import six
import tensorflow as tf
from tfsnippet.bayes import Bernoulli
from tests.helper import TestCase
from tests.bayes.distributions._helper import (DistributionTestMixin,
BigNumberVerifyTestMixin,
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
" The code for the sc2 environment, maybe add some functions for the original pysc2 version "
# modified from AlphaStar pseudo-code
import numpy as np
from s2clientprotocol import sc2api_pb2 as sc_pb
from pysc2 import run_configs
from pysc2.lib import features
from pys... | python |
"""definition of problem instance
Author: Keisuke Okumura
Affiliation: TokyoTech & OSX
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Optional, Union
import numpy as np
from .obstacle import Obstacle, ObstacleSphere
from .static_objects import StaticObjects
@dat... | python |
# ptif_uploader script / webhook
# The developement has been resumed from uploader_jyhton
# Designed to use models from slide-atlas
__author__ = 'dhan'
#TODO: Extend the uploader for
# - Wrapping c++ image_uploader for ndpi and jp2 images
#noqua E501
import os
import sys
import argparse
# from celery import Celery... | python |
import warnings
import math
from typing import Optional, TypeVar
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from torch.nn import init
from torch.nn.parameter import Parameter
import torchshard as ts
class ParallelLoss(Module):
"""
... | python |
# Generated by nuclio.export.NuclioExporter
import os
import pandas as pd
import numpy as np
import scipy as sp
import pickle
import datetime
import v3io_frames as v3f
import matplotlib.pyplot as plt
from sklearn.preprocessing import KBinsDiscretizer
def to_observations(context, t, u, key):
t = (
t.app... | python |
from django.db import models
class Author(models.Model):
"""
An `Article` author
Attributes:
name (CharField):
Author name.
email (EmailField):
Author email.
"""
name = models.CharField(max_length=255)
email = models.EmailField()
class Article(models... | python |
allData = {'AK': {'Aleutians East': {'pop': 3141, 'tracts': 1},
'Aleutians West': {'pop': 5561, 'tracts': 2},
'Anchorage': {'pop': 291826, 'tracts': 55},
'Bethel': {'pop': 17013, 'tracts': 3},
'Bristol Bay': {'pop': 997, 'tracts': 1},
'Denali': {'pop': 1826, 'tracts': 1},
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.