content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 12 10:02:12 2017
@author: alxgr
"""
import numpy as np
'''
################################################################################
'''
class GridDynamicSystem:
""" Create a discrete gird state-action space for a 2D continous dynamic system, one continuous... |
from setuptools import setup, find_packages
setup(
name='mlem',
version='0.0.1',
packages=["mlem"],
install_requires=['numpy', 'Pillow', 'scipy'],
tests_require=['pytest'],
license='MIT'
)
|
'''
@author: Dallas Fraser
@author: 2019-03-13
@organization: MLSB API
@summary: Tests all the advanced player lookup APIs
'''
from datetime import date
from api.helper import loads
from api.routes import Routes
from base64 import b64encode
from api.test.advanced.mock_league import MockLeague
from api.test.BaseTest imp... |
# -*- coding: utf-8 -*-
from . import abono
from . import cliente
from . import empleado
from . import instalacion
from . import material
from . import pago
from . import reserva
from . import tarjeta
from . import efectivo |
from .countries import COUNTRIES
from .regions import REGIONS
from .wmi import WMI
|
#
# to create executables for the filter and integrator
# type the following at the command line in this directory:
# python setup_py2exe.py py2exe
# executables will appear in the dist subdirectory
"""
Important note:
seeing errors in build with python setup.py py2exe?
move whole directory to a non-networked... |
from scanpy import read_h5ad
from ._io import read_10x_vdj, read_tracer, read_airr, read_bracer
from ._convert_anndata import from_ir_objs, to_ir_objs
from ..util import deprecated
from ._datastructures import IrCell, IrChain
@deprecated(
"Due to added BCR support, this function has been renamed "
"to `from_i... |
import kol.Error as Error
from kol.database import ItemDatabase
from kol.manager import PatternManager
from kol.request.GenericRequest import GenericRequest
class WokRequest(GenericRequest):
def __init__(self, session, itemid1, numMake=1):
super(WokRequest, self).__init__(session)
self.url = sessi... |
from bs4 import BeautifulSoup
import requests
import pandas as pd
from datetime import date, datetime
from sqlalchemy import create_engine
from psycopg2.errors import UniqueViolation
AZURE_IP_ADDRESS = 'stocks-db.postgres.database.azure.com'
AZURE_PORT = '5432'
AZURE_USERNAME = 'mattooren@stocks-db'
AZURE_PASSWORD = '... |
# 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 or agreed to in writing, software
# distributed under the... |
# Write tests for the hosts here.
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
import pytest
# Basic sanity check - the hosts file should be long to root
def test_hosts_file(host):
f = ... |
#!/usr/bin/env python
""" P4SC library: libMerge.py
This file provides fundamental functions of merging SFCs
Author: XiangChen, 2018.3.23
"""
import os
import sys
import argparse
import commands
import time
import datetime
import math
import psutil
from lcsSrc.lcs import *
from tableCmpSrc.genTopoOrder impor... |
#!/bin/env python3
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2012 Red Hat, Inc.
# Copyright 2013 IBM Corp.
# 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
#
# ... |
Ctx = {}
|
import json
import os
import shutil
from flask import current_app, jsonify
from flask_restful import Resource, marshal
from flask_restful.fields import Raw
import analysisweb_user
from analysisweb.api import db
from analysisweb_user.models import MetaDataException
class IDField(Raw):
def format(self, value):
... |
"""Расчет дивидендов и дохода начиная с определенной даты в пересчете на неделю, месяц и год."""
import pandas as pd
from poptimizer.data.views import indexes
from poptimizer.reports import pdf, pdf_middle
def get_investor_data(file_name: str, investor_name: str) -> pd.DataFrame:
"""Формирует DataFrame с вкладам... |
"""
File: bouncing_ball.py
Name: 賴珈汶
-------------------------
TODO: When the user clicks, the ball will fall and bounce.
While the ball reaches the right wall, the ball will come back to the initial site.
"""
from campy.graphics.gobjects import GOval
from campy.graphics.gwindow import GWindow
from campy.gui... |
from .BayesGau import *
|
from garage.regressors.product_regressor import ProductRegressor
__all__ = ["ProductRegressor"]
|
# -*- coding: UTF-8 -*-
"""
此脚本用于比较LAD线性回归和OLS线性回归
"""
import statsmodels.api as sm
from sklearn import linear_model
from statsmodels.regression.quantile_regression import QuantReg
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def generate_data():
"""
随机生成数据
"""
np.random.se... |
import pandas as pd
data_frame = {'name' : ['1'], 'email':['2'], 'phone':['3']}
df = pd.DataFrame(data=data_frame, index = ["we're on the way to success"])
print(df)
df.to_csv('contact_list_magic.csv')
#####
# import tkinter
# tkinter.messagebox.
# print(tkinter.ACTIVE) |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import time
import numpy as np
import os
import defenses
import data_utils as data
import cvxpy as cvx
import tensorflow as tf
import random
def poison_with_influence_... |
import logging
from typing import List, Any
import numpy as np
import pandas as pd
import pyskindose.constants as c
from .db_connect import db_connect
from .phantom_class import Phantom
logger = logging.getLogger(__name__)
def calculate_field_size(field_size_mode, data_parsed, data_norm):
"""Calculate X-ray fie... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import json
import string
# The paths need to be updated
visdial_train_data_file = 'visdial_0.9_train.json'
visdial_val... |
#! /usr/bin/python
#-*-coding:utf-8-*-
import urllib.request
import json
import sys, time
import curses
import console_view as cv
class fetch_coinmarket(cv.console_view):
def __init__(self, x = 0, y = 0, width = 80, height = 15, is_view = True):
cv.console_view.__init__(self, x, y, width, height, is_view)
... |
"""
Trait for a Slot meant to contain an object of a particular type
or having a particular interface (either a Traits interface or a
zope.interface).
"""
# The regular Instance class that comes with Traits will only check public
# methods on an object if that object is not a HasTraits object, which means
# we get ess... |
import os
import sys
import multiprocessing
import argparse
import torch
import torchvision.transforms as transforms
import numpy as np
import resnet_backbone
from bbox_tr import plot_bbox
from matplotlib import pyplot as plt
from PIL import Image
from TRD import TRD
from polynms import nms_poly
... |
from vpython import*
import numpy as np
import sys
sys.path.append(".")
import grow
from grow import *
import matplotlib.pyplot as plt
import time
scene2 = canvas(title='Simulation System', width=800, height=700, center=vector(0,0,0),
background=color.white)
#target
ball_position = ve... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# Invenio-Records-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Facets parameter interpreter API."""
from .base import ParamInterpreter
class FacetsParam(ParamI... |
import json
import os
import sys
import argparse
parser = argparse.ArgumentParser(description='Process JSON config file.')
parser.add_argument('target', type=str, help='NER or KB target to set')
args = parser.parse_args()
with open('config.json', 'r') as f:
config = json.load(f)
ner_entries = []
kb_entries = []
... |
#!/usr/bin/python -tOO
import sys
if len(sys.argv) != 4 :
print 'Usage : %s <interval (seconds)> <bsgfile> <tracefile> ' % sys.argv[0]
sys.exit(1)
stopat = 4752000
interval = int(sys.argv[1])
bsgfile = sys.argv[2]
trace = sys.argv[3]
keysize = 16
trustedgroupsize = 10
completionfile = '../complet... |
# this file shows how you could use load_extension to add games
# to your bot
# first, we make the bot
from discord.ext import commands
bot = commands.Bot("!") # Here, ! is the prefix
bot.load_extension("disgames")
# this would add a "Games" cog to your bot with all the games in it
|
from compas.datastructures import Network
from compas_plotters import Plotter
n = Network()
n.add_edge(1, 2)
n.add_edge(1, 3)
n.add_edge(1, 5)
n.add_edge(1, 7)
n.add_edge(2, 4)
n.add_edge(2, 6)
n.add_edge(2, 10)
n.add_edge(3, 6)
n.add_edge(3, 9)
n.add_edge(4, 8)
n.add_edge(5, 10)
print(n.summary())
visited = se... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import mock
import unittest
import undelete as D
class HDXConnectionTest(unittest.TestCase):
'''Unit tests for checking the connection with HDX.'''
def test_connection_with_hdx(self):
a = "xxx"
b = "yyy"
assert D.collectDatasetDataFromHDX(dataset_id = a, api... |
from __future__ import print_function, unicode_literals
import inspect
from rest_framework.exceptions import ValidationError
from rest_framework.fields import SkipField
from rest_framework.serializers import ListSerializer
from rest_framework.settings import api_settings
from rest_framework.utils import html
__all__... |
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, current_app
from . import settings
from .main import main
def create_app(settings_override=None):
# Create application.
app = Flask(
import_name=__name__,
static_folder=settings.STATIC_DIR,
temp... |
import random
import unittest
from numpy import random as np_random
from popgen import rhythm
class TestRhythm(unittest.TestCase):
def setUp(self):
self.rhythm = rhythm.Rhythm(120)
self.drum = self.rhythm.drum
def test_number_of_kicks_1(self):
random.seed(5)
assert self.rh... |
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import glob
import os
import sys
sys.path.insert(0,'..')
import intersection
width = 500
height = 500
rec_width = 200
rec_height = 300
first_x = 50
second_x = first_x + rec_width + 10
c... |
import os
from project import app, db
class BaseConfig:
"""Base configuration"""
TESTING = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
print('Running through config')
class DevelopmentConfig(BaseConfig):
"""Development configuration"""
SQLALCHEMY_DATABASE_URI = os.environ.get('POSTGRES_URL')... |
import pytest
#from ..basevalidators import AngleValidator
from _plotly_utils.basevalidators import AngleValidator
import numpy as np
# Fixtures
# --------
@pytest.fixture()
def validator():
return AngleValidator('prop', 'parent')
# Tests
# -----
# ### Test acceptance ###
@pytest.mark.parametrize('val', [0] + l... |
import pytest
from hypothesis import given
from hypothesis.strategies import text
from pytest import approx
from squiggle import transform
def test_A():
assert (
transform("A", method="yau")
== transform("a", method="yau")
== ([0, 0.5], [0, -(3 ** 0.5) / 2])
)
def test_T():
asse... |
"""
Inspired from APEX example at:
https://github.com/NVIDIA/apex/blob/master/examples/imagenet/main_amp.py#L256
and also from Timm loader at:
https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/loader.py
"""
from types import SimpleNamespace
from typing import Callable, List, Opti... |
#!/usr/bin/env python3
from os import cpu_count, getcwd, sched_setaffinity
from threading import Thread
from subprocess import Popen, DEVNULL, PIPE
# --------------------
# CONSTANTS
MAVEN = {
"CMD": ["./mvnw", "clean", "package", "-Dmaven.test.skip"],
"PROJECTS": [
["eureka", 8761, False],
... |
from PyQt4 import QtGui
class CaseModel(QtGui.QStandardItemModel):
def __init__(self, parent, dbConnection):
super(CaseModel, self).__init__(parent)
self.dbCon = dbConnection
def populate(self):
cur = self.dbCon.cursor()
cur.execute("SELECT NAME FROM FCASE")
rows = cur.fetchall()
for row in rows:
it... |
"""
@author: gsivaraman@anl.gov
"""
def plot_metric_write(train_size,err_list,r2_list, err_unscaled ,r2_unscaled , indlist, tag=None):
'''
Plot the metric/ write evolution history over the trial using this function
:param train_size: (list)
:param err_list: (list)
:param r2_list: (list)
:para... |
"""
蘋果日報分解測試
"""
# pylint: disable=duplicate-code
import unittest
import twnews.common
from twnews.soup import NewsSoup
#@unittest.skip
class TestAppleDaily(unittest.TestCase):
"""
蘋果日報分解測試
"""
def setUp(self):
self.dtf = '%Y-%m-%d %H:%M:%S'
def test_01_sample(self):
"""
... |
"""
Configures pytest
"""
import pytest
from snakeskin.protos.common.common_pb2 import (
BlockHeader,
BlockData,
BlockMetadata,
Block
)
from snakeskin.models.block import RawBlock
from snakeskin.models.transaction import DecodedTX
from snakeskin.models import User
@pytest.fixture()
def raw_block(... |
#!/usr/bin/python3 -m unittest
#
# test for devdax and hstore
#
# first run ...
# DAX_RESET=1 python3 ~/mcas/src/python/pymm/testing/devdax.py
#
# then re-run ..(as many times as you want, vars will increment)
#
# python3 ~/mcas/src/python/pymm/testing/devdax.py
#
import os
import unittest
import pymm
import numpy as n... |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('viewwork', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='menu',
options={'permissions': [('view_full_access', 'View full access'), ('view_read_only',... |
from django.contrib import admin
from .models import Language,Framework,Project,Academic,Profile
# Register your models here.
admin.site.register(Language)
admin.site.register(Framework)
admin.site.register(Project)
admin.site.register(Academic)
admin.site.register(Profile)
|
# -*- coding: utf-8 -*-
import numpy as np
from matplotlib import pyplot as plt
from shapely.geometry import Polygon
from shapely.geometry import LineString
import logging
from .alignSource import alignSource
from .alignDest import alignDest
from .types import alignType
from .types import transformationType
from .tra... |
from django.forms import widgets, MultiValueField, DateField
class DatePickerWidget(widgets.DateInput):
def __init__(self, attrs=None, format='%Y-%m-%d'):
# Use the HTML date widget
if attrs is not None:
attrs.update({'type': 'date'})
else:
attrs = {'type': 'date'}
... |
#!/usr/bin/env python
#
# Copyright 2016 Pinterest, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
from auditable.models import Auditable
from django.db import models
class ChargerRebates(Auditable):
organization = models.CharField(
blank=True,
null=True,
max_length=250,
unique=False
)
region = models.CharField(
blank=True,
null=True,
max_length... |
import os
import toml
from app import CONFIG
poetry_config = toml.load(f'{CONFIG.PROJECT_PATH}{os.path.sep}pyproject.toml')
with open(f'{CONFIG.PROJECT_PATH}{os.path.sep}requirements.txt') as f_stream:
requirements = f_stream.readlines()
all_dependencies = {
**poetry_config['tool']['poetry']['dependencies... |
import tensorflow as tf
def sigmoid_focal_loss(y_true, y_pred, alpha, gamma):
ce = tf.keras.backend.binary_crossentropy(target=y_true, output=y_pred, from_logits=True)
pred_prob = tf.math.sigmoid(y_pred)
p_t = (y_true * pred_prob) + ((1 - y_true) * (1 - pred_prob))
alpha_factor = y_true * alpha + (1 -... |
import json
from rest_framework import serializers
from authentication.models import AppUser
from .models import Note, Notebook
class NoteSerializer(serializers.ModelSerializer):
note_id = serializers.SlugField(source='id', read_only=True, required=False)
title = serializers.JSONField(required=False)
content =... |
## LANGUAGE: Python
## AUTHOR: Ananda Aguiar
## GITHUB: https://github.com/Anandinha
print("Hello World!!!")
|
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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... |
import os.path
import sys
import unittest
if '.' not in sys.path:
sys.path.append('.')
from openmdao.util.testutil import assert_rel_error
from openmdao.main.api import Assembly, set_as_top, Component
from openmdao.main.datatypes.api import Float
from axod_compn import AxodCompn
class temp_data(Component):
... |
from typing import NoReturn
from gloop.models.remote_player import RemotePlayer
class WebSocketPlayer(RemotePlayer):
def __init__(self, socket):
self.socket = socket
async def send(self, message: str) -> NoReturn:
await self.socket.send_json(message)
async def receive(self) -> str:
... |
"""
Copyright © 2021 William L Horvath II
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, soft... |
"""
Completes Hearthstone Card Lookup through comparing search queries to card names
"""
import copy
class Searcher:
def __init__(self, card_dict):
"""Initializes a Searcher object with a card dictionary provided
Args: card_dict(dict): Card dictionary with cards are separated
into sub dictionaries by set and... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import urllib2
import json
from pushbullet import Pushbullet
import profile
def sendNotification_Pushetta(message):
data = {
"body" : message,
"message_type" : "text/plain"
}
req = urllib2.Request('http://api.pushetta.com/api/pushes/{0}/'.format(profile.pushetta... |
"""
Placeholders
"""
# You're writing a program, and you don't know what your starting value for your 'initial' variable is yet. The program won't run if you leave it blank, but you don't want to forget you need it! Make a workaround.
|
class default_values:
def __init__(self):
pass
def default_equation():
return "3x-4x^2+1=1"
|
from typing import NamedTuple, List, Optional, Dict, Any
import numpy as np
import torch
from torch import nn as nn
from dpu_utils.ptutils import BaseComponent
class SampleDatapoint(NamedTuple):
input_features: List[float]
target_class: bool
class TensorizedDatapoint(NamedTuple):
input_... |
# -*- coding: utf-8 -*-
# https://tex2e.github.io/blog/crypto/point-of-elliptic-curve-over-GF
def quadratic_residue(a, p):
return pow(a, (p - 1) // 2, p) == 1
def f(x, a, b, p):
return (x**3 + a*x + b) % p
def calc_y(z, p):
res = z**3 % p
return res % p, -res % p
def disply_points(a, b, p):
poi... |
"""
MoinMoin - OpenID utils
@copyright: 2006, 2007 Johannes Berg <johannes@sipsolutions.net>
@license: GNU GPL, see COPYING for details.
"""
from random import randint
import time
from openid import oidutil
from openid.store.interface import OpenIDStore
from openid.association import Association
from ope... |
# This file is part of the bapsflib package, a Python toolkit for the
# BaPSF group at UCLA.
#
# http://plasma.physics.ucla.edu/
#
# Copyright 2017-2018 Erik T. Everson and contributors
#
# License: Standard 3-clause BSD; see "LICENSES/LICENSE.txt" for full
# license terms and contributor agreement.
"""
Module for th... |
A = AdemAlgebra(2)
A.compute_basis(20)
M = FDModule(A, "M", 0)
M.add_generator(0, "x0")
M.add_generator(2, "x2")
M.parse_action("Sq2 x0 = x2", None)
M.freeze()
r = ext.resolution.Resolver("Ceta", module=M)
Ceta = ResolverChannel(r, REPL)
await Ceta.setup_a()
Ceta.chart.sseq.initial_x_range = [0, 40]
Ceta.c... |
from data_structures.reverse_linked_list import *
# def test_import():
# assert reverse_list
|
#
# This class is automatically generated by mig. DO NOT EDIT THIS FILE.
# This class implements a Python interface to the 'Msg'
# message type.
#
import tinyos.message.Message
# The default size of this message type in bytes.
DEFAULT_MESSAGE_SIZE = 6
# The Active Message type associated with this message.
AM_TYPE =... |
from .facade import Client
|
#!/usr/bin/env python
from multiprocessing import Process
from time import sleep
import argparse
import http.server
import re
import socketserver
import socket
from scapy.all import *
def build_dns_response(query, name):
ip = query[IP]
udp = query[UDP]
dns = query[DNS]
dns_answer = DNSRR(rrname=nam... |
from django.urls import path
from .views import create_product_view, product_detail_view, edit_product_view
urlpatterns = [
path('add_product', create_product_view, name='add_product'),
path('product/<str:pk>/', product_detail_view, name='product_detail'),
path('product/<str:pk>/edit', edit_product_view, name='ed... |
import requests
from joblib import Parallel, delayed
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from .config import DATASET, SRC_FILES, n_jobs
from .data_reader import ManySStuBs4J
def download_file(session, url, save_path):
if not save_path.exists() or save_path.stat().st_si... |
# This file is part of the pyMOR project (https://www.pymor.org).
# Copyright 2013-2021 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)
from pymortests.base import runmodule
from pymortests.pickling import assert_picklable, assert_p... |
# coding: utf-8
# In[1]:
from song import measure_xdrift
# In[2]:
dp = '/hydrogen/song/star_spec/20161206/night/raw/'
# In[3]:
t = measure_xdrift.scan_files(dp)
# In[4]:
t2, fig = measure_xdrift.check_xdrift(t)
# In[5]:
fig
# In[6]:
fig.savefig('/hydrogen/song/figs/Xdrift_20161206.svg')
# In[7]:
t.... |
from __future__ import division, print_function
import time
from tfmini_library import TFmini
# create the sensor and give it a port and (optional) operating mode
tf = TFmini('/dev/ttyS0', mode=TFmini.STD_MODE)
#f=open("lidarDump.txt",a)
print('init done');
try:
print('='*25)
while True:
d = tf.read... |
# vim: sw=4:ts=4:et
#
# ACE proxy settings
import urllib.parse
import saq
def proxies():
"""Returns the current proxy settings pulled from the configuration.
Returns a dict in the following format. ::
{
'http': 'url',
'https': 'url'
}
"""
# set up the PROXY global dict (t... |
from .alphabet import Alphabet
from .beam_search import BeamSearcher
from .language_model import LanguageModel
|
from urllib.parse import urlencode
from seafileapi.utils import utf8lize
from seafileapi.files import SeafDir, SeafFile
from seafileapi.utils import raise_does_not_exist
class Repo(object):
"""
A seafile library
"""
def __init__(self, client, repo_id, repo_name,
encrypted, owner, perm)... |
import addict
from act.scio.plugins import threatactor_pattern
import os
import pytest
@pytest.mark.asyncio
async def test_threatactor_pattern() -> None:
""" test for plugins """
nlpdata = addict.Dict()
nlpdata.content = '''Lorem Ipsum Dirty Panda, APT1 APT-2, Apt 35, APT_46'''
plugin = threatacto... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import subprocess
import time
import argparse
proc = None
moving = True
def arg_conv(str):
if str.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif str.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Please enter a boolean v... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Main file of Altai. Execute it to use the application. """
# System imports
import sys
from os.path import expanduser
import PySide2.QtGui as QtGui
import PySide2.QtCore as QtCore
import PySide2.QtWidgets as QtWidgets
# Altai imports
from . import config
from .vented_b... |
import numpy as np
import pandas
import random
import re
import sys
from scipy.stats import pearsonr, spearmanr
# ausiliary functions
def buildSeriesByCategory(df, categories):
res = []
for cat in categories:
occ = df.loc[df["category"] == cat].shape[0]
res.append(occ)
res_series = pandas... |
from .expander import Expander # noqa
from .bundler import Bundler, create_scanner_factory_from_flavor # noqa
from .separator import Separator # noqa
from .resolver import ( # noqa
get_resolver,
get_resolver_from_filename, # backward compatibility
)
from .example import extract as extract_example # noqa
f... |
from pyacc.common import DFAState, DFA
class LALRDFAState(DFAState):
count = 0
class LALRDFA(DFA):
StateClass = LALRDFAState
def minimize(self):
pass |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 通过元类控制实例的创建
Desc :
"""
class NoInstances(type):
def __call__(self, *args, **kwargs):
raise TypeError("Can't instantiate directly")
# Example
class Spam(metaclass=NoInstances):
@staticmethod
def grok(x):
print('Spam.grok')
clas... |
import re
import csv
#with open('My_Games', 'r') as in_file:
# stripped = (line.strip() for line in in_file)
# lines = (line.split("\n\n") for line in stripped if line)
# with open('my_games.csv', 'w') as out_file:
# writer = csv.writer(out_file)
# writer.writerow(('Event', 'Date', 'White', 'Bla... |
import numpy as np
import torch
class YoloLoss(torch.nn.Module):
def __init__(self):
super(YoloLoss, self).__init__()
def forward(self, outputs, samp_bndbxs, y_true, anchors, scalez, cell_grid, ep, no_obj_thresh):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
... |
import unittest
from unittest import mock
from airfield.util import dependency_injection as di
from airfield.adapter.marathon import MarathonAdapter, InstanceState
from airfield.adapter.kv import KVAdapter
from airfield.util import logging
from tests.mocks.marathon_adapter import MarathonAdapterMock
from tests.mocks.kv... |
# 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... |
'''https://app.codesignal.com/interview-practice/task/6rE3maCQwrZS3Mm2H
Note: Your solution should have O(l1.length + l2.length) time
complexity, since this is what you will be asked to accomplish in an
interview.
Given two singly linked lists sorted in non-decreasing order, your
task is to merge them. In other words... |
# Copyright (c) 2013 Molly White
#
# 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, distrib... |
# Generated by Django 2.1.4 on 2019-02-13 05:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0005_alliance'),
]
operations = [
migrations.CreateModel(
name='CommentWords',
fields=[
('id... |
# -*- coding: utf-8 -*-
"""
@file
@brief Defines a set of modules for more machine learning or student projects.
"""
from ..installhelper.module_install import ModuleInstall
def cloud_set():
"""
modules introduced by students or needed for student projects, it requires the modules in set *extended*
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.