content stringlengths 5 1.05M |
|---|
class MarkdownFormatException(Exception):
"""Raised if the passed in file is formatted incorrectly """
class ReformatInconsistentException(RuntimeError):
"""Raised if a reformated Markdown file would be reformatted differently
If you get this error, you should open a bug report.
"""
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import schnipsllogger
logger = schnipsllogger.getLogger(__name__)
class JsonStorage:
'''loads and saves persistent data as json to disk
'''
def __init__(self, filename, default):
'''
creates a persistent data link to a config file on disk
... |
# python3
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in wr... |
# ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
"""
@package ros_test_generator
@file setup.py
@author Anthony Remazeilles
@brief Standard ROS python package setup file
Copyright (C) 2020 Tecnalia Research and Innovation
Distributed under the Apache 2.0 license.
"""
from distutils.core import setup
from ... |
import tensorflow as tf
import numpy as np
#full_model = tf.keras.models.load_model("./trained_models/model_ToyCar.hdf5")
full_model = tf.keras.models.load_model("./trained_models/ad01.h5")
#print(full_model(np.random.randn(1, 640)))
models = [("full_model", full_model)]
import torch
import torch.nn as nn
from torch.... |
"""Adds config flow for Readme."""
from collections import OrderedDict
import voluptuous as vol
from homeassistant import config_entries
from .const import DOMAIN
@config_entries.HANDLERS.register(DOMAIN)
class ReadmeFlowHandler(config_entries.ConfigFlow):
"""Config flow for Readme."""
VERSION = 1
CONN... |
from django.urls import path, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'customers', views.CustomerView)
router.register(r'products', views.ProductView)
router.register(r'orders', views.OrderView)
router.register(r'order_items', views.OrderItemView... |
from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from user.serializers import UserSerializer, AuthTokenSerializer
class CreateUserView(generics.CreateAPIView):
"""Create a new user in the s... |
import configparser
from file_common import dir_utils
ini_path = dir_utils.get_app_root_path() + "properties/conf/"
print("=============== 配置文件根目录" + ini_path)
def get_config_by_name(config_name, cf: configparser.ConfigParser = None):
if not cf:
cf = configparser.ConfigParser()
# 读取配置文件
... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
"""
A convenience script used to drive each individual source generation script. Replace by
batch script GenerateNativeFormatSources.bat.
"""
import sys
import os
if __... |
# Lint as: python3
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
# coding: utf-8
import pprint
import six
from enum import Enum
class SubscriptionCreateRequest:
swagger_types = {
'component_configurations': 'list[SubscriptionComponentReferenceConfiguration]',
'currency': 'str',
'product': 'int',
'selected_components': 'list[SubscriptionPr... |
# 005 - Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them.
userName = input('First name: ')
print(f'\n{input("Last name: ")} {userName}') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from lib.stoneException import StoneException
class TestStoneException(unittest.TestCase):
"""Test case docstring."""
def setUp(self):
pass
def tearDown(self):
pass
def test_StoneException(self):
with self.assert... |
from django.contrib import admin
from .models import WebHook, GroupSignal, TimerSignal, FleetSignal, HRAppSignal, CharacterSignal, StateSignal, SRPSignal
from .app_settings import fleets_active, timers_active, hr_active, srp_active
class WebHookAdmin(admin.ModelAdmin):
list_display=('name', 'enabled')
admin.site... |
import argparse
import sys
from typing import List
from .main import WebEncoder
PROGRAM = "WebEncoder"
USAGE = "python -m web_encoder [ e | d ] data [ --no-compress ]"
DESCRIPTION = """
------------------------------------------------------------------------------
Description:
This module was created to encode and ... |
import os
import unittest
import numpy as np
#from scipy.integrate import quadrature as quadrature
from scipy.integrate import quad as quadrature
from statsmodels.nonparametric import kernels as sm_kernels
from hpbandster.optimizers.kde import kernels as hp_kernels
import ConfigSpace as CS
from pdb import set_t... |
"""Test DSS functions."""
import matplotlib.pyplot as plt
import numpy as np
import pytest
from numpy.testing import assert_allclose
from scipy import signal
from meegkit import dss
from meegkit.utils import demean, fold, rms, tscov, unfold
@pytest.mark.parametrize('n_bad_chans', [0, -1])
def test_dss0(n_bad_chans):... |
from sklearn.model_selection import cross_val_score
#Methods
from sklearn import naive_bayes
from sklearn.neighbors import KNeighborsClassifier
from sklearn import tree
from sklearn import svm
def classification(X, y):
decision_tree_method = tree.DecisionTreeClassifier(random_state=42)
svm_method = svm.... |
import argparse
import copy
import os
import torch
from copy import deepcopy
from torch import nn
from torchvision import datasets, transforms
import numpy as np
from models.LeNet5 import LeNet5
from eval.metrics import get_accuracy
from bitarray import bitarray
from models.YourNet import TeacherNet, YourNet
from matpl... |
import requests
from paymentcorner.auth import Auth
class Config(object):
_token = None
ENV_PROD = 'prod'
ENV_SANDBOX = 'sandbox'
ENV_URLS = {
ENV_PROD: 'http://sandboxapi.paymentcorner.com/',
ENV_SANDBOX: 'http://sandboxapi.paymentcorner.com/',
}
ENDPOINT_URLS = {
'... |
import threading
import time
import metaparticle_sync
def master_fn():
print('I am the master')
def lost_master_fn():
print('I lost the master')
el = metaparticle_sync.Election('test', master_fn, lost_master_fn)
def run():
time.sleep(30)
el.shutdown()
def main():
t = threading.Thread(None,... |
# -*- coding: utf-8 -*-
import os
from contextlib import contextmanager
import pytest
from beer_garden.local_plugins.env_help import (
expand_string,
has_env_var,
is_valid_name,
var_name,
)
@contextmanager
def mangle_env(updates):
env_orig = os.environ.copy()
os.environ.update(updates)
... |
import argparse
from logger import logging
def parse():
global args
parser = argparse.ArgumentParser()
parser.add_argument(
"-d",
"--debug",
help="Print lots of debugging statements",
action="store_const",
dest="loglevel",
const=logging.DEBUG,
defau... |
# 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 json
import argparse
import numpy as np
import itertools
import torch.utils.data
import torch.nn.functional as F
from torch.optim.lr_sch... |
from context import PyEDGAR
import unittest
class TestCIKTools(unittest.TestCase):
"""Test the `cik_tools` in the `util` module.
"""
def test_CIKMatch(self):
"""Test a unique match of the CIK.
This test uses the ticker 'AAPL', with the expected match returning
a CIK '0000320193'... |
# -*- coding: utf-8 -*-
from Controller.Utils import DBFRead, pyqt_pdb
from Controller.config import ENCODING_SUPPORT
from Controller.dbfread.exceptions import MissingMemoFile
import csv
def Tocsv(self, header=[], data=[]):
""" """
delimiter = ','
quotechar = '"'
quoting = csv.QUOTE_ALL
if heade... |
from face_recons import test
from face_recons import train
import argparse
parser = argparse.ArgumentParser(description = "Face Application - Command Line Interface")
parser.add_argument("--mode", default = False, help="Enable Command Line Interface", action='store')
parser.add_argument("--input", type=str, required=... |
# basic method to load to MiHIN
# should make nicer and add to loaders in django management
import os
import json
import questionnaire.utils
# used for one-off loads from IDE
tools_dir = 'tools'
this_dir = '.'
def handle(dir_name, files, resource_type):
client = questionnaire.utils.getFhirClient(questionnaire.ut... |
import sys
import pickle
import random
def Count_Alignment(file_path):
char_confusion = {}
# simulate insertion errors * -> c (use the previous char as key)
char_insert_confusion = {}
with open(file_path, "rb") as F:
X = pickle.load(F)
op_cnt = [0] * 3
for x in X:
#print(x)
so... |
"""
RiscEmu (c) 2021 Anton Lydike
SPDX-License-Identifier: MIT
This file holds Executable and LoadedExecutable classes as well as loading and some linking code.
FIXME: refactor this code into muliple files
"""
from dataclasses import dataclass, field
from typing import Dict, List, Tuple, Union, Optional
from .Excep... |
"""Super-classes of common datasets to extract id information per image."""
import torch
import torchvision
import random
from ..consts import * # import all mean/std constants
import torchvision.transforms as transforms
from PIL import Image, ImageFilter
import os
import glob
from torchvision.datasets.imagenet im... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-17 10:40
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('family', '0002_kid_avatar'),
]
... |
from typing import List, Dict, Tuple, Union, Any
from collections import defaultdict
import logging
from allennlp.semparse import util as semparse_util
from allennlp.semparse.domain_languages.domain_language import ExecutionError
from allennlp.semparse.contexts.table_question_knowledge_graph import MONTH_NUMBERS
from ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import wagtail.wagtailcore.fields
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0006_add_verbose_names'),
('wagtaildocs', '0003_a... |
"""
:mod:`zsl.utils.redis_helper`
-----------------------------
Helper module for working with redis.
.. moduleauthor:: Peter Morihladko
"""
from __future__ import unicode_literals
from builtins import object
from functools import partial
from future.utils import viewitems
from zsl import Config, inject
def red... |
from flask import request, jsonify
import flask
app = flask.Flask(__name__)
from confluent_kafka import Producer
p = Producer({'bootstrap.servers': 'localhost:9092'})
@app.route('/topic', methods=['POST'])
def topic():
d = request.get_json()
url = d.get('url')
if url is None:
return 'failure', 4... |
import json
import os
import sagemaker
from transformers import pipeline, AutoTokenizer, AutoModelForQuestionAnswering
def model_fn(model_dir):
session = sagemaker.Session()
bucket = os.getenv("MODEL_ASSETS_S3_BUCKET")
prefix = os.getenv("MODEL_ASSETS_S3_PREFIX")
session.download_data(path=model_dir, ... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
def genFib():
f1 = 0
f2 = 1
yield 0
yield 1
while True:
next = f1 + f2
yield next
f1 = f2
f2 = next
fib = genFib()
n = int(input('How many fibonacci numbers would you like? - '))
for i in range(n):
print(fib.__next__())
|
from typing import Union, Dict, Iterable, Tuple, cast, List, Optional, Generator, Mapping
from collections import defaultdict
from enum import Enum
import warnings
import bisect
import numpy as np
import sympy.ntheory
from qupulse._program.waveforms import Waveform, ConstantWaveform
from qupulse._program.volatile imp... |
"""
Provides a simple check based on lsof output to see if a path is in use by another process
"""
from time import time
from msort.log import getLogger
from msort.check import BaseCheck, CheckSkip
from msort.system import call_output
class InUseCheck(BaseCheck):
""" Check if the file being scanned is in use """
... |
#!/usr/bin/env python3
import threading
import multiprocessing
from abc import ABC, abstractmethod
class Daemon(ABC):
def __init__(self, event):
self.stop_event = event
self.daemon = True
def stop(self):
self.stop_event.set()
def stopped(self):
return self.stop_event.is_se... |
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import BlogIndexPluginModel, BlogRecentPluginModel, BlogPost
@plugin_pool.register_plugin
class BlogIndexPluginPublisher(CMSPluginBase):
model = BlogIndexPluginM... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import numpy as np
from scipy import integrate
import argparse
import numpy as np
import matplotlib as mpl
mpl.use('Agg') #silent mode
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
def thermo_i... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="simplepythonwer",
version="1.0.3",
author="Rob Smith",
author_email="robmsmt@gmail.com",
description="A small basic python implementation of WER (word error rate) and levenshtein",
lon... |
# -*- coding: utf-8 -*-
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
import cv2, os, dlib, sys
import numpy as np
from py_utils.face_utils import lib
from concurrent.futures import ProcessPoolExecutor
seed = 100
# Employ dlib to extract face area and landmark points
pwd = os.path.dirname(os.path.abspath(__file__))
front_face_detector = dlib.get_frontal_face_detector()
lmark_predictor =... |
from ex_109 import moeda
p = float(input('Digite o preço: R$'))
print(f' A metade de {moeda.moeda(p)} é {moeda.metade(p, True)}')
print(f' O dobro de {moeda.moeda(p)} é {moeda.dobro(p, True)}')
print(f' Aumentado 10%, temos {moeda.aumentar(p, 10, True)}')
print(f' Reduzindo 13%, temos {moeda.diminuir(p, 10, True)} ')
... |
"""
HDF5 database module.
Store the traces in an HDF5 array using pytables.
Implementation Notes
--------------------
This version supports arbitrary objects through ObjectAtom and VLArray
constructs. Ordinary numerical objects are stored in a Table. Each chain
is stored in an individual group called ``chain#``.
Add... |
def getAllCompaniesWithoutBusinessSummary():
return """SELECT uuid, long_name, sector, industry, address, city, state, country, phone, website, logo_url
FROM companies;"""
def getFullCompanyById(companyId):
return f"SELECT * FROM companies C WHERE C.uuid = '{companyId}';"
def getCompa... |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2016-2017 GiovanniMCMXCIX
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 us... |
import json
import unittest
from django.contrib.auth.models import User
from django.test import Client
def get_user(username):
try:
user = User.objects.get(username=username)
return user
except Exception:
user = User.objects.create_user(username, password='pass')
return user
... |
#!/usr/bin/env python
from pathlib import Path
from setuptools import setup
def get_version():
"""
retreive gars_field version information in version variable
(taken from pyproj)
"""
with open(Path("gars_field", "_version.py")) as vfh:
for line in vfh:
if line.find("__version_... |
import json
from collections.abc import Mapping
import pytest
import snug
import quiz
from .example import Dog, DogQuery
from .helpers import MockAsyncClient, MockClient
_ = quiz.SELECTOR
def token_auth(token):
return snug.header_adder({"Authorization": "token {}".format(token)})
class TestExecute:
def ... |
import pandas
from modin.engines.base.axis_partition import BaseAxisPartition
from modin.data_management.utils import split_result_of_axis_func_pandas
from .remote_partition import DaskRemotePartition
class DaskAxisPartition(BaseAxisPartition):
"""Dask implementation for Column and Row partitions"""
def __i... |
#! atenção obrigatorio instalar esta biblioteca
# ! pip install FPDF
#
from fpdf import FPDF
from PIL import Image
local_das_imagens='C:\\Users\\dougl\\Desktop\\projetos\python\\fotos-20210624T144130Z-001\\sapato\\'
class Imagem :
def localizar_imagens (nome_da_imagem,local_das_imagens, numero_de_image... |
# 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 use ... |
from django.urls import re_path
from collector import views
urlpatterns = [
re_path(r'^log/$', views.log, name='log'),
]
|
import numpy as np
import open3d as o3d
from src.FrameProcessor import process_frame
from src.metrics.CompositeBenchmark import CompositeBenchmark
from src.output.LabelPrinter import LabelPrinter
from src.output.PointCloudPrinter import PointCloudPrinter
from src.parser import create_input_parser, loaders, annotators,... |
from .default import * # noqa
# use postgresql so we test database transactions correctly
DATABASES["default"] = {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"HOST": "localhost",
"NAME": "oscar_docdata_sandbox",
"USER": "postgres",
"PASSWORD": "",
}
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import json
import typing as t
from dataclasses import dataclass, field
from hmalib.common.logging import get_logger
from hmalib.models import MatchMessage, Label
from hmalib.common.actioner_models import (
ActionLabel,
ThreatExchangeReact... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making GameAISDK available.
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
Copyright... |
from Transaction import Transaction
from Block import Block
from datetime import date
class Blockchain:
def __init__(self):
self.chain = [self.createGenisisBlock()]
self.difficulty = 2
self.pendingTransactions = []
self.miningReward = 100
def __str__(self):
chainHistory... |
import os
import pandas_gbq
from google.cloud import bigquery
import google.cloud
class pythonbq:
def __init__(self, bq_key_path, project_id, dialect='standard'):
self.credentials=google.oauth2.service_account.Credentials.from_service_account_file(bq_key_path)
self.project_id=project_id
sel... |
import dockertarpusher
import sys
def main():
if(len(sys.argv) < 3):
print("Arguments required: {REGISTRYURL} {TARPATH} [LOGIN] [PASSWORD] --noSslVerify")
print("Example: http://localhost:5000 tests/busybox.tar")
sys.exit(1)
url = sys.argv[1]
tarpath = sys.argv[2]
login = None
... |
# Copyright 2016 Yogesh Kshirsagar
# 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 require... |
"""
Test the GWT with initial concentration of 0 in the model domain and right-hand
side GWT boundary conditions. Versions 6.2.1 and earlier failed because of a
divide by zero error in IMS. This test confirms the fix implemented as part
of the version 6.2.2 release that addressed Issue 655.
"""
import os
import numpy... |
"""
Parses files containing urls to product pages
"""
def parse_file(file_path):
"""Parse file with lines: retailer url
Args:
file_path: The path to the url file
Returns:
dict: {'retailer1': 'url1', 'retailer2': 'url2'...}
"""
file = open(file_path)
retailer_dict = {}
f... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
import sys
import os
from onnxruntime.capi import _pybind_state as C
cl... |
import term, orientation, system, time, uos, json, badge
system.serialWarning()
term.header(True, "Services")
print("Loading...")
apps = uos.listdir('/lib')
services = []
for app in apps:
if "ledsrv.py" in uos.listdir('/lib/'+app):
services.append(app)
current = badge.nvs_get_str('splash', 'ledApp', None)
while T... |
from flask import Blueprint, request, render_template, \
flash, g, session, redirect, url_for, \
jsonify, make_response
from btsapi.modules.vendors.models import Vendor, VendorSchema
from btsapi.extensions import db
import datetime
from sqlalchemy import text
from flask_login import ... |
#74270524
"""[32m>> [39m[1m[42mTOTAL: tested 1 platforms, 0/142 tests failed[0m"""
#62977969
"""PASS Coding Rules :: List Actions :: Deactivate (6 tests)
Test file: src/test/js/coding-rules-page-quality-profile-facet.js
PASS coding-rules-page-quality-profile-facet (6 tests)
PASS Coding Rules :: Facets :: Language ... |
from .models.type_validator import TypeValidator
from .models.typed_list import TypedList
from utils.star_class_map import spectral_class_map, oddity_map
from config import NMSConfig
class StarClass(object):
config = TypeValidator(dict)
spectral_class_str = TypeValidator(str)
spectral_class = TypeValidat... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 Tier IV, 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/LIC... |
# import environ
from .settings import *
env = environ.Env(
DEBUG=(bool, False)) # false default
environ.Env.read_env(env_file='./.env')
ALLOWED_HOSTS += [
'kromm.info',
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
LOGGING['handlers']['file']['level'] = 'WARNING'
LOGGING['handlers']['file']['filename... |
app_set_debug_mode = 0 # 0 = off, 1 on, 2 in/out. 3 all
def weasel_act(valid_answer,response,runquery=True):
return None
|
""" Defines project for JPEG library """
Import("*")
from scons_symbian import *
Import("TARGET_NAME UID3 PACKAGE_NAME CAPABILITIES")
# Built as dll because needed by SDL and the application
target = TARGET_NAME
targettype = "dll"
libraries = C_LIBRARY + ['euser']
# Static libs
libraries += []
... |
class HydraNotFoundException(Exception):
pass
class MissingKeyParametersError(Exception):
pass
class HydraRunTimeoutException(Exception):
pass
class HydraError(Exception):
pass
|
import io
import os
import pandas as pd
import numpy as np
import subprocess
import sdi_utils.gensolution as gs
import sdi_utils.set_logging as slog
import sdi_utils.textfield_parser as tfp
import sdi_utils.tprogress as tp
import random
try:
api
except NameError:
class api:
class Message:
... |
from .data_augmentation_preprocessor import (
DataAugmentationPreprocessor,
DataAugmentationPreprocessor2,
DataAugmentationPreprocessor3,
) # NOQA
from .nchw_preprocessor import NCHWPreprocessor # NOQA
from .normalization_preprocessor import NormalizationPreprocessor # NOQA
from .sequential_preprocessor ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-12 04:30
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('newsletter_signup', '0001_i... |
import os
import os.path
def normpath(path):
"""Shorthand for os.path.normpath()
Normalizes path variables for your OS"""
return os.path.normpath(path)
def get_most_recent_file(path, key_string = "loss"):
"""File names must end with date formated as DD_MM_YYYY"""
for (dirpath, dirnames, filenames) in os... |
from emojitations.emojitypes import EmojiAnnotations
emoji = [
EmojiAnnotations(emoji='😀', codepoints=(128512,), name='față încântată', slug='față_încântată', annotations=frozenset({'încântare', 'față'})),
EmojiAnnotations(emoji='😁', codepoints=(128513,), name='față încântată cu ochi zâmbitori', slug='față_încânt... |
import argparse
import datetime
import gym
import numpy as np
import itertools
import torch
from sac import SAC
from cbsac import CBSAC
from torch.utils.tensorboard import SummaryWriter
import pickle
parser = argparse.ArgumentParser(description='PyTorch Soft Actor-Critic Args')
parser.add_argument('--env-name', defau... |
"""
Copyright (c) 2020 VMware, Inc.
This product is licensed to you under the Apache License, Version 2.0 (the "License").
You may not use this product except in compliance with the License.
This product may include a number of subcomponents with separate copyright notices
and license terms. Your use of these subcomp... |
import time
import re
import random
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from app.src.showdownai.exceptions import *
class Selenium():
BASE_URL="http://play.pokemonshowdown.com"
def __init__(self, url=B... |
"""
Functions for retrieving strings from files
"""
import os
def string_from_file(string, strip=True):
"""
Return an unaltered string or the contents of a file if the string
begins with @ and the rest of it points at a path.
If 'strip' is True, remove leading and trailing whitespace
(default be... |
from ape import plugins
from .explorer import Etherscan
NETWORKS = {
"ethereum": [
"mainnet",
"ropsten",
"rinkeby",
"kovan",
"goerli",
],
"fantom": [
"opera",
"testnet",
],
}
@plugins.register(plugins.ExplorerPlugin)
def explorers():
for ec... |
import numpy as np
from .common import Node
from .search import dfs
class findTrails(object):
"""
This class imlpemets a method to find trails
between nodeA and nodeB
"""
def __init__(self, rootNode, nodeA, nodeB, type='BN'):
"""
rootNode: rootnode of a graph
... |
import json
from datetime import datetime
from difflib import Differ
from sys import exit, stderr
from typing import Any, Dict, Iterator, List
from github import Github
from loguru import logger
from notifiers.logging import NotificationHandler
from utils import Utility
class SitRep:
"""
SitRep is an automa... |
import re
from datetime import datetime
from typing import List
import discord
from PIL import ImageColor
from d4dj_utils.master.card_master import CardMaster
from d4dj_utils.master.event_specific_bonus_master import EventSpecificBonusMaster
from d4dj_utils.master.skill_master import SkillMaster
from miyu_bot.bot.bot... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from orders.views import OrderSuccessView
urlpatterns = patterns('',
# Examples:
url(r'^(?P<id>\d+)/$', 'orders.views.auth_checkout', name='auth_checkout'),
url(r'^add_info/(?P<id>\d+)$', 'orders.views.add_info', name='add... |
from dataclasses import dataclass
from blacksheep.server.controllers import Controller, get
from app.configuration import config
@dataclass
class IndexModel:
development: str
url: str
class Welcome(Controller):
@get("/")
def index(self):
return self.view(model=IndexModel(str(config.show_err... |
# This code takes a movie title, searches for it in the json file and returns the year if it is present
import json
# Defining the search method
def search(search):
with open("Movies.json") as file:
data = json.loads(file.read())
# Iterating through the json array
for movie in data:
# Fin... |
import hashlib
import os
path='fileList.txt'
file_list = open(path,'w')
lists_files_old = []
lists_files_new = []
lists_files_new = os.listdir('new/')
lists_files_old = os.listdir('old/')
for filename in lists_files_new:
for filecompare in lists_files_old:
if filecompare == filename:
hasher ... |
from sabueso.tools.file_mmtf import download
|
from .DataDecoder import DataDecoder
import h5py
import logging
from pybind_nisar.products.readers import Base
import numpy as np
import pyre
import pybind_isce3 as isce
import re
# TODO some CSV logger
log = logging.getLogger("Raw")
PRODUCT = "RRSD"
def find_case_insensitive(group: h5py.Group, name: str) -> str:
... |
"""
LstGen generates php, python, go, or java code from PAP XML
"""
import re
import ast
from lxml import etree
# matches java-like long or double numbers, e.g.
# 123L or 3.12354D
NUMS_WITH_SIZE_RE = re.compile(r'([0-9]+)([LD]{1})')
J2PY_REPLACEMENTS = {
'new BigDecimal': 'BigDecimalConstructor',
'&&': 'and',
... |
import unittest
import numpy as np
import tensorflow as tf
import torch
from fastestimator.backend import squeeze
class TestSqueeze(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.test_np = np.array([[[[1], [2]]], [[[3], [3]]]])
cls.test_output_np = np.array([[1, 2], [3, 3]])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.